Compare commits

..
Author SHA1 Message Date
anand76 a8b5e4a6b7 Update HISTORY and version for 10.3.4 2025-06-17 16:36:32 -07:00
anand76 a59ca8d5da Change NewExternalTableFactory to return unique_ptr (#13705)
Summary:
Change NewExternalTableFactory API to return unique_ptr for use with the object registry.

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

Reviewed By: jaykorean

Differential Revision: D76827580

Pulled By: anand1976

fbshipit-source-id: 251ad0e498b62059b8417ff967ca74146de43e2f
2025-06-17 16:22:16 -07:00
Peter Dillinger 740240e3b1 Update version and HISTORY for 10.3.3 2025-06-04 19:14:23 -07:00
anand76 633631ac79 Fix iterator errors for CFs with disallow_memtable_writes (#13663)
Summary:
Iterator seek returns "SeekAndValidate() not implemented" error if the disallow_memtable_writes CF option is set along with paranoid_memory_checks. The fix is to sanitize the paranoid_memory_checks option to false, which should be safe since the memtable is guaranteed to be empty.

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

Test Plan: Update unit test in db_basic_test.cc

Reviewed By: pdillinger

Differential Revision: D75973515

Pulled By: anand1976

fbshipit-source-id: 3f381f19dcda72e3b78ee375f755fb4809c6b99c
2025-06-04 19:12:49 -07:00
Peter Dillinger e7d28965ce Clean up stale unreleased_history (not sure what happened) 2025-06-04 12:02:40 -07:00
Peter Dillinger c1b29dfe70 Fix tests broken by gtest upgrade (#13661)
Summary:
Some tests were failing due to apparent missing include of iomanip. I suspect this was from a gtest upgrade, because in open source, the include iomanip comes from gtest.h. To ensure we maintain compatibility with older gtest as well as the newer one, I pulled the include iomanip out of the in-repo gtest.h. Note that other places in gtest code only instantiate floating-point related templates with `float` and `double` types.

Also, to avoid `make format` being insanely slow on gtest.h, I've excluded third-party from the formatting check.

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

Test Plan: make check, internal CI, manually ensure formatting check works outside of third-party/

Reviewed By: jaykorean

Differential Revision: D75963897

Pulled By: pdillinger

fbshipit-source-id: ed5737dd456e74068185f1ac5d57046d7509df7a
2025-06-04 10:53:41 -07:00
Peter Dillinger a116092ee6 Fix XPRESS compression and enable in CI (#13649)
Summary:
Somehow this was previously not being tested in our Windows CI jobs so was accidentally broken in https://github.com/facebook/rocksdb/pull/13540  This fix will need to be backported to 10.3.

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

Test Plan: CI

Reviewed By: hx235

Differential Revision: D75655418

Pulled By: pdillinger

fbshipit-source-id: a56bb213270904a1b7a13b905c2cc1919116df1c
2025-05-30 09:31:36 -07:00
Jay Huh f90d89ea52 Update HISTORY and version for 10.3.2 2025-05-30 07:18:13 -07:00
Jay Huh cf149842a2 Include file_size in CompactionServiceOutputFile (#13620)
Summary:
Instead of using FileSystem::GetFileSize() for each CompactionOutputFile, use the file size that is being tracked internally as part of the output file's metadata. FileSize is now part of `CompactionServiceOutputFile` and serialized in the `CompactionServiceResult`

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

Test Plan:
Tested with logging Meta's internal offload Infra

```
./compaction_job_test
```

Reviewed By: jowlyzhang

Differential Revision: D75006961

Pulled By: jaykorean

fbshipit-source-id: 008f9dc22bd672746ac180380ada4188713a6b85
2025-05-30 07:12:47 -07:00
Changyu Bi f2d64341f5 Update HISTORY and version for 10.3.1 2025-05-22 20:34:07 -07:00
Changyu Bi 9c7f4946bb Update default value for large txn options (#13636)
Summary:
to make it easier to use 0 for disabled. And deprecate the use of txn db option `txn_commit_bypass_memtable_threshold`.

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

Test Plan: updated unit tests.

Reviewed By: jowlyzhang

Differential Revision: D75262136

Pulled By: cbi42

fbshipit-source-id: 9040e5a9c918c1d0906a2db4600cc012d2436b22
2025-05-22 20:27:57 -07:00
Changyu Bi 9885ced363 Enable large txn optimization by transaction write batch size (#13634)
Summary:
Larger key/values can cause memtable write to take longer time. Add new option `TransactionOptions::large_txn_commit_optimize_byte_threshold` that enables the optimization by transaction write batch size.

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

Test Plan:
- new unit test
- added option to stress test and ran stress test for some time: `python3 ./tools/db_crashtest.py --txn blackbox  --txn_write_policy=0 --commit_bypass_memtable_one_in=50 --test_batches_snapshots=0`

Reviewed By: jowlyzhang

Differential Revision: D75248126

Pulled By: cbi42

fbshipit-source-id: 9522db93457729ba60e4176f7d47f7c2c7778567
2025-05-22 20:27:49 -07:00
Peter Dillinger cda1e40498 Fix another format compatibility failure (#13628)
Summary:
Some specific old versions around RocksDB 2.5 would compress the metaindex and properties blocks. This hasn't been done since, probably because it interferes with the properties block indicating how to set up for decompression (so the reader can read those blocks before doing any decompression).

To fix backward compatibility, we establish a decompressor early if format_version indicates the file could come from a sufficiently old version.

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

Test Plan: local and CI runs of tools/check_format_compatible.sh. (I don't believe we need special code to set up a unit test for this case.)

Reviewed By: jowlyzhang

Differential Revision: D75107623

Pulled By: pdillinger

fbshipit-source-id: 97132b8c5e0602e8e27254a11386d866b23cb4f5
2025-05-21 09:29:12 -07:00
Peter Dillinger 0c3f08008a Update HISTORY for 10.3.0 release 2025-05-17 16:25:23 -07:00
90 changed files with 1821 additions and 4030 deletions

No files matched your search

+4 -4
View File
@@ -4,8 +4,8 @@ runs:
steps:
- name: Install Maven
run: |
wget --no-check-certificate https://dlcdn.apache.org/maven/maven-3/3.9.10/binaries/apache-maven-3.9.10-bin.tar.gz
tar zxf apache-maven-3.9.10-bin.tar.gz
echo "export M2_HOME=$(pwd)/apache-maven-3.9.10" >> $GITHUB_ENV
echo "$(pwd)/apache-maven-3.9.10/bin" >> $GITHUB_PATH
wget --no-check-certificate https://dlcdn.apache.org/maven/maven-3/3.9.6/binaries/apache-maven-3.9.6-bin.tar.gz
tar zxf apache-maven-3.9.6-bin.tar.gz
echo "export M2_HOME=$(pwd)/apache-maven-3.9.6" >> $GITHUB_ENV
echo "$(pwd)/apache-maven-3.9.6/bin" >> $GITHUB_PATH
shell: bash
-8
View File
@@ -52,14 +52,6 @@ jobs:
run: make check-buck-targets
- name: Simple source code checks
run: make check-sources
- name: Sanity check check_format_compatible.sh
run: |-
export TEST_TMPDIR=/dev/shm/rocksdb
rm -rf /dev/shm/rocksdb
mkdir /dev/shm/rocksdb
git reset --hard
git config --global --add safe.directory /__w/rocksdb/rocksdb
SANITY_CHECK=1 LONG_TEST=1 tools/check_format_compatible.sh
# ========================= Linux With Tests ======================== #
build-linux:
if: ${{ github.repository_owner == 'facebook' }}
-8
View File
@@ -249,7 +249,6 @@ cpp_library_wrapper(name="rocksdb_lib", srcs=[
"trace_replay/trace_record_result.cc",
"trace_replay/trace_replay.cc",
"util/async_file_reader.cc",
"util/auto_skip_compressor.cc",
"util/build_version.cc",
"util/cleanable.cc",
"util/coding.cc",
@@ -268,7 +267,6 @@ cpp_library_wrapper(name="rocksdb_lib", srcs=[
"util/random.cc",
"util/rate_limiter.cc",
"util/ribbon_config.cc",
"util/simple_mixed_compressor.cc",
"util/slice.cc",
"util/status.cc",
"util/stderr_logger.cc",
@@ -4711,12 +4709,6 @@ cpp_unittest_wrapper(name="compressed_secondary_cache_test",
extra_compiler_flags=[])
cpp_unittest_wrapper(name="compression_test",
srcs=["util/compression_test.cc"],
deps=[":rocksdb_test_lib"],
extra_compiler_flags=[])
cpp_unittest_wrapper(name="configurable_test",
srcs=["options/configurable_test.cc"],
deps=[":rocksdb_test_lib"],
-3
View File
@@ -874,13 +874,11 @@ set(SOURCES
trace_replay/trace_record.cc
trace_replay/trace_replay.cc
util/async_file_reader.cc
util/auto_skip_compressor.cc
util/cleanable.cc
util/coding.cc
util/compaction_job_stats_impl.cc
util/comparator.cc
util/compression.cc
util/simple_mixed_compressor.cc
util/compression_context_cache.cc
util/concurrent_task_limiter_impl.cc
util/crc32c.cc
@@ -1458,7 +1456,6 @@ if(WITH_TESTS)
util/autovector_test.cc
util/bloom_test.cc
util/coding_test.cc
util/compression_test.cc
util/crc32c_test.cc
util/defer_test.cc
util/dynamic_bloom_test.cc
+21
View File
@@ -1,6 +1,27 @@
# Rocksdb Change Log
> NOTE: Entries for next release do not go here. Follow instructions in `unreleased_history/README.txt`
## 10.3.4 (06/17/2025)
### Public API Changes
* Change NewExternalTableFactory to return a unique_ptr instead of shared_ptr.
## 10.3.3 (06/04/2025)
### Bug Fixes
* Fix iterator operations returning NotImplemented status if disallow_memtable_writes and paranoid_memory_checks CF options are both set.
* Fix Windows-only XPRESS compression
* Fix newer gtest compatibility
## 10.3.2 (05/30/2025)
### Behavior Changes
* In Remote Compactions, instead of using FileSystem::GetFileSize() for each CompactionOutputFile, use the file size that is being tracked internally as part of the output file's metadata. FileSize is now part of CompactionServiceOutputFile and serialized in the CompactionServiceResult
## 10.3.1 (05/22/2025)
### New Features
* Add new experimental `TransactionOptions::large_txn_commit_optimize_byte_threshold` to enable optimizations for large transaction commit by transaction batch data size.
### Behavior Changes
* `TransactionOptions::large_txn_commit_optimize_threshold` now has default value 0 for disabled. `TransactionDBOptions::txn_commit_bypass_memtable_threshold` now has no effect on transactions.
## 10.3.0 (05/17/2025)
### New Features
* Add new experimental `CompactionOptionsFIFO::allow_trivial_copy_when_change_temperature` along with `CompactionOptionsFIFO::trivial_copy_buffer_size` to allow optimizing FIFO compactions with tiering when kChangeTemperature to move files from source tier FileSystem to another tier FileSystem via trivial and direct copying raw sst file instead of reading thru the content of the SST file then rebuilding the table files.
+5 -10
View File
@@ -1491,9 +1491,6 @@ db_test: $(OBJ_DIR)/db/db_test.o $(TEST_LIBRARY) $(LIBRARY)
db_test2: $(OBJ_DIR)/db/db_test2.o $(TEST_LIBRARY) $(LIBRARY)
$(AM_LINK)
compression_test: $(OBJ_DIR)/util/compression_test.o $(TEST_LIBRARY) $(LIBRARY)
$(AM_LINK)
db_logical_block_size_cache_test: $(OBJ_DIR)/db/db_logical_block_size_cache_test.o $(TEST_LIBRARY) $(LIBRARY)
$(AM_LINK)
@@ -2492,13 +2489,11 @@ checkout_folly:
fi
@# Pin to a particular version for public CI, so that PR authors don't
@# need to worry about folly breaking our integration. Update periodically
cd third-party/folly && git reset --hard d17bf897cb5bbf8f07b122a614e8cffdc38edcde
@# Apparently missing include
perl -pi -e 's/(#include <atomic>)/$$1\n#include <cstring>/' third-party/folly/folly/lang/Exception.h
@# Warning-as-error on memcpy
perl -pi -e 's/memcpy.&ptr/memcpy((void*)&ptr/' third-party/folly/folly/lang/Exception.cpp
@# const mismatch
perl -pi -e 's/: environ/: (const char**)(environ)/' third-party/folly/folly/Subprocess.cpp
cd third-party/folly && git reset --hard 8e8186f67de7a23d3a07366946b1617343927d84
@# NOTE: this hack is required for clang in some cases
perl -pi -e 's/int rv = syscall/int rv = (int)syscall/' third-party/folly/folly/detail/Futex.cpp
@# NOTE: this hack is required for gcc in some cases
perl -pi -e 's/(__has_include.<experimental.memory_resource>.)/__cpp_rtti && $$1/' third-party/folly/folly/memory/MemoryResource.h
@# NOTE: boost source will be needed for any build including `USE_FOLLY_LITE` builds as those depend on boost headers
cd third-party/folly && $(PYTHON) build/fbcode_builder/getdeps.py fetch boost
-10
View File
@@ -3748,16 +3748,6 @@ uint32_t rocksdb_options_get_memtable_op_scan_flush_trigger(
return opt->rep.memtable_op_scan_flush_trigger;
}
void rocksdb_options_set_memtable_avg_op_scan_flush_trigger(
rocksdb_options_t* opt, uint32_t n) {
opt->rep.memtable_avg_op_scan_flush_trigger = n;
}
uint32_t rocksdb_options_get_memtable_avg_op_scan_flush_trigger(
rocksdb_options_t* opt) {
return opt->rep.memtable_avg_op_scan_flush_trigger;
}
void rocksdb_options_enable_statistics(rocksdb_options_t* opt) {
opt->rep.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
}
-10
View File
@@ -2220,10 +2220,6 @@ int main(int argc, char** argv) {
CheckCondition(100 ==
rocksdb_options_get_memtable_op_scan_flush_trigger(o));
rocksdb_options_set_memtable_avg_op_scan_flush_trigger(o, 150);
CheckCondition(150 ==
rocksdb_options_get_memtable_avg_op_scan_flush_trigger(o));
rocksdb_options_set_ttl(o, 5000);
CheckCondition(5000 == rocksdb_options_get_ttl(o));
@@ -2667,12 +2663,6 @@ int main(int argc, char** argv) {
CheckCondition(100 ==
rocksdb_options_get_memtable_op_scan_flush_trigger(o));
rocksdb_options_set_memtable_avg_op_scan_flush_trigger(copy, 900);
CheckCondition(
900 == rocksdb_options_get_memtable_avg_op_scan_flush_trigger(copy));
CheckCondition(150 ==
rocksdb_options_get_memtable_avg_op_scan_flush_trigger(o));
rocksdb_options_set_ttl(copy, 8000);
CheckCondition(8000 == rocksdb_options_get_ttl(copy));
CheckCondition(5000 == rocksdb_options_get_ttl(o));
+8 -18
View File
@@ -448,21 +448,13 @@ ColumnFamilyOptions SanitizeCfOptions(const ImmutableDBOptions& db_options,
result.preclude_last_level_data_seconds = 0;
}
if (read_only) {
if (result.memtable_op_scan_flush_trigger) {
ROCKS_LOG_WARN(db_options.info_log.get(),
"option memtable_op_scan_flush_trigger is sanitized to "
"0(disabled) for read only DB.");
result.memtable_op_scan_flush_trigger = 0;
}
if (result.memtable_avg_op_scan_flush_trigger) {
ROCKS_LOG_WARN(
db_options.info_log.get(),
"option memtable_avg_op_scan_flush_trigger is sanitized to "
"0(disabled) for read only DB.");
result.memtable_avg_op_scan_flush_trigger = 0;
}
if (read_only && result.memtable_op_scan_flush_trigger != 0) {
ROCKS_LOG_WARN(db_options.info_log.get(),
"option memtable_op_scan_flush_trigger is sanitized to "
"0(disabled) for read only DB.");
result.memtable_op_scan_flush_trigger = 0;
}
return result;
}
@@ -1217,12 +1209,10 @@ Compaction* ColumnFamilyData::PickCompaction(
const MutableCFOptions& mutable_options,
const MutableDBOptions& mutable_db_options,
const std::vector<SequenceNumber>& existing_snapshots,
const SnapshotChecker* snapshot_checker, LogBuffer* log_buffer,
bool require_max_output_level) {
const SnapshotChecker* snapshot_checker, LogBuffer* log_buffer) {
auto* result = compaction_picker_->PickCompaction(
GetName(), mutable_options, mutable_db_options, existing_snapshots,
snapshot_checker, current_->storage_info(), log_buffer,
require_max_output_level);
snapshot_checker, current_->storage_info(), log_buffer);
if (result != nullptr) {
result->FinalizeInputInfo(current_);
}
+1 -2
View File
@@ -424,8 +424,7 @@ class ColumnFamilyData {
const MutableCFOptions& mutable_options,
const MutableDBOptions& mutable_db_options,
const std::vector<SequenceNumber>& existing_snapshots,
const SnapshotChecker* snapshot_checker, LogBuffer* log_buffer,
bool require_max_output_level = false);
const SnapshotChecker* snapshot_checker, LogBuffer* log_buffer);
// Check if the passed range overlap with any running compactions.
// REQUIRES: DB mutex held
-5
View File
@@ -463,11 +463,6 @@ class Compaction {
const int start_level,
const int output_level);
static bool OutputToNonZeroMaxOutputLevel(int output_level,
int max_output_level) {
return output_level > 0 && output_level == max_output_level;
}
// If some data cannot be safely migrated "up" the LSM tree due to a change
// in the preclude_last_level_data_seconds setting, this indicates a sequence
// number for the newest data that must be kept in the last level.
+28 -27
View File
@@ -133,7 +133,10 @@ CompactionJob::CompactionJob(
LogBuffer* log_buffer, FSDirectory* db_directory,
FSDirectory* output_directory, FSDirectory* blob_output_directory,
Statistics* stats, InstrumentedMutex* db_mutex,
ErrorHandler* db_error_handler, JobContext* job_context,
ErrorHandler* db_error_handler,
std::vector<SequenceNumber> existing_snapshots,
SequenceNumber earliest_write_conflict_snapshot,
const SnapshotChecker* snapshot_checker, JobContext* job_context,
std::shared_ptr<Cache> table_cache, EventLogger* event_logger,
bool paranoid_file_checks, bool measure_io_stats, const std::string& dbname,
CompactionJobStats* compaction_job_stats, Env::Priority thread_pri,
@@ -170,7 +173,12 @@ CompactionJob::CompactionJob(
blob_output_directory_(blob_output_directory),
db_mutex_(db_mutex),
db_error_handler_(db_error_handler),
earliest_snapshot_(job_context->GetEarliestSnapshotSequence()),
existing_snapshots_(std::move(existing_snapshots)),
earliest_snapshot_(existing_snapshots_.empty()
? kMaxSequenceNumber
: existing_snapshots_.at(0)),
earliest_write_conflict_snapshot_(earliest_write_conflict_snapshot),
snapshot_checker_(snapshot_checker),
job_context_(job_context),
table_cache_(std::move(table_cache)),
event_logger_(event_logger),
@@ -185,7 +193,6 @@ CompactionJob::CompactionJob(
bg_bottom_compaction_scheduled_(bg_bottom_compaction_scheduled) {
assert(job_stats_ != nullptr);
assert(log_buffer_ != nullptr);
assert(job_context->snapshot_context_initialized);
const auto* cfd = compact_->compaction->column_family_data();
ThreadStatusUtil::SetEnableTracking(db_options_.enable_thread_tracking);
@@ -217,9 +224,10 @@ void CompactionJob::ReportStartedCompaction(Compaction* compaction) {
ThreadStatus::COMPACTION_PROP_FLAGS,
compaction->is_manual_compaction() +
(compaction->deletion_compaction() << 1));
auto total_input_bytes = compaction->CalculateTotalInputSize();
ThreadStatusUtil::SetThreadOperationProperty(
ThreadStatus::COMPACTION_TOTAL_INPUT_BYTES, total_input_bytes);
ThreadStatus::COMPACTION_TOTAL_INPUT_BYTES,
compaction->CalculateTotalInputSize());
IOSTATS_RESET(bytes_written);
IOSTATS_RESET(bytes_read);
@@ -234,16 +242,6 @@ void CompactionJob::ReportStartedCompaction(Compaction* compaction) {
job_stats_->is_manual_compaction = compaction->is_manual_compaction();
job_stats_->is_full_compaction = compaction->is_full_compaction();
// populate compaction stats num_input_files and total_num_of_bytes
size_t num_input_files = 0;
for (int input_level = 0;
input_level < static_cast<int>(compaction->num_input_levels());
++input_level) {
const LevelFilesBrief* flevel = compaction->input_levels(input_level);
num_input_files += flevel->num_files;
}
job_stats_->CompactionJobStats::num_input_files = num_input_files;
job_stats_->total_input_bytes = total_input_bytes;
}
void CompactionJob::Prepare(
@@ -839,7 +837,8 @@ Status CompactionJob::Run() {
}
ReleaseSubcompactionResources();
TEST_SYNC_POINT("CompactionJob::ReleaseSubcompactionResources");
TEST_SYNC_POINT("CompactionJob::ReleaseSubcompactionResources:0");
TEST_SYNC_POINT("CompactionJob::ReleaseSubcompactionResources:1");
for (const auto& state : compact_->sub_compact_states) {
for (const auto& output : state.GetOutputs()) {
@@ -1184,7 +1183,7 @@ void CompactionJob::ProcessKeyValueCompaction(SubcompactionState* sub_compact) {
// creation across both CompactionJob and CompactionServiceCompactionJob
sub_compact->AssignRangeDelAggregator(
std::make_unique<CompactionRangeDelAggregator>(
&cfd->internal_comparator(), job_context_->snapshot_seqs,
&cfd->internal_comparator(), existing_snapshots_,
&full_history_ts_low_, &trim_ts_));
// TODO: since we already use C++17, should use
@@ -1325,8 +1324,8 @@ void CompactionJob::ProcessKeyValueCompaction(SubcompactionState* sub_compact) {
env_, cfd->user_comparator(), cfd->ioptions().merge_operator.get(),
compaction_filter, db_options_.info_log.get(),
false /* internal key corruption is expected */,
job_context_->GetLatestSnapshotSequence(), job_context_->snapshot_checker,
compact_->compaction->level(), db_options_.stats);
existing_snapshots_.empty() ? 0 : existing_snapshots_.back(),
snapshot_checker_, compact_->compaction->level(), db_options_.stats);
const auto& mutable_cf_options =
sub_compact->compaction->mutable_cf_options();
@@ -1362,10 +1361,9 @@ void CompactionJob::ProcessKeyValueCompaction(SubcompactionState* sub_compact) {
auto c_iter = std::make_unique<CompactionIterator>(
input, cfd->user_comparator(), &merge, versions_->LastSequence(),
&(job_context_->snapshot_seqs), earliest_snapshot_,
job_context_->earliest_write_conflict_snapshot, job_snapshot_seq,
job_context_->snapshot_checker, env_,
ShouldReportDetailedTime(env_, stats_),
&existing_snapshots_, earliest_snapshot_,
earliest_write_conflict_snapshot_, job_snapshot_seq, snapshot_checker_,
env_, ShouldReportDetailedTime(env_, stats_),
/*expect_valid_internal_key=*/true, sub_compact->RangeDelAgg(),
blob_file_builder.get(), db_options_.allow_data_in_errors,
db_options_.enforce_single_del_contracts, manual_compaction_canceled_,
@@ -1654,6 +1652,10 @@ Status CompactionJob::FinishCompactionOutputFile(
Status s = input_status;
// Add range tombstones
auto earliest_snapshot = kMaxSequenceNumber;
if (existing_snapshots_.size() > 0) {
earliest_snapshot = existing_snapshots_[0];
}
if (s.ok()) {
// Inclusive lower bound, exclusive upper bound
std::pair<SequenceNumber, SequenceNumber> keep_seqno_range{
@@ -1679,7 +1681,7 @@ Status CompactionJob::FinishCompactionOutputFile(
s = outputs.AddRangeDels(*sub_compact->RangeDelAgg(), comp_start_user_key,
comp_end_user_key, range_del_out_stats,
bottommost_level_, cfd->internal_comparator(),
earliest_snapshot_, keep_seqno_range,
earliest_snapshot, keep_seqno_range,
next_table_min_key, full_history_ts_low_);
}
RecordDroppedKeys(range_del_out_stats, &sub_compact->compaction_job_stats);
@@ -2311,10 +2313,9 @@ void CompactionJob::LogCompaction() {
}
stream << "score" << compaction->score() << "input_data_size"
<< compaction->CalculateTotalInputSize() << "oldest_snapshot_seqno"
<< (job_context_->snapshot_seqs.empty()
<< (existing_snapshots_.empty()
? int64_t{-1} // Use -1 for "none"
: static_cast<int64_t>(
job_context_->GetEarliestSnapshotSequence()));
: static_cast<int64_t>(existing_snapshots_[0]));
if (compaction->SupportsPerKeyPlacement()) {
stream << "proximal_after_seqno" << proximal_after_seqno_;
stream << "preserve_seqno_after" << preserve_seqno_after_;
+37 -24
View File
@@ -142,27 +142,27 @@ class SubcompactionState;
class CompactionJob {
public:
CompactionJob(int job_id, Compaction* compaction,
const ImmutableDBOptions& db_options,
const MutableDBOptions& mutable_db_options,
const FileOptions& file_options, VersionSet* versions,
const std::atomic<bool>* shutting_down, LogBuffer* log_buffer,
FSDirectory* db_directory, FSDirectory* output_directory,
FSDirectory* blob_output_directory, Statistics* stats,
InstrumentedMutex* db_mutex, ErrorHandler* db_error_handler,
JobContext* job_context, std::shared_ptr<Cache> table_cache,
EventLogger* event_logger, bool paranoid_file_checks,
bool measure_io_stats, const std::string& dbname,
CompactionJobStats* compaction_job_stats,
Env::Priority thread_pri,
const std::shared_ptr<IOTracer>& io_tracer,
const std::atomic<bool>& manual_compaction_canceled,
const std::string& db_id = "",
const std::string& db_session_id = "",
std::string full_history_ts_low = "", std::string trim_ts = "",
BlobFileCompletionCallback* blob_callback = nullptr,
int* bg_compaction_scheduled = nullptr,
int* bg_bottom_compaction_scheduled = nullptr);
CompactionJob(
int job_id, Compaction* compaction, const ImmutableDBOptions& db_options,
const MutableDBOptions& mutable_db_options,
const FileOptions& file_options, VersionSet* versions,
const std::atomic<bool>* shutting_down, LogBuffer* log_buffer,
FSDirectory* db_directory, FSDirectory* output_directory,
FSDirectory* blob_output_directory, Statistics* stats,
InstrumentedMutex* db_mutex, ErrorHandler* db_error_handler,
std::vector<SequenceNumber> existing_snapshots,
SequenceNumber earliest_write_conflict_snapshot,
const SnapshotChecker* snapshot_checker, JobContext* job_context,
std::shared_ptr<Cache> table_cache, EventLogger* event_logger,
bool paranoid_file_checks, bool measure_io_stats,
const std::string& dbname, CompactionJobStats* compaction_job_stats,
Env::Priority thread_pri, const std::shared_ptr<IOTracer>& io_tracer,
const std::atomic<bool>& manual_compaction_canceled,
const std::string& db_id = "", const std::string& db_session_id = "",
std::string full_history_ts_low = "", std::string trim_ts = "",
BlobFileCompletionCallback* blob_callback = nullptr,
int* bg_compaction_scheduled = nullptr,
int* bg_bottom_compaction_scheduled = nullptr);
virtual ~CompactionJob();
@@ -321,8 +321,21 @@ class CompactionJob {
FSDirectory* blob_output_directory_;
InstrumentedMutex* db_mutex_;
ErrorHandler* db_error_handler_;
// If there were two snapshots with seq numbers s1 and
// s2 and s1 < s2, and if we find two instances of a key k1 then lies
// entirely within s1 and s2, then the earlier version of k1 can be safely
// deleted because that version is not visible in any snapshot.
std::vector<SequenceNumber> existing_snapshots_;
SequenceNumber earliest_snapshot_;
// This is the earliest snapshot that could be used for write-conflict
// checking by a transaction. For any user-key newer than this snapshot, we
// should make sure not to remove evidence that a write occurred.
SequenceNumber earliest_write_conflict_snapshot_;
const SnapshotChecker* const snapshot_checker_;
JobContext* job_context_;
std::shared_ptr<Cache> table_cache_;
@@ -511,9 +524,9 @@ class CompactionServiceCompactionJob : private CompactionJob {
const std::atomic<bool>* shutting_down, LogBuffer* log_buffer,
FSDirectory* output_directory, Statistics* stats,
InstrumentedMutex* db_mutex, ErrorHandler* db_error_handler,
JobContext* job_context, std::shared_ptr<Cache> table_cache,
EventLogger* event_logger, const std::string& dbname,
const std::shared_ptr<IOTracer>& io_tracer,
std::vector<SequenceNumber> existing_snapshots,
std::shared_ptr<Cache> table_cache, EventLogger* event_logger,
const std::string& dbname, const std::shared_ptr<IOTracer>& io_tracer,
const std::atomic<bool>& manual_compaction_canceled,
const std::string& db_id, const std::string& db_session_id,
std::string output_path,
+11 -12
View File
@@ -43,6 +43,7 @@ void VerifyInitializationOfCompactionJobStats(
ASSERT_EQ(compaction_job_stats.elapsed_micros, 0U);
ASSERT_EQ(compaction_job_stats.num_input_records, 0U);
ASSERT_EQ(compaction_job_stats.num_input_files, 0U);
ASSERT_EQ(compaction_job_stats.num_input_files_at_output_level, 0U);
ASSERT_EQ(compaction_job_stats.num_output_records, 0U);
@@ -51,6 +52,7 @@ void VerifyInitializationOfCompactionJobStats(
ASSERT_TRUE(compaction_job_stats.is_manual_compaction);
ASSERT_FALSE(compaction_job_stats.is_remote_compaction);
ASSERT_EQ(compaction_job_stats.total_input_bytes, 0U);
ASSERT_EQ(compaction_job_stats.total_output_bytes, 0U);
ASSERT_EQ(compaction_job_stats.total_input_raw_key_bytes, 0U);
@@ -593,11 +595,11 @@ class CompactionJobTestBase : public testing::Test {
const std::vector<std::vector<FileMetaData*>>& input_files,
const std::vector<int> input_levels,
std::function<void(Compaction& comp)>&& verify_func,
std::vector<SequenceNumber>&& snapshots = {}) {
const std::vector<SequenceNumber>& snapshots = {}) {
const int kLastLevel = cf_options_.num_levels - 1;
verify_per_key_placement_ = std::move(verify_func);
mock::KVVector empty_map;
RunCompaction(input_files, input_levels, {empty_map}, std::move(snapshots),
RunCompaction(input_files, input_levels, {empty_map}, snapshots,
kMaxSequenceNumber, kLastLevel, false);
}
@@ -606,7 +608,7 @@ class CompactionJobTestBase : public testing::Test {
const std::vector<std::vector<FileMetaData*>>& input_files,
const std::vector<int>& input_levels,
const std::vector<mock::KVVector>& expected_results,
std::vector<SequenceNumber>&& snapshots = {},
const std::vector<SequenceNumber>& snapshots = {},
SequenceNumber earliest_write_conflict_snapshot = kMaxSequenceNumber,
int output_level = 1, bool verify = true,
std::vector<uint64_t> expected_oldest_blob_file_numbers = {},
@@ -663,15 +665,13 @@ class CompactionJobTestBase : public testing::Test {
ucmp_->timestamp_size() == full_history_ts_low_.size());
const std::atomic<bool> kManualCompactionCanceledFalse{false};
JobContext job_context(1, false /* create_superversion */);
job_context.InitSnapshotContext(snapshot_checker, nullptr,
earliest_write_conflict_snapshot,
std::move(snapshots));
CompactionJob compaction_job(
0, &compaction, db_options_, mutable_db_options_, env_options_,
versions_.get(), &shutting_down_, &log_buffer, nullptr, nullptr,
nullptr, nullptr, &mutex_, &error_handler_, &job_context, table_cache_,
&event_logger, false, false, dbname_, &compaction_job_stats_,
Env::Priority::USER, nullptr /* IOTracer */,
nullptr, nullptr, &mutex_, &error_handler_, snapshots,
earliest_write_conflict_snapshot, snapshot_checker, &job_context,
table_cache_, &event_logger, false, false, dbname_,
&compaction_job_stats_, Env::Priority::USER, nullptr /* IOTracer */,
/*manual_compaction_canceled=*/kManualCompactionCanceledFalse,
env_->GenerateUniqueId(), DBImpl::GenerateDbSessionId(nullptr),
full_history_ts_low_);
@@ -2036,7 +2036,7 @@ TEST_F(CompactionJobTest, CutToAlignGrandparentBoundarySameKey) {
snapshots.emplace_back(i);
}
RunCompaction({lvl0_files, lvl1_files}, input_levels,
{expected_file1, expected_file2}, std::move(snapshots));
{expected_file1, expected_file2}, snapshots);
}
TEST_F(CompactionJobTest, CutForMaxCompactionBytesSameKey) {
@@ -2095,8 +2095,7 @@ TEST_F(CompactionJobTest, CutForMaxCompactionBytesSameKey) {
snapshots.emplace_back(i);
}
RunCompaction({lvl0_files, lvl1_files}, input_levels,
{expected_file1, expected_file2, expected_file3},
std::move(snapshots));
{expected_file1, expected_file2, expected_file3}, snapshots);
}
class CompactionJobTimestampTest : public CompactionJobTestBase {
+2 -3
View File
@@ -65,7 +65,7 @@ class CompactionPicker {
const MutableDBOptions& mutable_db_options,
const std::vector<SequenceNumber>& existing_snapshots,
const SnapshotChecker* snapshot_checker, VersionStorageInfo* vstorage,
LogBuffer* log_buffer, bool require_max_output_level) = 0;
LogBuffer* log_buffer) = 0;
// The returned Compaction might not include the whole requested range.
// In that case, compaction_end will be set to the next key that needs
@@ -272,8 +272,7 @@ class NullCompactionPicker : public CompactionPicker {
const MutableDBOptions& /*mutable_db_options*/,
const std::vector<SequenceNumber>& /*existing_snapshots*/,
const SnapshotChecker* /*snapshot_checker*/,
VersionStorageInfo* /*vstorage*/, LogBuffer* /* log_buffer */,
bool /*require_max_output_level*/ = false) override {
VersionStorageInfo* /*vstorage*/, LogBuffer* /* log_buffer */) override {
return nullptr;
}
+1 -1
View File
@@ -428,7 +428,7 @@ Compaction* FIFOCompactionPicker::PickCompaction(
const MutableDBOptions& mutable_db_options,
const std::vector<SequenceNumber>& /* existing_snapshots */,
const SnapshotChecker* /* snapshot_checker */, VersionStorageInfo* vstorage,
LogBuffer* log_buffer, bool /* require_max_output_level*/) {
LogBuffer* log_buffer) {
Compaction* c = nullptr;
if (mutable_cf_options.ttl > 0) {
c = PickTTLCompaction(cf_name, mutable_cf_options, mutable_db_options,
+1 -2
View File
@@ -23,8 +23,7 @@ class FIFOCompactionPicker : public CompactionPicker {
const MutableDBOptions& mutable_db_options,
const std::vector<SequenceNumber>& /* existing_snapshots */,
const SnapshotChecker* /* snapshot_checker */,
VersionStorageInfo* version, LogBuffer* log_buffer,
bool /* require_max_output_level*/ = false) override;
VersionStorageInfo* version, LogBuffer* log_buffer) override;
Compaction* CompactRange(const std::string& cf_name,
const MutableCFOptions& mutable_cf_options,
+1 -1
View File
@@ -978,7 +978,7 @@ Compaction* LevelCompactionPicker::PickCompaction(
const MutableDBOptions& mutable_db_options,
const std::vector<SequenceNumber>& /*existing_snapshots */,
const SnapshotChecker* /*snapshot_checker*/, VersionStorageInfo* vstorage,
LogBuffer* log_buffer, bool /* require_max_output_level*/) {
LogBuffer* log_buffer) {
LevelCompactionBuilder builder(cf_name, vstorage, this, log_buffer,
mutable_cf_options, ioptions_,
mutable_db_options);
+1 -2
View File
@@ -25,8 +25,7 @@ class LevelCompactionPicker : public CompactionPicker {
const MutableDBOptions& mutable_db_options,
const std::vector<SequenceNumber>& /* existing_snapshots */,
const SnapshotChecker* /* snapshot_checker */,
VersionStorageInfo* vstorage, LogBuffer* log_buffer,
bool /*require_max_output_level*/ = false) override;
VersionStorageInfo* vstorage, LogBuffer* log_buffer) override;
bool NeedsCompaction(const VersionStorageInfo* vstorage) const override;
};
+152 -253
View File
@@ -38,8 +38,7 @@ class UniversalCompactionBuilder {
const MutableDBOptions& mutable_db_options,
const std::vector<SequenceNumber>& existing_snapshots,
const SnapshotChecker* snapshot_checker, VersionStorageInfo* vstorage,
UniversalCompactionPicker* picker, LogBuffer* log_buffer,
bool require_max_output_level)
UniversalCompactionPicker* picker, LogBuffer* log_buffer)
: ioptions_(ioptions),
icmp_(icmp),
cf_name_(cf_name),
@@ -47,8 +46,7 @@ class UniversalCompactionBuilder {
mutable_db_options_(mutable_db_options),
vstorage_(vstorage),
picker_(picker),
log_buffer_(log_buffer),
require_max_output_level_(require_max_output_level) {
log_buffer_(log_buffer) {
assert(icmp_);
const auto* ucmp = icmp_->user_comparator();
assert(ucmp);
@@ -104,174 +102,6 @@ class UniversalCompactionBuilder {
bool level_has_marked_standalone_rangedel;
};
unsigned int GetMaxNumFilesToCompactBasedOnMaxReadAmp(
const int file_num_compaction_trigger, const unsigned int ratio,
int* num_sr_not_compacted_output, int* max_num_runs_output) const {
assert(num_sr_not_compacted_output);
assert(max_num_runs_output);
int max_num_runs =
mutable_cf_options_.compaction_options_universal.max_read_amp;
if (max_num_runs < 0) {
// any value < -1 is not valid
assert(max_num_runs == -1);
// By default, fall back to `level0_file_num_compaction_trigger`
max_num_runs = file_num_compaction_trigger;
} else if (max_num_runs == 0) {
if (mutable_cf_options_.compaction_options_universal.stop_style ==
kCompactionStopStyleTotalSize) {
// 0 means auto-tuning by RocksDB. We estimate max num run based on
// max_run_size, size_ratio and write buffer size:
// Assume the size of the lowest level size is equal to
// write_buffer_size. Each subsequent level is the max size without
// triggering size_ratio compaction. `max_num_runs` is the minimum
// number of levels required such that the target size of the
// largest level is at least `max_run_size_`.
max_num_runs = 1;
double cur_level_max_size =
static_cast<double>(mutable_cf_options_.write_buffer_size);
double total_run_size = 0;
while (cur_level_max_size < static_cast<double>(max_run_size_)) {
// This loop should not take too many iterations since
// cur_level_max_size at least doubles each iteration.
total_run_size += cur_level_max_size;
cur_level_max_size = (100.0 + ratio) / 100.0 * total_run_size;
++max_num_runs;
}
} else {
// TODO: implement the auto-tune logic for this stop style
max_num_runs = file_num_compaction_trigger;
}
} else {
// max_num_runs > 0, it's the limit on the number of sorted run
}
// Get the total number of sorted runs that are not being compacted
int num_sr_not_compacted = 0;
for (size_t i = 0; i < sorted_runs_.size(); i++) {
if (sorted_runs_[i].being_compacted == false &&
!sorted_runs_[i].level_has_marked_standalone_rangedel) {
num_sr_not_compacted++;
}
}
*num_sr_not_compacted_output = num_sr_not_compacted;
*max_num_runs_output = max_num_runs;
if (num_sr_not_compacted > max_num_runs) {
return num_sr_not_compacted - max_num_runs + 1;
} else {
return 0;
}
}
Compaction* MaybePickPeriodicCompaction(Compaction* const prev_picked_c) {
if (prev_picked_c != nullptr ||
vstorage_->FilesMarkedForPeriodicCompaction().empty()) {
return prev_picked_c;
}
// Always need to do a full compaction for periodic compaction.
Compaction* c = PickPeriodicCompaction();
TEST_SYNC_POINT_CALLBACK("PostPickPeriodicCompaction", c);
if (c != nullptr) {
ROCKS_LOG_BUFFER(log_buffer_,
"[%s] Universal: picked for periodic compaction\n",
cf_name_.c_str());
}
return c;
}
Compaction* MaybePickSizeAmpCompaction(Compaction* const prev_picked_c,
int file_num_compaction_trigger) {
if (prev_picked_c != nullptr ||
sorted_runs_.size() <
static_cast<size_t>(file_num_compaction_trigger)) {
return prev_picked_c;
}
Compaction* c = PickCompactionToReduceSizeAmp();
if (c != nullptr) {
TEST_SYNC_POINT("PickCompactionToReduceSizeAmpReturnNonnullptr");
ROCKS_LOG_BUFFER(log_buffer_,
"[%s] Universal: picked for size amp compaction \n",
cf_name_.c_str());
}
return c;
}
Compaction* MaybePickCompactionToReduceSortedRunsBasedFileRatio(
Compaction* const prev_picked_c, int file_num_compaction_trigger,
unsigned int ratio) {
if (prev_picked_c != nullptr ||
sorted_runs_.size() <
static_cast<size_t>(file_num_compaction_trigger)) {
return prev_picked_c;
}
Compaction* c = PickCompactionToReduceSortedRuns(ratio, UINT_MAX);
if (c != nullptr) {
TEST_SYNC_POINT("PickCompactionToReduceSortedRunsReturnNonnullptr");
ROCKS_LOG_BUFFER(log_buffer_,
"[%s] Universal: picked for size ratio compaction to "
"reduce sorted run\n",
cf_name_.c_str());
}
return c;
}
Compaction* MaybePickCompactionToReduceSortedRuns(
Compaction* const prev_picked_c, int file_num_compaction_trigger,
unsigned int ratio) {
if (prev_picked_c != nullptr ||
sorted_runs_.size() <
static_cast<size_t>(file_num_compaction_trigger)) {
return prev_picked_c;
}
int num_sr_not_compacted = 0;
int max_num_runs = 0;
const unsigned int max_num_files_to_compact =
GetMaxNumFilesToCompactBasedOnMaxReadAmp(file_num_compaction_trigger,
ratio, &num_sr_not_compacted,
&max_num_runs);
if (max_num_files_to_compact == 0) {
ROCKS_LOG_BUFFER(
log_buffer_,
"[%s] Universal: skipping compaction to reduce sorted run, num "
"sorted runs not "
"being compacted -- %u, max num runs allowed -- %d, max_run_size "
"-- %" PRIu64 "\n",
cf_name_.c_str(), num_sr_not_compacted, max_num_runs, max_run_size_);
return nullptr;
}
Compaction* c =
PickCompactionToReduceSortedRuns(UINT_MAX, max_num_files_to_compact);
if (c != nullptr) {
ROCKS_LOG_BUFFER(log_buffer_,
"[%s] Universal: picked for sorted run num compaction "
"to reduce sorted run, to "
"compact file num -- %u, max num runs allowed"
"-- %d, max_run_size -- %" PRIu64 "\n",
cf_name_.c_str(), max_num_files_to_compact, max_num_runs,
max_run_size_);
}
return c;
}
Compaction* MaybePickDeleteTriggeredCompaction(
Compaction* const prev_picked_c) {
if (prev_picked_c != nullptr) {
return prev_picked_c;
}
Compaction* c = PickDeleteTriggeredCompaction();
if (c != nullptr) {
TEST_SYNC_POINT("PickDeleteTriggeredCompactionReturnNonnullptr");
ROCKS_LOG_BUFFER(
log_buffer_,
"[%s] Universal: picked for delete triggered compaction\n",
cf_name_.c_str());
}
return c;
}
// Pick Universal compaction to limit read amplification
Compaction* PickCompactionToReduceSortedRuns(
unsigned int ratio, unsigned int max_number_of_files_to_compact);
@@ -419,13 +249,6 @@ class UniversalCompactionBuilder {
return num_l0_to_exclude;
}
bool MeetsOutputLevelRequirements(int output_level) const {
return !require_max_output_level_ ||
Compaction::OutputToNonZeroMaxOutputLevel(
output_level,
vstorage_->MaxOutputLevel(ioptions_.allow_ingest_behind));
}
const ImmutableOptions& ioptions_;
const InternalKeyComparator* icmp_;
double score_;
@@ -437,7 +260,6 @@ class UniversalCompactionBuilder {
VersionStorageInfo* vstorage_;
UniversalCompactionPicker* picker_;
LogBuffer* log_buffer_;
bool require_max_output_level_;
// Optional earliest snapshot at time of compaction picking. This is only
// provided if the column family doesn't enable user-defined timestamps.
// And this information is only passed to `Compaction` picked by deletion
@@ -598,11 +420,10 @@ Compaction* UniversalCompactionPicker::PickCompaction(
const MutableDBOptions& mutable_db_options,
const std::vector<SequenceNumber>& existing_snapshots,
const SnapshotChecker* snapshot_checker, VersionStorageInfo* vstorage,
LogBuffer* log_buffer, bool require_max_output_level) {
LogBuffer* log_buffer) {
UniversalCompactionBuilder builder(
ioptions_, icmp_, cf_name, mutable_cf_options, mutable_db_options,
existing_snapshots, snapshot_checker, vstorage, this, log_buffer,
require_max_output_level);
existing_snapshots, snapshot_checker, vstorage, this, log_buffer);
return builder.PickCompaction();
}
@@ -733,21 +554,13 @@ bool UniversalCompactionBuilder::ShouldSkipMarkedFile(
Compaction* UniversalCompactionBuilder::PickCompaction() {
const int kLevel0 = 0;
score_ = vstorage_->CompactionScore(kLevel0);
const int max_output_level =
int max_output_level =
vstorage_->MaxOutputLevel(ioptions_.allow_ingest_behind);
const int file_num_compaction_trigger =
mutable_cf_options_.level0_file_num_compaction_trigger;
const unsigned int ratio =
mutable_cf_options_.compaction_options_universal.size_ratio;
if (max_output_level == 0 &&
!MeetsOutputLevelRequirements(0 /* output_level */)) {
return nullptr;
}
max_run_size_ = 0;
sorted_runs_ =
CalculateSortedRuns(*vstorage_, max_output_level, &max_run_size_);
int file_num_compaction_trigger =
mutable_cf_options_.level0_file_num_compaction_trigger;
if (sorted_runs_.size() == 0 ||
(vstorage_->FilesMarkedForPeriodicCompaction().empty() &&
@@ -759,7 +572,6 @@ Compaction* UniversalCompactionBuilder::PickCompaction() {
"UniversalCompactionBuilder::PickCompaction:Return", nullptr);
return nullptr;
}
VersionStorageInfo::LevelSummaryStorage tmp;
ROCKS_LOG_BUFFER_MAX_SZ(
log_buffer_, 3072,
@@ -767,14 +579,119 @@ Compaction* UniversalCompactionBuilder::PickCompaction() {
cf_name_.c_str(), sorted_runs_.size(), vstorage_->LevelSummary(&tmp));
Compaction* c = nullptr;
// Periodic compaction has higher priority than other type of compaction
// because it's a hard requirement.
if (!vstorage_->FilesMarkedForPeriodicCompaction().empty()) {
// Always need to do a full compaction for periodic compaction.
c = PickPeriodicCompaction();
TEST_SYNC_POINT_CALLBACK("PostPickPeriodicCompaction", c);
}
c = MaybePickPeriodicCompaction(c);
c = MaybePickSizeAmpCompaction(c, file_num_compaction_trigger);
c = MaybePickCompactionToReduceSortedRunsBasedFileRatio(
c, file_num_compaction_trigger, ratio);
c = MaybePickCompactionToReduceSortedRuns(c, file_num_compaction_trigger,
ratio);
c = MaybePickDeleteTriggeredCompaction(c);
if (c == nullptr &&
sorted_runs_.size() >= static_cast<size_t>(file_num_compaction_trigger)) {
// Check for size amplification.
if ((c = PickCompactionToReduceSizeAmp()) != nullptr) {
TEST_SYNC_POINT("PickCompactionToReduceSizeAmpReturnNonnullptr");
ROCKS_LOG_BUFFER(log_buffer_, "[%s] Universal: compacting for size amp\n",
cf_name_.c_str());
} else {
// Size amplification is within limits. Try reducing read
// amplification while maintaining file size ratios.
unsigned int ratio =
mutable_cf_options_.compaction_options_universal.size_ratio;
if ((c = PickCompactionToReduceSortedRuns(ratio, UINT_MAX)) != nullptr) {
TEST_SYNC_POINT("PickCompactionToReduceSortedRunsReturnNonnullptr");
ROCKS_LOG_BUFFER(log_buffer_,
"[%s] Universal: compacting for size ratio\n",
cf_name_.c_str());
} else {
// Size amplification and file size ratios are within configured limits.
// If max read amplification exceeds configured limits, then force
// compaction to reduce the number sorted runs without looking at file
// size ratios.
// This is guaranteed by NeedsCompaction()
assert(sorted_runs_.size() >=
static_cast<size_t>(file_num_compaction_trigger));
int max_num_runs =
mutable_cf_options_.compaction_options_universal.max_read_amp;
if (max_num_runs < 0) {
// any value < -1 is not valid
assert(max_num_runs == -1);
// By default, fall back to `level0_file_num_compaction_trigger`
max_num_runs = file_num_compaction_trigger;
} else if (max_num_runs == 0) {
if (mutable_cf_options_.compaction_options_universal.stop_style ==
kCompactionStopStyleTotalSize) {
// 0 means auto-tuning by RocksDB. We estimate max num run based on
// max_run_size, size_ratio and write buffer size:
// Assume the size of the lowest level size is equal to
// write_buffer_size. Each subsequent level is the max size without
// triggering size_ratio compaction. `max_num_runs` is the minimum
// number of levels required such that the target size of the
// largest level is at least `max_run_size_`.
max_num_runs = 1;
double cur_level_max_size =
static_cast<double>(mutable_cf_options_.write_buffer_size);
double total_run_size = 0;
while (cur_level_max_size < static_cast<double>(max_run_size_)) {
// This loop should not take too many iterations since
// cur_level_max_size at least doubles each iteration.
total_run_size += cur_level_max_size;
cur_level_max_size = (100.0 + ratio) / 100.0 * total_run_size;
++max_num_runs;
}
} else {
// TODO: implement the auto-tune logic for this stop style
max_num_runs = file_num_compaction_trigger;
}
} else {
// max_num_runs > 0, it's the limit on the number of sorted run
}
// Get the total number of sorted runs that are not being compacted
int num_sr_not_compacted = 0;
for (size_t i = 0; i < sorted_runs_.size(); i++) {
if (sorted_runs_[i].being_compacted == false &&
!sorted_runs_[i].level_has_marked_standalone_rangedel) {
num_sr_not_compacted++;
}
}
// The number of sorted runs that are not being compacted is greater
// than the maximum allowed number of sorted runs
if (num_sr_not_compacted > max_num_runs) {
unsigned int num_files = num_sr_not_compacted - max_num_runs + 1;
if ((c = PickCompactionToReduceSortedRuns(UINT_MAX, num_files)) !=
nullptr) {
ROCKS_LOG_BUFFER(log_buffer_,
"[%s] Universal: compacting for file num, to "
"compact file num -- %u, max num runs allowed"
"-- %d, max_run_size -- %" PRIu64 "\n",
cf_name_.c_str(), num_files, max_num_runs,
max_run_size_);
}
} else {
ROCKS_LOG_BUFFER(
log_buffer_,
"[%s] Universal: skipping compaction for file num, num runs not "
"being compacted -- %u, max num runs allowed -- %d, max_run_size "
"-- %" PRIu64 "\n",
cf_name_.c_str(), num_sr_not_compacted, max_num_runs,
max_run_size_);
}
}
}
}
if (c == nullptr) {
if ((c = PickDeleteTriggeredCompaction()) != nullptr) {
TEST_SYNC_POINT("PickDeleteTriggeredCompactionReturnNonnullptr");
ROCKS_LOG_BUFFER(log_buffer_,
"[%s] Universal: delete triggered compaction\n",
cf_name_.c_str());
}
}
if (c == nullptr) {
TEST_SYNC_POINT_CALLBACK(
@@ -783,7 +700,6 @@ Compaction* UniversalCompactionBuilder::PickCompaction() {
}
assert(c->output_level() <=
vstorage_->MaxOutputLevel(ioptions_.allow_ingest_behind));
assert(MeetsOutputLevelRequirements(c->output_level()));
if (mutable_cf_options_.compaction_options_universal.allow_trivial_move ==
true &&
@@ -909,16 +825,14 @@ Compaction* UniversalCompactionBuilder::PickCompactionToReduceSortedRuns(
if (sr->being_compacted) {
ROCKS_LOG_BUFFER(log_buffer_,
"[%s] Universal: %s"
"[%d] being compacted, skipping for compaction to "
"reduce sorted runs",
"[%d] being compacted, skipping",
cf_name_.c_str(), file_num_buf, loop);
} else if (sr->level_has_marked_standalone_rangedel) {
ROCKS_LOG_BUFFER(
log_buffer_,
"[%s] Universal: %s"
"[%d] has standalone range tombstone files marked for "
"compaction, skipping for compaction to reduce sorted runs",
cf_name_.c_str(), file_num_buf, loop);
ROCKS_LOG_BUFFER(log_buffer_,
"[%s] Universal: %s"
"[%d] has standalone range tombstone files marked for "
"compaction, skipping",
cf_name_.c_str(), file_num_buf, loop);
}
sr = nullptr;
@@ -931,8 +845,7 @@ Compaction* UniversalCompactionBuilder::PickCompactionToReduceSortedRuns(
char file_num_buf[kFormatFileNumberBufSize];
sr->Dump(file_num_buf, sizeof(file_num_buf), true);
ROCKS_LOG_BUFFER(log_buffer_,
"[%s] Universal: Possible candidate for compaction to "
"reduce sorted runs %s[%d].",
"[%s] Universal: Possible candidate %s[%d].",
cf_name_.c_str(), file_num_buf, loop);
}
@@ -1034,10 +947,6 @@ Compaction* UniversalCompactionBuilder::PickCompactionToReduceSortedRuns(
output_level = sorted_runs_[first_index_after].level - 1;
}
if (!MeetsOutputLevelRequirements(output_level)) {
return nullptr;
}
std::vector<CompactionInputFiles> inputs(max_output_level + 1);
for (size_t i = 0; i < inputs.size(); ++i) {
inputs[i].level = start_level + static_cast<int>(i);
@@ -1130,19 +1039,18 @@ Compaction* UniversalCompactionBuilder::PickCompactionToReduceSizeAmp() {
char file_num_buf[kFormatFileNumberBufSize];
sr->Dump(file_num_buf, sizeof(file_num_buf), true);
if (sr->being_compacted) {
ROCKS_LOG_BUFFER(log_buffer_,
"[%s] Universal: stopping for size amp compaction at "
"sorted run undergoing compaction: "
"%s[%" ROCKSDB_PRIszt "]",
cf_name_.c_str(), file_num_buf, start_index - 1);
ROCKS_LOG_BUFFER(
log_buffer_,
"[%s] Universal: stopping at sorted run undergoing compaction: "
"%s[%" ROCKSDB_PRIszt "]",
cf_name_.c_str(), file_num_buf, start_index - 1);
} else if (sr->level_has_marked_standalone_rangedel) {
ROCKS_LOG_BUFFER(log_buffer_,
"[%s] Universal: stopping for size amp compaction at "
"sorted run that has "
"standalone range "
"tombstone files marked for compaction: "
"%s[%" ROCKSDB_PRIszt "]",
cf_name_.c_str(), file_num_buf, start_index - 1);
ROCKS_LOG_BUFFER(
log_buffer_,
"[%s] Universal: stopping at sorted run that has standalone range "
"tombstone files marked for compaction: "
"%s[%" ROCKSDB_PRIszt "]",
cf_name_.c_str(), file_num_buf, start_index - 1);
}
break;
}
@@ -1158,12 +1066,11 @@ Compaction* UniversalCompactionBuilder::PickCompactionToReduceSizeAmp() {
{
const size_t num_l0_to_exclude = MightExcludeNewL0sToReduceWriteStop(
num_l0_files, end_index, start_index, candidate_size);
ROCKS_LOG_BUFFER(
log_buffer_,
"[%s] Universal: Excluding for size amp compaction %" ROCKSDB_PRIszt
" latest L0 files to reduce potential write stop "
"triggered by `level0_stop_writes_trigger`",
cf_name_.c_str(), num_l0_to_exclude);
ROCKS_LOG_BUFFER(log_buffer_,
"[%s] Universal: Excluding %" ROCKSDB_PRIszt
" latest L0 files to reduce potential write stop "
"triggered by `level0_stop_writes_trigger`",
cf_name_.c_str(), num_l0_to_exclude);
}
{
@@ -1181,18 +1088,18 @@ Compaction* UniversalCompactionBuilder::PickCompactionToReduceSizeAmp() {
// size amplification = percentage of additional size
if (candidate_size * 100 < ratio * base_sr_size) {
ROCKS_LOG_BUFFER(log_buffer_,
"[%s] Universal: size amp compction not needed. "
"newer-files-total-size %" PRIu64
" earliest-file-size %" PRIu64,
cf_name_.c_str(), candidate_size, base_sr_size);
ROCKS_LOG_BUFFER(
log_buffer_,
"[%s] Universal: size amp not needed. newer-files-total-size %" PRIu64
" earliest-file-size %" PRIu64,
cf_name_.c_str(), candidate_size, base_sr_size);
return nullptr;
} else {
ROCKS_LOG_BUFFER(log_buffer_,
"[%s] Universal: size amp compaction needed. "
"newer-files-total-size %" PRIu64
" earliest-file-size %" PRIu64,
cf_name_.c_str(), candidate_size, base_sr_size);
ROCKS_LOG_BUFFER(
log_buffer_,
"[%s] Universal: size amp needed. newer-files-total-size %" PRIu64
" earliest-file-size %" PRIu64,
cf_name_.c_str(), candidate_size, base_sr_size);
}
// Since incremental compaction can't include more than second last
// level, it can introduce penalty, compared to full compaction. We
@@ -1543,10 +1450,6 @@ Compaction* UniversalCompactionBuilder::PickDeleteTriggeredCompaction() {
}
assert(output_level <= max_output_level);
if (!MeetsOutputLevelRequirements(output_level)) {
return nullptr;
}
if (output_level != 0) {
if (start_level == 0) {
if (!picker_->GetOverlappingL0Files(vstorage_, &start_level_inputs,
@@ -1671,10 +1574,6 @@ Compaction* UniversalCompactionBuilder::PickCompactionWithSortedRunRange(
output_level = sorted_runs_[end_index + 1].level - 1;
}
if (!MeetsOutputLevelRequirements(output_level)) {
return nullptr;
}
// intra L0 compactions outputs could have overlap
if (output_level != 0 && picker_->FilesRangeOverlapWithCompaction(
inputs, output_level,
+1 -4
View File
@@ -18,15 +18,12 @@ class UniversalCompactionPicker : public CompactionPicker {
UniversalCompactionPicker(const ImmutableOptions& ioptions,
const InternalKeyComparator* icmp)
: CompactionPicker(ioptions, icmp) {}
// If `require_max_output_level` is true, only pick compaction
// with max output level or return nullptr if no such compaction exists.
Compaction* PickCompaction(
const std::string& cf_name, const MutableCFOptions& mutable_cf_options,
const MutableDBOptions& mutable_db_options,
const std::vector<SequenceNumber>& existing_snapshots,
const SnapshotChecker* snapshot_checker, VersionStorageInfo* vstorage,
LogBuffer* log_buffer, bool require_max_output_level = false) override;
LogBuffer* log_buffer) override;
int MaxOutputLevel() const override { return NumberLevels() - 1; }
bool NeedsCompaction(const VersionStorageInfo* vstorage) const override;
+7 -6
View File
@@ -41,7 +41,7 @@ CompactionJob::ProcessKeyValueCompactionWithCompactionService(
}
compaction_input.cf_name = compaction->column_family_data()->GetName();
compaction_input.snapshots = job_context_->snapshot_seqs;
compaction_input.snapshots = existing_snapshots_;
compaction_input.has_begin = sub_compact->start.has_value();
compaction_input.begin =
compaction_input.has_begin ? sub_compact->start->ToString() : "";
@@ -304,9 +304,9 @@ CompactionServiceCompactionJob::CompactionServiceCompactionJob(
VersionSet* versions, const std::atomic<bool>* shutting_down,
LogBuffer* log_buffer, FSDirectory* output_directory, Statistics* stats,
InstrumentedMutex* db_mutex, ErrorHandler* db_error_handler,
JobContext* job_context, std::shared_ptr<Cache> table_cache,
EventLogger* event_logger, const std::string& dbname,
const std::shared_ptr<IOTracer>& io_tracer,
std::vector<SequenceNumber> existing_snapshots,
std::shared_ptr<Cache> table_cache, EventLogger* event_logger,
const std::string& dbname, const std::shared_ptr<IOTracer>& io_tracer,
const std::atomic<bool>& manual_compaction_canceled,
const std::string& db_id, const std::string& db_session_id,
std::string output_path,
@@ -315,8 +315,9 @@ CompactionServiceCompactionJob::CompactionServiceCompactionJob(
: CompactionJob(job_id, compaction, db_options, mutable_db_options,
file_options, versions, shutting_down, log_buffer, nullptr,
output_directory, nullptr, stats, db_mutex,
db_error_handler, job_context, std::move(table_cache),
event_logger,
db_error_handler, std::move(existing_snapshots),
kMaxSequenceNumber, nullptr, nullptr,
std::move(table_cache), event_logger,
compaction->mutable_cf_options().paranoid_file_checks,
compaction->mutable_cf_options().report_bg_io_stats, dbname,
&(compaction_service_result->stats), Env::Priority::USER,
-27
View File
@@ -7,7 +7,6 @@
#include "port/stack_trace.h"
#include "rocksdb/utilities/options_util.h"
#include "table/unique_id_impl.h"
#include "utilities/merge_operators/string_append/stringappend.h"
namespace ROCKSDB_NAMESPACE {
@@ -1223,32 +1222,6 @@ TEST_F(CompactionServiceTest, CompactionFilter) {
ASSERT_GE(my_cs->GetCompactionNum(), 1);
}
TEST_F(CompactionServiceTest, MergeOperator) {
Options options = CurrentOptions();
options.merge_operator.reset(new StringAppendOperator(','));
ReopenWithCompactionService(&options);
GenerateTestData();
ASSERT_OK(dbfull()->TEST_WaitForCompact());
for (int i = 0; i < 200; i++) {
ASSERT_OK(db_->Merge(WriteOptions(), Key(i),
"merge_op_append_" + std::to_string(i)));
}
ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
// verify result
for (int i = 0; i < 200; i++) {
auto result = Get(Key(i));
if (i % 2) {
ASSERT_EQ(result, "value" + std::to_string(i) + ",merge_op_append_" +
std::to_string(i));
} else {
ASSERT_EQ(result, "value_new" + std::to_string(i) + ",merge_op_append_" +
std::to_string(i));
}
}
auto my_cs = GetCompactionService();
ASSERT_GE(my_cs->GetCompactionNum(), 1);
}
TEST_F(CompactionServiceTest, Snapshot) {
Options options = CurrentOptions();
ReopenWithCompactionService(&options);
-4
View File
@@ -106,11 +106,7 @@ class SubcompactionState {
subcompaction_job_info.subcompaction_job_id = static_cast<int>(sub_job_id);
subcompaction_job_info.base_input_level = c->start_level();
subcompaction_job_info.output_level = c->output_level();
subcompaction_job_info.compaction_reason = c->compaction_reason();
subcompaction_job_info.compression = c->output_compression();
subcompaction_job_info.stats = compaction_job_stats;
subcompaction_job_info.blob_compression_type =
c->mutable_cf_options().blob_compression_type;
}
SubcompactionState() = delete;
+143 -269
View File
@@ -455,72 +455,6 @@ TEST_P(DBCompactionTestWithParam, CompactionDeletionTrigger) {
}
}
#endif // !defined(ROCKSDB_VALGRIND_RUN) || defined(ROCKSDB_FULL_VALGRIND_RUN)
TEST_F(DBCompactionTest, UniversalReduceFileLockingRepickNothing) {
const int kFileNumCompactionTrigger = 3;
Options options = CurrentOptions();
options.compaction_options_universal.reduce_file_locking = true;
// Set `max_background_jobs` to be 3 to allow low and bottom priority thread
// to run compaction together
options.max_background_jobs = 3;
Env::Default()->SetBackgroundThreads(1, Env::Priority::BOTTOM);
options.num_levels = 3;
options.compaction_style = kCompactionStyleUniversal;
options.level0_file_num_compaction_trigger = kFileNumCompactionTrigger;
options.compaction_options_universal.max_size_amplification_percent = 1;
DestroyAndReopen(options);
// Need to get a token to enable compaction parallelism up to
// `max_background_compactions` jobs.
auto pressure_token =
dbfull()->TEST_write_controler().GetCompactionPressureToken();
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
{// Wait for the full (bottom-priority) compaction to be pre-picked as an
// intent (that is allowing files to be picked by other compactions and
// will pick later when the bottom-priority thread is available to
// execute the compaction) before triggering the low-priority compaction.
{"DBImpl::BackgroundCompaction:ForwardToBottomPriPool",
"LowPriCompaction"},
// Wait for low-priority compaction to start before
// repicking for the full compaction intent (bottom-priority), enabling
// them to run in parallel.
{"DBImpl::BackgroundCompaction:NonTrivial",
"DBImpl::BGWorkBottomCompaction"}});
bool bottom_pri_compaction_attempt_repick = false;
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
"DBImpl::BackgroundCompaction():AfterPickCompactionBottomPri",
[&](void* arg) {
bottom_pri_compaction_attempt_repick = true;
Compaction* c = static_cast<Compaction*>(arg);
// Verify the intended full compaction for bottom priority thread does
// not get to run (i.e, output to bottommost level) since when it
// repicks its files, some of the the intended input files are already
// compacted by the low priority thread
assert(c == nullptr);
});
SyncPoint::GetInstance()->EnableProcessing();
for (int i = 0; i < kFileNumCompactionTrigger; ++i) {
if (i == 0) {
ASSERT_OK(Put("file_locked_for_bottom_pri_compaction", "value"));
} else {
ASSERT_OK(
Put("file_not_locked_for_bottom_pri_compaction" + std::to_string(i),
"value"));
}
ASSERT_OK(Flush());
}
TEST_SYNC_POINT("LowPriCompaction");
ASSERT_OK(Put("a_new_file_to_pick_for_low_pri_compaction", "value"));
ASSERT_OK(Flush());
ASSERT_OK(dbfull()->TEST_WaitForCompact());
ASSERT_TRUE(bottom_pri_compaction_attempt_repick);
}
TEST_F(DBCompactionTest, SkipStatsUpdateTest) {
// This test verify UpdateAccumulatedStats is not on
@@ -2890,99 +2824,46 @@ TEST_F(DBCompactionTest, L0_CompactionBug_Issue44_b) {
}
TEST_F(DBCompactionTest, ManualAutoRace) {
const int kNumL0FilesTrigger = 4;
// Verify that the auto compaction is retried after the conflicting exclusive
// manual compaction finishes for:
// 1. Non-bottom-priority compactions (tested with level compaction)
// 2. Bottom-priority compactions (tested with universal compaction)
for (auto compaction_style :
{kCompactionStyleLevel, kCompactionStyleUniversal}) {
Env::Default()->SetBackgroundThreads(
compaction_style == kCompactionStyleUniversal ? 2 : 0,
Env::Priority::BOTTOM);
for (auto universal_reduce_file_locking : {false, true}) {
if (compaction_style != kCompactionStyleUniversal &&
universal_reduce_file_locking) {
continue;
}
CreateAndReopenWithCF({"pikachu"}, CurrentOptions());
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
{{"DBImpl::BGWorkCompaction", "DBCompactionTest::ManualAutoRace:1"},
{"DBImpl::RunManualCompaction:WaitScheduled",
"BackgroundCallCompaction:0"}});
Options options = CurrentOptions();
options.num_levels = 3;
options.level0_file_num_compaction_trigger = kNumL0FilesTrigger;
options.compaction_style = compaction_style;
options.compaction_options_universal.reduce_file_locking =
universal_reduce_file_locking;
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
DestroyAndReopen(options);
CreateAndReopenWithCF({"exclusive_manual_compaction_cf"}, options);
ASSERT_OK(Put(1, "foo", ""));
ASSERT_OK(Put(1, "bar", ""));
ASSERT_OK(Flush(1));
ASSERT_OK(Put(1, "foo", ""));
ASSERT_OK(Put(1, "bar", ""));
// Generate four files in CF 0, which should trigger an auto compaction
ASSERT_OK(Put("foo", ""));
ASSERT_OK(Put("bar", ""));
ASSERT_OK(Flush());
ASSERT_OK(Put("foo", ""));
ASSERT_OK(Put("bar", ""));
ASSERT_OK(Flush());
ASSERT_OK(Put("foo", ""));
ASSERT_OK(Put("bar", ""));
ASSERT_OK(Flush());
ASSERT_OK(Put("foo", ""));
ASSERT_OK(Put("bar", ""));
ASSERT_OK(Flush());
// Set up sync points to ensure that the auto compaction
// encounters a conflict from exclusive manual compaction before the auto
// compaction gets to pick files, This will trigger a retry later.
//
// Specifically, the sync points are set up as following:
// 1. Wait until background low-pri scheduled (not picking files yet) or
// bottom-pri scheduled (not repicking files yet) for
// `universal_reduce_file_locking = true` before triggering
// CompactRange()
//
// 2. Wait until the triggered CompactRange()
// registers its compaction and creates conflict before the auto
// compaction picks or repicks files for the background compaction.
if (compaction_style == kCompactionStyleLevel ||
!universal_reduce_file_locking) {
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
{{"DBImpl::BGWorkCompaction", "DBCompactionTest::ManualAutoRace:1"},
{"DBImpl::RunManualCompaction:WaitScheduled",
"BackgroundCallCompaction:0"}});
} else {
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
{{"DBImpl::BackgroundCompaction:ForwardToBottomPriPool",
"DBCompactionTest::ManualAutoRace:1"},
{"DBImpl::RunManualCompaction:WaitScheduled",
"BackgroundCallCompaction:0:BottomPri"}});
}
// The auto compaction is scheduled but waited until here
TEST_SYNC_POINT("DBCompactionTest::ManualAutoRace:1");
// The auto compaction will wait until the manual compaction is registerd
// before processing so that it will be cancelled.
CompactRangeOptions cro;
cro.exclusive_manual_compaction = true;
ASSERT_OK(dbfull()->CompactRange(cro, handles_[1], nullptr, nullptr));
ASSERT_EQ("0,1", FilesPerLevel(1));
bool encounter_conflict = false;
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
"DBImpl::BackgroundCompaction()::Conflict",
[&](void* /*arg*/) { encounter_conflict = true; });
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
// Generate files in CF 1 for exclusive CompactRange()
ASSERT_OK(Put(1, "foo", ""));
ASSERT_OK(Put(1, "bar", ""));
ASSERT_OK(Flush(1));
ASSERT_OK(Put(1, "foo", ""));
ASSERT_OK(Put(1, "bar", ""));
// Generate files in CF0 to trigger full compaction
for (int i = 0; i < kNumL0FilesTrigger; ++i) {
ASSERT_OK(Put("foo", ""));
ASSERT_OK(Put("bar", ""));
ASSERT_OK(Flush());
}
TEST_SYNC_POINT("DBCompactionTest::ManualAutoRace:1");
CompactRangeOptions cro;
cro.exclusive_manual_compaction = true;
ASSERT_OK(dbfull()->CompactRange(cro, handles_[1], nullptr, nullptr));
ASSERT_EQ(compaction_style == kCompactionStyleLevel ? "0,1" : "0,0,1",
FilesPerLevel(1));
ASSERT_OK(dbfull()->TEST_WaitForCompact());
ASSERT_TRUE(encounter_conflict);
// Verify that the auto compaction is eventually executed after the
// exclusive CompactRange() finishes.
ASSERT_EQ(compaction_style == kCompactionStyleLevel ? "0,1" : "0,0,1",
FilesPerLevel(0));
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearAllCallBacks();
}
Env::Default()->SetBackgroundThreads(0, Env::Priority::BOTTOM);
}
// Eventually the cancelled compaction will be rescheduled and executed.
ASSERT_OK(dbfull()->TEST_WaitForCompact());
ASSERT_EQ("0,1", FilesPerLevel(0));
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
}
TEST_P(DBCompactionTestWithParam, ManualCompaction) {
@@ -4105,51 +3986,41 @@ TEST_P(DBCompactionTestWithParam, IntraL0CompactionDoesNotObsoleteDeletions) {
TEST_P(DBCompactionTestWithParam, FullCompactionInBottomPriThreadPool) {
const int kNumFilesTrigger = 3;
Env::Default()->SetBackgroundThreads(1, Env::Priority::BOTTOM);
for (auto compaction_style :
{kCompactionStyleLevel, kCompactionStyleUniversal}) {
for (auto universal_reduce_file_locking : {false, true}) {
if (compaction_style != kCompactionStyleUniversal &&
universal_reduce_file_locking) {
continue;
}
Options options = CurrentOptions();
options.compaction_style = compaction_style;
if (compaction_style == kCompactionStyleLevel) {
options.level_compaction_dynamic_level_bytes = true;
} else {
options.compaction_options_universal.reduce_file_locking =
universal_reduce_file_locking;
// Trigger compaction if size amplification exceeds 110%
options.compaction_options_universal.max_size_amplification_percent =
110;
}
options.num_levels = 4;
options.write_buffer_size = 100 << 10; // 100KB
options.target_file_size_base = 32 << 10; // 32KB
options.level0_file_num_compaction_trigger = kNumFilesTrigger;
DestroyAndReopen(options);
int num_bottom_pri_compactions = 0;
SyncPoint::GetInstance()->SetCallBack(
"DBImpl::BGWorkBottomCompaction",
[&](void* /*arg*/) { ++num_bottom_pri_compactions; });
SyncPoint::GetInstance()->EnableProcessing();
Random rnd(301);
for (int num = 0; num < kNumFilesTrigger; num++) {
ASSERT_EQ(NumSortedRuns(), num);
int key_idx = 0;
GenerateNewFile(&rnd, &key_idx);
}
ASSERT_OK(dbfull()->TEST_WaitForCompact());
ASSERT_EQ(1, num_bottom_pri_compactions);
// Verify that size amplification did occur
ASSERT_EQ(NumSortedRuns(), 1);
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
for (bool use_universal_compaction : {false, true}) {
Options options = CurrentOptions();
if (use_universal_compaction) {
options.compaction_style = kCompactionStyleUniversal;
} else {
options.compaction_style = kCompactionStyleLevel;
options.level_compaction_dynamic_level_bytes = true;
}
options.num_levels = 4;
options.write_buffer_size = 100 << 10; // 100KB
options.target_file_size_base = 32 << 10; // 32KB
options.level0_file_num_compaction_trigger = kNumFilesTrigger;
// Trigger compaction if size amplification exceeds 110%
options.compaction_options_universal.max_size_amplification_percent = 110;
DestroyAndReopen(options);
int num_bottom_pri_compactions = 0;
SyncPoint::GetInstance()->SetCallBack(
"DBImpl::BGWorkBottomCompaction",
[&](void* /*arg*/) { ++num_bottom_pri_compactions; });
SyncPoint::GetInstance()->EnableProcessing();
Random rnd(301);
for (int num = 0; num < kNumFilesTrigger; num++) {
ASSERT_EQ(NumSortedRuns(), num);
int key_idx = 0;
GenerateNewFile(&rnd, &key_idx);
}
ASSERT_OK(dbfull()->TEST_WaitForCompact());
ASSERT_EQ(1, num_bottom_pri_compactions);
// Verify that size amplification did occur
ASSERT_EQ(NumSortedRuns(), 1);
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
}
Env::Default()->SetBackgroundThreads(0, Env::Priority::BOTTOM);
}
@@ -6763,7 +6634,7 @@ TEST_P(RoundRobinSubcompactionsAgainstResources, SubcompactionsUsingResources) {
// compaction is enough to make post-compaction L1 size less than
// the maximum size (this test assumes only one round-robin compaction
// is triggered by kLevelMaxLevelSize)
options.max_compaction_bytes = std::numeric_limits<uint64_t>::max();
options.max_compaction_bytes = 100000000;
DestroyAndReopen(options);
env_->SetBackgroundThreads(total_low_pri_threads_, Env::LOW);
@@ -6796,33 +6667,41 @@ TEST_P(RoundRobinSubcompactionsAgainstResources, SubcompactionsUsingResources) {
// More than 10 files are selected for round-robin under auto
// compaction. The number of planned subcompaction is restricted by
// the minimum number between available threads and compaction limits
auto actual_reserved_threads =
num_planned_subcompactions - options.max_subcompactions;
auto expected_reserved_threads =
std::min(total_low_pri_threads_, max_compaction_limits_) - 1;
ASSERT_EQ(actual_reserved_threads, expected_reserved_threads);
ASSERT_EQ(num_planned_subcompactions - options.max_subcompactions,
std::min(total_low_pri_threads_, max_compaction_limits_) - 1);
num_planned_subcompactions_verified = true;
});
int acquire_count = 0;
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
"CompactionJob::AcquireSubcompactionResources:0",
[&](void* /*arg*/) { acquire_count++; });
int release_count = 0;
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
"CompactionJob::ReleaseSubcompactionResources",
[&](void* /*arg*/) { release_count++; });
SyncPoint::GetInstance()->LoadDependency(
{{"RoundRobinSubcompactionsAgainstResources:0",
"BackgroundCallCompaction:0"},
{"CompactionJob::AcquireSubcompactionResources:0",
"RoundRobinSubcompactionsAgainstResources:1"},
{"RoundRobinSubcompactionsAgainstResources:2",
"CompactionJob::AcquireSubcompactionResources:1"},
{"CompactionJob::ReleaseSubcompactionResources:0",
"RoundRobinSubcompactionsAgainstResources:3"},
{"RoundRobinSubcompactionsAgainstResources:4",
"CompactionJob::ReleaseSubcompactionResources:1"}});
SyncPoint::GetInstance()->EnableProcessing();
ASSERT_OK(dbfull()->TEST_WaitForCompact());
ASSERT_OK(dbfull()->EnableAutoCompaction({dbfull()->DefaultColumnFamily()}));
TEST_SYNC_POINT("RoundRobinSubcompactionsAgainstResources:0");
TEST_SYNC_POINT("RoundRobinSubcompactionsAgainstResources:1");
auto pressure_token =
dbfull()->TEST_write_controler().GetCompactionPressureToken();
ASSERT_OK(dbfull()->EnableAutoCompaction({dbfull()->DefaultColumnFamily()}));
TEST_SYNC_POINT("RoundRobinSubcompactionsAgainstResources:2");
TEST_SYNC_POINT("RoundRobinSubcompactionsAgainstResources:3");
// We can reserve more threads now except one is being used
ASSERT_EQ(total_low_pri_threads_ - 1,
env_->ReserveThreads(total_low_pri_threads_, Env::Priority::LOW));
ASSERT_EQ(
total_low_pri_threads_ - 1,
env_->ReleaseThreads(total_low_pri_threads_ - 1, Env::Priority::LOW));
TEST_SYNC_POINT("RoundRobinSubcompactionsAgainstResources:4");
ASSERT_OK(dbfull()->TEST_WaitForCompact());
ASSERT_TRUE(num_planned_subcompactions_verified);
ASSERT_EQ(acquire_count, release_count);
SyncPoint::GetInstance()->DisableProcessing();
SyncPoint::GetInstance()->ClearAllCallBacks();
}
@@ -10127,60 +10006,55 @@ TEST_F(DBCompactionTest, BottomPriCompactionCountsTowardConcurrencyLimit) {
env_->SetBackgroundThreads(1, Env::Priority::BOTTOM);
for (bool universal_reduce_file_locking : {false, true}) {
Options options = CurrentOptions();
options.level0_file_num_compaction_trigger = kNumL0Files;
options.num_levels = kNumLevels;
options.compaction_style = kCompactionStyleUniversal;
options.compaction_options_universal.reduce_file_locking =
universal_reduce_file_locking;
DestroyAndReopen(options);
Options options = CurrentOptions();
options.level0_file_num_compaction_trigger = kNumL0Files;
options.num_levels = kNumLevels;
DestroyAndReopen(options);
// Setup last level to be non-empty since it's a bit unclear whether
// compaction to an empty level would be considered "bottommost".
// Setup last level to be non-empty since it's a bit unclear whether
// compaction to an empty level would be considered "bottommost".
ASSERT_OK(Put(Key(0), "val"));
ASSERT_OK(Flush());
MoveFilesToLevel(kNumLevels - 1);
SyncPoint::GetInstance()->LoadDependency(
{{"DBImpl::BGWorkBottomCompaction",
"DBCompactionTest::BottomPriCompactionCountsTowardConcurrencyLimit:"
"PreTriggerCompaction"},
{"DBCompactionTest::BottomPriCompactionCountsTowardConcurrencyLimit:"
"PostTriggerCompaction",
"BackgroundCallCompaction:0"}});
SyncPoint::GetInstance()->EnableProcessing();
port::Thread compact_range_thread([&] {
CompactRangeOptions cro;
cro.bottommost_level_compaction = BottommostLevelCompaction::kForce;
cro.exclusive_manual_compaction = false;
ASSERT_OK(dbfull()->CompactRange(cro, nullptr, nullptr));
});
// Sleep in the low-pri thread so any newly scheduled compaction will be
// queued. Otherwise it might finish before we check its existence.
test::SleepingBackgroundTask sleeping_task_low;
env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask, &sleeping_task_low,
Env::Priority::LOW);
sleeping_task_low.WaitUntilSleeping();
TEST_SYNC_POINT(
"DBCompactionTest::BottomPriCompactionCountsTowardConcurrencyLimit:"
"PreTriggerCompaction");
for (int i = 0; i < kNumL0Files; ++i) {
ASSERT_OK(Put(Key(0), "val"));
ASSERT_OK(Flush());
MoveFilesToLevel(kNumLevels - 1);
SyncPoint::GetInstance()->LoadDependency(
{{"DBImpl::BGWorkBottomCompaction",
"DBCompactionTest::BottomPriCompactionCountsTowardConcurrencyLimit:"
"PreTriggerCompaction"},
{"DBCompactionTest::BottomPriCompactionCountsTowardConcurrencyLimit:"
"PostTriggerCompaction",
"BackgroundCallCompaction:0"}});
SyncPoint::GetInstance()->EnableProcessing();
port::Thread compact_range_thread([&] {
CompactRangeOptions cro;
cro.bottommost_level_compaction = BottommostLevelCompaction::kForce;
cro.exclusive_manual_compaction = false;
ASSERT_OK(dbfull()->CompactRange(cro, nullptr, nullptr));
});
// Sleep in the low-pri thread so any newly scheduled compaction will be
// queued. Otherwise it might finish before we check its existence.
test::SleepingBackgroundTask sleeping_task_low;
env_->Schedule(&test::SleepingBackgroundTask::DoSleepTask,
&sleeping_task_low, Env::Priority::LOW);
sleeping_task_low.WaitUntilSleeping();
TEST_SYNC_POINT(
"DBCompactionTest::BottomPriCompactionCountsTowardConcurrencyLimit:"
"PreTriggerCompaction");
for (int i = 0; i < kNumL0Files; ++i) {
ASSERT_OK(Put(Key(0), "val"));
ASSERT_OK(Flush());
}
ASSERT_EQ(0u, env_->GetThreadPoolQueueLen(Env::Priority::LOW));
TEST_SYNC_POINT(
"DBCompactionTest::BottomPriCompactionCountsTowardConcurrencyLimit:"
"PostTriggerCompaction");
sleeping_task_low.WakeUp();
sleeping_task_low.WaitUntilDone();
compact_range_thread.join();
}
ASSERT_EQ(0u, env_->GetThreadPoolQueueLen(Env::Priority::LOW));
TEST_SYNC_POINT(
"DBCompactionTest::BottomPriCompactionCountsTowardConcurrencyLimit:"
"PostTriggerCompaction");
sleeping_task_low.WakeUp();
sleeping_task_low.WaitUntilDone();
compact_range_thread.join();
}
TEST_F(DBCompactionTest, BottommostFileCompactionAllowIngestBehind) {
+3 -1
View File
@@ -5018,6 +5018,7 @@ void DBImpl::GetColumnFamilyMetaData(ColumnFamilyHandle* column_family,
assert(column_family);
auto* cfd =
static_cast_with_check<ColumnFamilyHandleImpl>(column_family)->cfd();
auto* sv = GetAndRefSuperVersion(cfd);
{
// Without mutex, Version::GetColumnFamilyMetaData will have data race
// with Compaction::MarkFilesBeingCompacted. One solution is to use mutex,
@@ -5029,8 +5030,9 @@ void DBImpl::GetColumnFamilyMetaData(ColumnFamilyHandle* column_family,
// DB::GetColumnFamilyMetaData is not called frequently, the regression
// should not be big. We still need to keep an eye on it.
InstrumentedMutexLock l(&mutex_);
cfd->current()->GetColumnFamilyMetaData(cf_meta);
sv->current->GetColumnFamilyMetaData(cf_meta);
}
ReturnAndCleanupSuperVersion(cfd, sv);
}
void DBImpl::GetAllColumnFamilyMetaData(
+12 -22
View File
@@ -1090,7 +1090,10 @@ class DBImpl : public DB {
void SetSnapshotChecker(SnapshotChecker* snapshot_checker);
// Fill JobContext with snapshot information needed by flush and compaction.
void InitSnapshotContext(JobContext* job_context);
void GetSnapshotContext(JobContext* job_context,
std::vector<SequenceNumber>* snapshot_seqs,
SequenceNumber* earliest_write_conflict_snapshot,
SnapshotChecker** snapshot_checker);
// Not thread-safe.
void SetRecoverableStatePreReleaseCallback(PreReleaseCallback* callback);
@@ -1952,19 +1955,12 @@ class DBImpl : public DB {
};
struct PrepickedCompaction {
// background compaction takes ownership of `compaction`.
// TODO(hx235): consider using std::shared_ptr for easier ownership
// management
Compaction* compaction;
// caller retains ownership of `manual_compaction_state` as it is reused
// across background compactions.
ManualCompactionState* manual_compaction_state; // nullptr if non-manual
// task limiter token is requested during compaction picking.
std::unique_ptr<TaskLimiterToken> task_token;
// If true, `compaction` is picked temporarily to express compaction intent
// and will be released before re-picking a real compaction based on the
// updated LSM shape when thread associated with `compaction` is ready to
// run
bool need_repick;
};
struct CompactionArg {
@@ -2055,13 +2051,14 @@ class DBImpl : public DB {
// Flush the in-memory write buffer to storage. Switches to a new
// log-file/memtable and writes a new descriptor iff successful. Then
// installs a new super version for the column family.
Status FlushMemTableToOutputFile(ColumnFamilyData* cfd,
const MutableCFOptions& mutable_cf_options,
bool* madeProgress, JobContext* job_context,
FlushReason flush_reason,
SuperVersionContext* superversion_context,
LogBuffer* log_buffer,
Env::Priority thread_pri);
Status FlushMemTableToOutputFile(
ColumnFamilyData* cfd, const MutableCFOptions& mutable_cf_options,
bool* madeProgress, JobContext* job_context, FlushReason flush_reason,
SuperVersionContext* superversion_context,
std::vector<SequenceNumber>& snapshot_seqs,
SequenceNumber earliest_write_conflict_snapshot,
SnapshotChecker* snapshot_checker, LogBuffer* log_buffer,
Env::Priority thread_pri);
// Flush the memtables of (multiple) column families to multiple files on
// persistent storage.
@@ -2463,8 +2460,6 @@ class DBImpl : public DB {
bool* flush_rescheduled_to_retain_udt,
Env::Priority thread_pri);
Compaction* CreateIntendedCompactionForwardedToBottomPriorityPool(
Compaction* c);
bool EnoughRoomForCompaction(ColumnFamilyData* cfd,
const std::vector<CompactionInputFiles>& inputs,
bool* sfm_bookkeeping, LogBuffer* log_buffer);
@@ -2732,11 +2727,6 @@ class DBImpl : public DB {
const std::vector<ColumnFamilyHandle*>& column_families,
ErrorIteratorFuncType error_iterator_func);
bool ShouldPickCompaction(bool is_prepicked,
const PrepickedCompaction* prepicked_compaction);
void ResetBottomPriCompactionIntent(ColumnFamilyData* cfd,
std::unique_ptr<Compaction>& c);
// Lock over the persistent DB state. Non-nullptr iff successfully acquired.
FileLock* db_lock_ = nullptr;
+99 -224
View File
@@ -145,7 +145,10 @@ IOStatus DBImpl::SyncClosedWals(const WriteOptions& write_options,
Status DBImpl::FlushMemTableToOutputFile(
ColumnFamilyData* cfd, const MutableCFOptions& mutable_cf_options,
bool* made_progress, JobContext* job_context, FlushReason flush_reason,
SuperVersionContext* superversion_context, LogBuffer* log_buffer,
SuperVersionContext* superversion_context,
std::vector<SequenceNumber>& snapshot_seqs,
SequenceNumber earliest_write_conflict_snapshot,
SnapshotChecker* snapshot_checker, LogBuffer* log_buffer,
Env::Priority thread_pri) {
mutex_.AssertHeld();
assert(cfd);
@@ -209,6 +212,7 @@ Status DBImpl::FlushMemTableToOutputFile(
FlushJob flush_job(
dbname_, cfd, immutable_db_options_, mutable_cf_options, max_memtable_id,
file_options_for_compaction_, versions_.get(), &mutex_, &shutting_down_,
snapshot_seqs, earliest_write_conflict_snapshot, snapshot_checker,
job_context, flush_reason, log_buffer, directories_.GetDbDir(),
GetDataDir(cfd, 0U),
GetCompressionFlush(cfd->ioptions(), mutable_cf_options), stats_,
@@ -393,8 +397,11 @@ Status DBImpl::FlushMemTablesToOutputFiles(
bg_flush_args, made_progress, job_context, log_buffer, thread_pri);
}
assert(bg_flush_args.size() == 1);
InitSnapshotContext(job_context);
std::vector<SequenceNumber> snapshot_seqs;
SequenceNumber earliest_write_conflict_snapshot;
SnapshotChecker* snapshot_checker;
GetSnapshotContext(job_context, &snapshot_seqs,
&earliest_write_conflict_snapshot, &snapshot_checker);
const auto& bg_flush_arg = bg_flush_args[0];
ColumnFamilyData* cfd = bg_flush_arg.cfd_;
// intentional infrequent copy for each flush
@@ -405,7 +412,8 @@ Status DBImpl::FlushMemTablesToOutputFiles(
FlushReason flush_reason = bg_flush_arg.flush_reason_;
Status s = FlushMemTableToOutputFile(
cfd, mutable_cf_options_copy, made_progress, job_context, flush_reason,
superversion_context, log_buffer, thread_pri);
superversion_context, snapshot_seqs, earliest_write_conflict_snapshot,
snapshot_checker, log_buffer, thread_pri);
return s;
}
@@ -440,7 +448,12 @@ Status DBImpl::AtomicFlushMemTablesToOutputFiles(
}
#endif /* !NDEBUG */
InitSnapshotContext(job_context);
std::vector<SequenceNumber> snapshot_seqs;
SequenceNumber earliest_write_conflict_snapshot;
SnapshotChecker* snapshot_checker;
GetSnapshotContext(job_context, &snapshot_seqs,
&earliest_write_conflict_snapshot, &snapshot_checker);
autovector<FSDirectory*> distinct_output_dirs;
autovector<std::string> distinct_output_dir_paths;
std::vector<std::unique_ptr<FlushJob>> jobs;
@@ -474,7 +487,8 @@ Status DBImpl::AtomicFlushMemTablesToOutputFiles(
jobs.emplace_back(new FlushJob(
dbname_, cfd, immutable_db_options_, mutable_cf_options,
max_memtable_id, file_options_for_compaction_, versions_.get(), &mutex_,
&shutting_down_, job_context, flush_reason, log_buffer,
&shutting_down_, snapshot_seqs, earliest_write_conflict_snapshot,
snapshot_checker, job_context, flush_reason, log_buffer,
directories_.GetDbDir(), data_dir,
GetCompressionFlush(cfd->ioptions(), mutable_cf_options), stats_,
&event_logger_, mutable_cf_options.report_bg_io_stats,
@@ -1381,9 +1395,6 @@ Status DBImpl::CompactFiles(const CompactionOptions& compact_options,
TEST_SYNC_POINT_CALLBACK("TestCompactFiles:PausingManualCompaction:3",
static_cast<void*>(const_cast<std::atomic<int>*>(
&manual_compaction_paused_)));
TEST_SYNC_POINT_CALLBACK("TestCancelCompactFiles:SuccessfulCompaction",
static_cast<void*>(const_cast<std::atomic<int>*>(
&manual_compaction_paused_)));
{
InstrumentedMutexLock l(&mutex_);
auto* current = cfd->current();
@@ -1436,12 +1447,7 @@ Status DBImpl::CompactFilesImpl(
if (shutting_down_.load(std::memory_order_acquire)) {
return Status::ShutdownInProgress();
}
// triggered by DisableManualCompactions or by user-set canceled flag in
// CompactionOptions
if (manual_compaction_paused_.load(std::memory_order_acquire) > 0 ||
(compact_options.canceled &&
compact_options.canceled->load(std::memory_order_acquire))) {
if (manual_compaction_paused_.load(std::memory_order_acquire) > 0) {
return Status::Incomplete(Status::SubCode::kManualCompactionPaused);
}
@@ -1512,7 +1518,11 @@ Status DBImpl::CompactFilesImpl(
// deletion compaction currently not allowed in CompactFiles.
assert(!c->deletion_compaction());
InitSnapshotContext(job_context);
std::vector<SequenceNumber> snapshot_seqs;
SequenceNumber earliest_write_conflict_snapshot;
SnapshotChecker* snapshot_checker;
GetSnapshotContext(job_context, &snapshot_seqs,
&earliest_write_conflict_snapshot, &snapshot_checker);
std::unique_ptr<std::list<uint64_t>::iterator> pending_outputs_inserted_elem(
new std::list<uint64_t>::iterator(
@@ -1526,6 +1536,7 @@ Status DBImpl::CompactFilesImpl(
log_buffer, directories_.GetDbDir(),
GetDataDir(c->column_family_data(), c->output_path_id()),
GetDataDir(c->column_family_data(), 0), stats_, &mutex_, &error_handler_,
snapshot_seqs, earliest_write_conflict_snapshot, snapshot_checker,
job_context, table_cache_, &event_logger_,
c->mutable_cf_options().paranoid_file_checks,
c->mutable_cf_options().report_bg_io_stats, dbname_,
@@ -2178,7 +2189,6 @@ Status DBImpl::RunManualCompaction(
// Don't throttle manual compaction, only count outstanding tasks.
assert(false);
}
ca->prepicked_compaction->need_repick = false;
manual.incomplete = false;
if (compaction->bottommost_level() &&
env_->GetBackgroundThreads(Env::Priority::BOTTOM) > 0) {
@@ -2708,10 +2718,6 @@ Status DBImpl::WaitUntilFlushWouldNotStallWrites(ColumnFamilyData* cfd,
// Finish waiting when ALL column families finish flushing memtables.
// resuming_from_bg_err indicates whether the caller is trying to resume from
// background error or in normal processing.
// Note that the wait finishes when the flush result is installed to column
// families' Versions and persisted in MANIFEST. It doesn't wait until
// SuperVersion to reflect the flush result, except for the case when
// flush_reason is `kExternalFileIngestion`.
Status DBImpl::WaitForFlushMemTables(
const autovector<ColumnFamilyData*>& cfds,
const autovector<const uint64_t*>& flush_memtable_ids,
@@ -3405,10 +3411,6 @@ void DBImpl::BackgroundCallCompaction(PrepickedCompaction* prepicked_compaction,
bool made_progress = false;
JobContext job_context(next_job_id_.fetch_add(1), true);
TEST_SYNC_POINT("BackgroundCallCompaction:0");
if (bg_thread_pri == Env::Priority::BOTTOM) {
TEST_SYNC_POINT("BackgroundCallCompaction:0:BottomPri");
}
LogBuffer log_buffer(InfoLogLevel::INFO_LEVEL,
immutable_db_options_.info_log.get());
{
@@ -3644,54 +3646,34 @@ Status DBImpl::BackgroundCompaction(bool* made_progress,
: m->manual_end->DebugString(true).c_str()));
}
}
} else if (ShouldPickCompaction(is_prepicked, prepicked_compaction)) {
bool need_repick = is_prepicked && prepicked_compaction->need_repick;
} else if (!is_prepicked && !compaction_queue_.empty()) {
if (HasExclusiveManualCompaction()) {
// Can't compact right now, but try again later
TEST_SYNC_POINT("DBImpl::BackgroundCompaction()::Conflict");
// TODO(hx235): Resolve conflict between intended
// bottom-priority compaction (requiring repick, i.e., need_repick = true)
// and exclusive manual compaction by releasing the intended
// bottom-priority compaction.
if (!need_repick) {
// Can't compact right now, but try again later
//
// Increase `unscheduled_compactions_` directly so we
// don't need to
// dequeue and enqueue the CFD again in the compaction queue and thus
// keep the CFD's position in the queue
unscheduled_compactions_++;
// Stay in the compaction queue.
unscheduled_compactions_++;
return Status::OK();
}
return Status::OK();
}
ColumnFamilyData* cfd = nullptr;
auto cfd = PickCompactionFromQueue(&task_token, log_buffer);
if (cfd == nullptr) {
// Can't find any executable task from the compaction queue.
// All tasks have been throttled by compaction thread limiter.
++unscheduled_compactions_;
return Status::Busy();
}
if (!need_repick) {
cfd = PickCompactionFromQueue(&task_token, log_buffer);
if (cfd == nullptr) {
// Can't find any executable task from the compaction queue.
// All tasks have been throttled by compaction thread limiter.
++unscheduled_compactions_;
return Status::Busy();
}
// We unreference here because the following code will take a Ref() on
// this cfd if it is going to use it (Compaction class holds a
// reference).
// This will all happen under a mutex so we don't have to be afraid of
// somebody else deleting it.
if (cfd->UnrefAndTryDelete()) {
// This was the last reference of the column family, so no need to
// compact.
return Status::OK();
}
} else {
cfd = c->column_family_data();
assert(cfd);
ResetBottomPriCompactionIntent(cfd, c);
assert(c == nullptr);
// We unreference here because the following code will take a Ref() on
// this cfd if it is going to use it (Compaction class holds a
// reference).
// This will all happen under a mutex so we don't have to be afraid of
// somebody else deleting it.
if (cfd->UnrefAndTryDelete()) {
// This was the last reference of the column family, so no need to
// compact.
return Status::OK();
}
// Pick up latest mutable CF Options and use it throughout the
@@ -3705,24 +3687,21 @@ Status DBImpl::BackgroundCompaction(bool* made_progress,
// compaction is not necessary. Need to make sure mutex is held
// until we make a copy in the following code
TEST_SYNC_POINT("DBImpl::BackgroundCompaction():BeforePickCompaction");
SnapshotChecker* snapshot_checker = nullptr;
std::vector<SequenceNumber> snapshot_seqs;
// This info is not useful for other scenarios, so save querying existing
// snapshots for those cases.
if (cfd->ioptions().compaction_style == kCompactionStyleUniversal &&
cfd->user_comparator()->timestamp_size() == 0) {
InitSnapshotContext(job_context);
SequenceNumber earliest_write_conflict_snapshot;
GetSnapshotContext(job_context, &snapshot_seqs,
&earliest_write_conflict_snapshot,
&snapshot_checker);
assert(is_snapshot_supported_ || snapshots_.empty());
}
c.reset(cfd->PickCompaction(
mutable_cf_options, mutable_db_options_, job_context->snapshot_seqs,
job_context->snapshot_checker, log_buffer,
thread_pri == Env::Priority::BOTTOM /* require_max_output_level */));
if (thread_pri == Env::Priority::LOW) {
TEST_SYNC_POINT("DBImpl::BackgroundCompaction():AfterPickCompaction");
} else if (thread_pri == Env::Priority::BOTTOM) {
TEST_SYNC_POINT_CALLBACK(
"DBImpl::BackgroundCompaction():AfterPickCompactionBottomPri",
c.get());
}
c.reset(cfd->PickCompaction(mutable_cf_options, mutable_db_options_,
snapshot_seqs, snapshot_checker, log_buffer));
TEST_SYNC_POINT("DBImpl::BackgroundCompaction():AfterPickCompaction");
if (c != nullptr) {
bool enough_room = EnoughRoomForCompaction(
@@ -3736,7 +3715,7 @@ Status DBImpl::BackgroundCompaction(bool* made_progress,
->storage_info()
->ComputeCompactionScore(c->immutable_options(),
c->mutable_cf_options());
EnqueuePendingCompaction(cfd);
AddToCompactionQueue(cfd);
c.reset();
// Don't need to sleep here, because BackgroundCallCompaction
@@ -3758,21 +3737,16 @@ Status DBImpl::BackgroundCompaction(bool* made_progress,
// options take effect.
// 3) When we Pick a new compaction, we "remove" those files being
// compacted from the calculation, which then influences compaction
// score. Inside EnqueuePendingCompaction(), we check if we need
// the new compaction even without the files that are currently being
// compacted. If we need another compaction, we might be able to
// execute it in parallel, so we add it to the queue and schedule a
// new thread.
EnqueuePendingCompaction(cfd);
MaybeScheduleFlushOrCompaction();
// score. Here we check if we need the new compaction even without the
// files that are currently being compacted. If we need another
// compaction, we might be able to execute it in parallel, so we add
// it to the queue and schedule a new thread.
if (cfd->NeedsCompaction()) {
// Yes, we need more compactions!
AddToCompactionQueue(cfd);
MaybeScheduleFlushOrCompaction();
}
}
} else if (is_prepicked) {
ROCKS_LOG_BUFFER(
log_buffer,
"[%s] Pre-picked compaction repicked files for compaction as "
"required, "
"but upon re-evaluation, no compaction was found necessary \n",
cfd->GetName().c_str());
}
}
}
@@ -4149,16 +4123,14 @@ Status DBImpl::BackgroundCompaction(bool* made_progress,
ThreadStatusUtil::ResetThreadStatus();
TEST_SYNC_POINT_CALLBACK("DBImpl::BackgroundCompaction:AfterCompaction",
c->column_family_data());
} else if (!is_prepicked &&
Compaction::OutputToNonZeroMaxOutputLevel(
c->output_level(),
} else if (!is_prepicked && c->output_level() > 0 &&
c->output_level() ==
c->column_family_data()
->current()
->storage_info()
->MaxOutputLevel(
immutable_db_options_.allow_ingest_behind)) &&
immutable_db_options_.allow_ingest_behind) &&
env_->GetBackgroundThreads(Env::Priority::BOTTOM) > 0) {
assert(thread_pri == Env::Priority::LOW);
// Forward compactions involving last level to the bottom pool if it exists,
// such that compactions unlikely to contribute to write stalls can be
// delayed or deprioritized.
@@ -4167,23 +4139,7 @@ Status DBImpl::BackgroundCompaction(bool* made_progress,
ca->db = this;
ca->compaction_pri_ = Env::Priority::BOTTOM;
ca->prepicked_compaction = new PrepickedCompaction;
// If `universal_reduce_file_locking` is true, we only lock a limited set of
// input files by creating an intended compaction to forward to bottom
// priority pool and repicking files when bottom priority thread
// gets to execute this intended compaction
const bool need_repick =
c->mutable_cf_options()
.compaction_options_universal.reduce_file_locking;
if (need_repick) {
ca->prepicked_compaction->compaction =
CreateIntendedCompactionForwardedToBottomPriorityPool(c.get());
c.reset();
ca->prepicked_compaction->need_repick = true;
} else {
ca->prepicked_compaction->compaction = c.release();
ca->prepicked_compaction->need_repick = false;
}
ca->prepicked_compaction->compaction = c.release();
ca->prepicked_compaction->manual_compaction_state = nullptr;
// Transfer requested token, so it doesn't need to do it again.
ca->prepicked_compaction->task_token = std::move(task_token);
@@ -4198,7 +4154,11 @@ Status DBImpl::BackgroundCompaction(bool* made_progress,
output_level = c->output_level();
TEST_SYNC_POINT_CALLBACK("DBImpl::BackgroundCompaction:NonTrivial",
&output_level);
InitSnapshotContext(job_context);
std::vector<SequenceNumber> snapshot_seqs;
SequenceNumber earliest_write_conflict_snapshot;
SnapshotChecker* snapshot_checker;
GetSnapshotContext(job_context, &snapshot_seqs,
&earliest_write_conflict_snapshot, &snapshot_checker);
assert(is_snapshot_supported_ || snapshots_.empty());
CompactionJob compaction_job(
@@ -4207,7 +4167,8 @@ Status DBImpl::BackgroundCompaction(bool* made_progress,
&shutting_down_, log_buffer, directories_.GetDbDir(),
GetDataDir(c->column_family_data(), c->output_path_id()),
GetDataDir(c->column_family_data(), 0), stats_, &mutex_,
&error_handler_, job_context, table_cache_, &event_logger_,
&error_handler_, snapshot_seqs, earliest_write_conflict_snapshot,
snapshot_checker, job_context, table_cache_, &event_logger_,
c->mutable_cf_options().paranoid_file_checks,
c->mutable_cf_options().report_bg_io_stats, dbname_,
&compaction_job_stats, thread_pri, io_tracer_,
@@ -4227,15 +4188,8 @@ Status DBImpl::BackgroundCompaction(bool* made_progress,
NotifyOnCompactionBegin(c->column_family_data(), c.get(), status,
compaction_job_stats, job_context->job_id);
mutex_.Unlock();
if (thread_pri == Env::Priority::LOW) {
TEST_SYNC_POINT_CALLBACK(
"DBImpl::BackgroundCompaction:NonTrivial:BeforeRun", nullptr);
} else {
assert(thread_pri == Env::Priority::BOTTOM);
TEST_SYNC_POINT(
"DBImpl::BackgroundCompaction:NonTrivial:BeforeRunBottomPri");
}
TEST_SYNC_POINT_CALLBACK(
"DBImpl::BackgroundCompaction:NonTrivial:BeforeRun", nullptr);
// Should handle error?
compaction_job.Run().PermitUncheckedError();
TEST_SYNC_POINT("DBImpl::BackgroundCompaction:NonTrivial:AfterRun");
@@ -4329,7 +4283,9 @@ Status DBImpl::BackgroundCompaction(bool* made_progress,
->storage_info()
->ComputeCompactionScore(c->immutable_options(),
c->mutable_cf_options());
EnqueuePendingCompaction(cfd);
if (!cfd->queued_for_compaction()) {
AddToCompactionQueue(cfd);
}
}
}
// this will unref its input_version and column_family_data
@@ -4374,71 +4330,6 @@ Status DBImpl::BackgroundCompaction(bool* made_progress,
return status;
}
// Create an intended compaction to forward based on the original picked
// compaction. It serves two purposes while it is waiting
// for a bottom-priority thread becomes available to run:
// - Prevent the last input file (or sorted run if non-L0) from
// being included in compaction score calculations unnecessarily since the
// intended compaction is already scheduled to compact it
// - Allow other input files to be picked by low-priority compactions that can
// run right away
//
// Once a bottom-priority available to run this intended compaction, it will
// repick files to consider the LSM updates that occurred during the waiting
// period.
Compaction* DBImpl::CreateIntendedCompactionForwardedToBottomPriorityPool(
Compaction* c) {
auto* cfd = c->column_family_data();
const auto& io = c->immutable_options();
const auto& mo = c->mutable_cf_options();
auto* vstorage = c->input_version()->storage_info();
std::vector<CompactionInputFiles> inputs(1);
const std::vector<FileMetaData*>* max_intput_level_files = nullptr;
int max_intput_level = 0;
for (size_t i = c->num_input_levels(); i >= 1; --i) {
size_t level = i - 1;
if (c->num_input_files(level) > 0) {
max_intput_level = static_cast<int>(level);
max_intput_level_files = c->inputs(level);
break;
}
}
assert(max_intput_level_files);
assert(!max_intput_level_files->empty());
inputs[0].level = max_intput_level;
if (max_intput_level == 0) {
// The last input file
inputs[0].files.push_back(
(*max_intput_level_files)[max_intput_level_files->size() - 1]);
} else {
// The last input sorted run
for (FileMetaData* f : (*max_intput_level_files)) {
inputs[0].files.push_back(f);
}
}
c->ReleaseCompactionFiles(Status::OK());
Compaction* intended_compaction = new Compaction(
vstorage, io, mo, mutable_db_options_, std::move(inputs),
c->output_level(), c->target_output_file_size(),
c->max_compaction_bytes(), c->output_path_id(), c->output_compression(),
c->output_compression_opts(), c->output_temperature(),
c->max_subcompactions(), c->grandparents(),
std::nullopt /* earliest_snapshot */, nullptr /* snapshot_checker */);
cfd->compaction_picker()->RegisterCompaction(intended_compaction);
vstorage->ComputeCompactionScore(io, mo);
intended_compaction->FinalizeInputInfo(cfd->current());
return intended_compaction;
}
bool DBImpl::HasPendingManualCompaction() {
return (!manual_compaction_dequeue_.empty());
}
@@ -4710,33 +4601,31 @@ void DBImpl::SetSnapshotChecker(SnapshotChecker* snapshot_checker) {
snapshot_checker_.reset(snapshot_checker);
}
void DBImpl::InitSnapshotContext(JobContext* job_context) {
void DBImpl::GetSnapshotContext(
JobContext* job_context, std::vector<SequenceNumber>* snapshot_seqs,
SequenceNumber* earliest_write_conflict_snapshot,
SnapshotChecker** snapshot_checker_ptr) {
mutex_.AssertHeld();
assert(job_context != nullptr);
if (job_context->snapshot_context_initialized) {
return;
assert(snapshot_seqs != nullptr);
assert(earliest_write_conflict_snapshot != nullptr);
assert(snapshot_checker_ptr != nullptr);
*snapshot_checker_ptr = snapshot_checker_.get();
if (use_custom_gc_ && *snapshot_checker_ptr == nullptr) {
*snapshot_checker_ptr = DisableGCSnapshotChecker::Instance();
}
SnapshotChecker* snapshot_checker = snapshot_checker_.get();
if (use_custom_gc_ && !snapshot_checker) {
snapshot_checker = DisableGCSnapshotChecker::Instance();
}
std::unique_ptr<ManagedSnapshot> managed_snapshot = nullptr;
if (snapshot_checker) {
if (*snapshot_checker_ptr != nullptr) {
// If snapshot_checker is used, that means the flush/compaction may
// contain values not visible to snapshot taken after
// flush/compaction job starts. Take a snapshot and it will appear
// in snapshot_seqs and force compaction iterator to consider such
// snapshots.
const Snapshot* snapshot =
GetSnapshotImpl(/*is_write_conflict_boundary=*/false, /*lock=*/false);
managed_snapshot.reset(new ManagedSnapshot(this, snapshot));
const Snapshot* job_snapshot =
GetSnapshotImpl(false /*write_conflict_boundary*/, false /*lock*/);
job_context->job_snapshot.reset(new ManagedSnapshot(this, job_snapshot));
}
SequenceNumber earliest_write_conflict_snapshot = kMaxSequenceNumber;
std::vector<SequenceNumber> snapshot_seqs =
snapshots_.GetAll(&earliest_write_conflict_snapshot);
job_context->InitSnapshotContext(
snapshot_checker, std::move(managed_snapshot),
earliest_write_conflict_snapshot, std::move(snapshot_seqs));
*snapshot_seqs = snapshots_.GetAll(earliest_write_conflict_snapshot);
}
Status DBImpl::WaitForCompact(
@@ -4795,18 +4684,4 @@ Status DBImpl::WaitForCompact(
}
}
bool DBImpl::ShouldPickCompaction(
bool is_prepicked, const PrepickedCompaction* prepicked_compaction) {
return (!is_prepicked && !compaction_queue_.empty()) ||
(is_prepicked && prepicked_compaction->need_repick);
}
void DBImpl::ResetBottomPriCompactionIntent(ColumnFamilyData* cfd,
std::unique_ptr<Compaction>& c) {
c->ReleaseCompactionFiles(Status::OK());
cfd->current()->storage_info()->ComputeCompactionScore(
c->immutable_options(), c->mutable_cf_options());
c.reset();
}
} // namespace ROCKSDB_NAMESPACE
+2 -5
View File
@@ -933,10 +933,7 @@ Status DBImplSecondary::CompactWithoutInstallation(
immutable_db_options_.info_log.get());
const int job_id = next_job_id_.fetch_add(1);
JobContext job_context(0, true /*create_superversion*/);
std::vector<SequenceNumber> snapshots = input.snapshots;
job_context.InitSnapshotContext(nullptr, nullptr, kMaxSequenceNumber,
std::move(snapshots));
// use primary host's db_id for running the compaction, but db_session_id is
// using the local one, which is to make sure the unique id is unique from
// the remote compactors. Because the id is generated from db_id,
@@ -947,7 +944,7 @@ Status DBImplSecondary::CompactWithoutInstallation(
job_id, c.get(), immutable_db_options_, mutable_db_options_,
file_options_for_compaction_, versions_.get(), &shutting_down_,
&log_buffer, output_dir.get(), stats_, &mutex_, &error_handler_,
&job_context, table_cache_, &event_logger_, dbname_, io_tracer_,
input.snapshots, table_cache_, &event_logger_, dbname_, io_tracer_,
options.canceled ? *options.canceled : kManualCompactionCanceledFalse_,
input.db_id, db_session_id_, secondary_path_, input, result);
+19 -32
View File
@@ -66,11 +66,11 @@ DBIter::DBIter(Env* _env, const ReadOptions& read_options,
timestamp_lb_(read_options.iter_start_ts),
timestamp_size_(timestamp_ub_ ? timestamp_ub_->size() : 0),
active_mem_(active_mem),
memtable_seqno_lb_(kMaxSequenceNumber),
memtable_op_scan_flush_trigger_(0),
avg_op_scan_flush_trigger_(0),
iter_step_since_seek_(1),
mem_hidden_op_scanned_since_seek_(0),
memtable_seqno_lb_((active_mem_ && !active_mem_->IsEmpty())
? active_mem_->GetFirstSequenceNumber()
: kMaxSequenceNumber),
memtable_op_scan_flush_trigger_(
mutable_cf_options.memtable_op_scan_flush_trigger),
direction_(kForward),
valid_(false),
current_entry_is_merged_(false),
@@ -98,25 +98,6 @@ DBIter::DBIter(Env* _env, const ReadOptions& read_options,
// prefix_seek_opt_in_only should force total_order_seek whereever the caller
// is duplicating the original ReadOptions
assert(!ioptions.prefix_seek_opt_in_only || read_options.total_order_seek);
if (active_mem_) {
// FIXME: GetEarliestSequenceNumber() may return a seqno that is one smaller
// than the smallest seqno in the memtable. This violates its comment and
// entries with that seqno may not be in the active memtable. Before it's
// fixed, we use GetFirstSequenceNumber() for more accurate result.
memtable_seqno_lb_ = active_mem_->IsEmpty()
? active_mem_->GetEarliestSequenceNumber()
: active_mem_->GetFirstSequenceNumber();
memtable_op_scan_flush_trigger_ =
mutable_cf_options.memtable_op_scan_flush_trigger;
if (memtable_op_scan_flush_trigger_) {
// avg_op_scan_flush_trigger_ requires memtable_op_scan_flush_trigger_ > 0
avg_op_scan_flush_trigger_ =
mutable_cf_options.memtable_avg_op_scan_flush_trigger;
}
} else {
// memtable_op_scan_flush_trigger_ and avg_op_scan_flush_trigger_ are
// initialized to 0(disabled) as default.
}
}
Status DBIter::GetProperty(std::string prop_name, std::string* prop) {
@@ -178,7 +159,6 @@ void DBIter::Next() {
local_stats_.skip_count_ += num_internal_keys_skipped_;
local_stats_.skip_count_--;
num_internal_keys_skipped_ = 0;
iter_step_since_seek_++;
bool ok = true;
if (direction_ == kReverse) {
is_key_seqnum_zero_ = false;
@@ -393,7 +373,8 @@ bool DBIter::FindNextUserEntryInternal(bool skipping_saved_key,
// to one.
bool reseek_done = false;
uint64_t mem_hidden_op_scanned = 0;
uint64_t mem_ops_scanned = 0;
bool marked_for_flush = false;
do {
// Will update is_key_seqnum_zero_ as soon as we parsed the current key
// but we need to save the previous value to be used in the loop.
@@ -450,7 +431,12 @@ bool DBIter::FindNextUserEntryInternal(bool skipping_saved_key,
CompareKeyForSkip(ikey_.user_key, saved_key_.GetUserKey()) <= 0) {
num_skipped++; // skip this entry
PERF_COUNTER_ADD(internal_key_skipped_count, 1);
MarkMemtableForFlushForPerOpTrigger(mem_hidden_op_scanned);
if (memtable_op_scan_flush_trigger_ && active_mem_ &&
ikey_.sequence >= memtable_seqno_lb_ && !marked_for_flush &&
++mem_ops_scanned >= memtable_op_scan_flush_trigger_) {
active_mem_->MarkForFlush();
marked_for_flush = true;
}
} else {
assert(!skipping_saved_key ||
CompareKeyForSkip(ikey_.user_key, saved_key_.GetUserKey()) > 0);
@@ -472,7 +458,12 @@ bool DBIter::FindNextUserEntryInternal(bool skipping_saved_key,
!iter_.iter()->IsKeyPinned() /* copy */);
skipping_saved_key = true;
PERF_COUNTER_ADD(internal_delete_skipped_count, 1);
MarkMemtableForFlushForPerOpTrigger(mem_hidden_op_scanned);
if (memtable_op_scan_flush_trigger_ && active_mem_ &&
ikey_.sequence >= memtable_seqno_lb_ && !marked_for_flush &&
++mem_ops_scanned >= memtable_op_scan_flush_trigger_) {
active_mem_->MarkForFlush();
marked_for_flush = true;
}
}
break;
case kTypeValue:
@@ -1597,7 +1588,6 @@ void DBIter::Seek(const Slice& target) {
ResetBlobData();
ResetValueAndColumns();
ResetInternalKeysSkippedCounter();
MarkMemtableForFlushForAvgTrigger();
// Seek the inner iterator based on the target key.
{
@@ -1674,7 +1664,6 @@ void DBIter::SeekForPrev(const Slice& target) {
ResetBlobData();
ResetValueAndColumns();
ResetInternalKeysSkippedCounter();
MarkMemtableForFlushForAvgTrigger();
// Seek the inner iterator based on the target key.
{
@@ -1736,7 +1725,6 @@ void DBIter::SeekToFirst() {
ResetBlobData();
ResetValueAndColumns();
ResetInternalKeysSkippedCounter();
MarkMemtableForFlushForAvgTrigger();
ClearSavedValue();
is_key_seqnum_zero_ = false;
@@ -1800,7 +1788,6 @@ void DBIter::SeekToLast() {
ResetBlobData();
ResetValueAndColumns();
ResetInternalKeysSkippedCounter();
MarkMemtableForFlushForAvgTrigger();
ClearSavedValue();
is_key_seqnum_zero_ = false;
+4 -38
View File
@@ -12,6 +12,7 @@
#include <string>
#include "db/db_impl/db_impl.h"
#include "db/range_del_aggregator.h"
#include "memory/arena.h"
#include "options/cf_options.h"
#include "rocksdb/db.h"
@@ -61,8 +62,7 @@ class DBIter final : public Iterator {
//
// @param active_mem Pointer to the active memtable that `internal_iter`
// is reading from. If not null, the memtable can be marked for flush
// according to options mutable_cf_options.memtable_op_scan_flush_trigger
// and mutable_cf_options.memtable_avg_op_scan_flush_trigger.
// according to option mutable_cf_options.memtable_op_scan_flush_trigger.
// @param arena_mode If true, the DBIter will be allocated from the arena.
static DBIter* NewIter(Env* env, const ReadOptions& read_options,
const ImmutableOptions& ioptions,
@@ -145,7 +145,6 @@ class DBIter final : public Iterator {
void operator=(const DBIter&) = delete;
~DBIter() override {
MarkMemtableForFlushForAvgTrigger();
ThreadStatus::OperationType cur_op_type =
ThreadStatusUtil::GetThreadOperation();
ThreadStatusUtil::SetThreadOperation(
@@ -418,36 +417,6 @@ class DBIter final : public Iterator {
return true;
}
void MarkMemtableForFlushForAvgTrigger() {
if (avg_op_scan_flush_trigger_ &&
mem_hidden_op_scanned_since_seek_ >= memtable_op_scan_flush_trigger_ &&
mem_hidden_op_scanned_since_seek_ >=
static_cast<uint64_t>(iter_step_since_seek_) *
avg_op_scan_flush_trigger_) {
assert(memtable_op_scan_flush_trigger_ > 0);
active_mem_->MarkForFlush();
avg_op_scan_flush_trigger_ = 0;
memtable_op_scan_flush_trigger_ = 0;
}
iter_step_since_seek_ = 1;
mem_hidden_op_scanned_since_seek_ = 0;
}
void MarkMemtableForFlushForPerOpTrigger(uint64_t& mem_hidden_op_scanned) {
if (memtable_op_scan_flush_trigger_ &&
ikey_.sequence >= memtable_seqno_lb_) {
if (++mem_hidden_op_scanned >= memtable_op_scan_flush_trigger_) {
active_mem_->MarkForFlush();
// Turn off the flush trigger checks.
memtable_op_scan_flush_trigger_ = 0;
avg_op_scan_flush_trigger_ = 0;
}
if (avg_op_scan_flush_trigger_) {
++mem_hidden_op_scanned_since_seek_;
}
}
}
const SliceTransform* prefix_extractor_;
Env* const env_;
SystemClock* clock_;
@@ -507,11 +476,8 @@ class DBIter final : public Iterator {
std::string saved_timestamp_;
std::optional<std::vector<ScanOptions>> scan_opts_;
ReadOnlyMemTable* const active_mem_;
SequenceNumber memtable_seqno_lb_;
uint32_t memtable_op_scan_flush_trigger_;
uint32_t avg_op_scan_flush_trigger_;
uint32_t iter_step_since_seek_;
uint32_t mem_hidden_op_scanned_since_seek_;
const SequenceNumber memtable_seqno_lb_;
const uint32_t memtable_op_scan_flush_trigger_;
Direction direction_;
bool valid_;
bool current_entry_is_merged_;
-155
View File
@@ -3890,7 +3890,6 @@ TEST_P(DBIteratorTest, MemtableOpsScanFlushTriggerWithSeek) {
db_->GetIntProperty("rocksdb.num-deletes-active-mem-table", &val));
ASSERT_EQ(0, val);
} else {
ASSERT_EQ(0, NumTableFilesAtLevel(0));
uint64_t val = 0;
ASSERT_TRUE(
db_->GetIntProperty("rocksdb.num-deletes-active-mem-table", &val));
@@ -3985,160 +3984,6 @@ TEST_P(DBIteratorTest, MemtableOpsScanFlushTriggerWithNext) {
}
}
}
TEST_P(DBIteratorTest, AverageMemtableOpsScanFlushTrigger) {
// Tests option memtable_avg_op_scan_flush_trigger with
// long tombstone sequences.
Random* r = Random::GetTLSInstance();
const int kAvgTrigger = 10;
const int kMaxTrigger = 500;
Options options;
options.create_if_missing = true;
options.memtable_op_scan_flush_trigger = kMaxTrigger;
options.memtable_avg_op_scan_flush_trigger = kAvgTrigger;
options.level_compaction_dynamic_level_bytes = true;
DestroyAndReopen(options);
const int kNumKeys = 1000;
// Base data that will be covered by a consecutive sequence of tombstones.
for (int i = 0; i < kNumKeys; ++i) {
ASSERT_OK(Put(Key(i), r->RandomString(50)));
}
ASSERT_OK(Flush());
ASSERT_OK(db_->CompactRange({}, nullptr, nullptr));
ASSERT_EQ(1, NumTableFilesAtLevel(6));
for (int i = 0; i < kNumKeys; ++i) {
// We issue slightly more deletions than kAvgTrigger between visible keys
// to ensure avg skipped entries exceed kAvgTrigger.
if (i % (kAvgTrigger + 2) != 0) {
ASSERT_OK(SingleDelete(Key(i)));
}
}
// Each operation, except the first Seek, is expected to see kAvgTrigger + 1
// tombstones (from the active memtable) before it finds the next visible key.
SetPerfLevel(PerfLevel::kEnableCount);
get_perf_context()->Reset();
std::unique_ptr<Iterator> iter(db_->NewIterator(ReadOptions()));
iter->Seek(Key(1));
ASSERT_EQ(get_perf_context()->next_on_memtable_count, kAvgTrigger + 1);
iter.reset();
// Should not flush since total entries skipped is below
// memtable_op_scan_flush_trigger
ASSERT_OK(Put(Key(0), "dummy write"));
ASSERT_OK(Put(Key(0), "dummy write"));
ASSERT_OK(db_->WaitForCompact({}));
ASSERT_EQ(0, NumTableFilesAtLevel(0));
get_perf_context()->Reset();
iter.reset(db_->NewIterator(ReadOptions()));
int num_ops = 1;
uint64_t num_skipped = 0;
iter->Seek(Key(0));
ASSERT_EQ(iter->key(), Key(0));
uint64_t last_memtable_next_count =
get_perf_context()->next_on_memtable_count;
iter->Next();
num_ops++;
while (iter->Valid()) {
ASSERT_OK(iter->status());
uint64_t num_skipped_in_op =
get_perf_context()->next_on_memtable_count - last_memtable_next_count;
ASSERT_GE(num_skipped_in_op, kAvgTrigger + 1);
last_memtable_next_count = get_perf_context()->next_on_memtable_count;
num_skipped += num_skipped_in_op;
iter->Next();
num_ops++;
}
// During iterator destruction we mark memtable for flush
iter.reset();
// avg trigger
ASSERT_GE(num_skipped, kAvgTrigger * num_ops);
// memtable_op_scan_flush_trigger
ASSERT_GE(num_skipped, kMaxTrigger);
// Average hidden entries scanned from memtable per operation is more than
// kAvgTrigger and the total skipped is more than
// memtable_op_scan_flush_trigger, the current memtable should be marked for
// flush. The following two writes will trigger the flush.
ASSERT_OK(Put(Key(0), "dummy write"));
// Before a write, we schedule memtables for flush if requested.
ASSERT_OK(Put(Key(0), "dummy write"));
ASSERT_OK(db_->WaitForCompact({}));
ASSERT_EQ(1, NumTableFilesAtLevel(0));
}
TEST_P(DBIteratorTest, AverageMemtableOpsScanFlushTriggerByOverwrites) {
// Tests option memtable_avg_op_scan_flush_trigger with overwrites to keys.
Random* r = Random::GetTLSInstance();
const int kAvgTrigger = 25;
Options options;
options.create_if_missing = true;
options.memtable_op_scan_flush_trigger = 250;
options.memtable_avg_op_scan_flush_trigger = kAvgTrigger;
options.level_compaction_dynamic_level_bytes = true;
DestroyAndReopen(options);
const int kNumKeys = 100;
// Base data that will be covered by a consecutive sequence of tombstones.
for (int i = 0; i < kNumKeys; ++i) {
ASSERT_OK(Put(Key(i), r->RandomString(50)));
}
ASSERT_OK(Flush());
ASSERT_OK(db_->CompactRange({}, nullptr, nullptr));
ASSERT_EQ(1, NumTableFilesAtLevel(6));
// One visible key every 10 keys.
// Each non-visible user key has 3 non-visible entries in the active memtable.
for (int i = 0; i < kNumKeys; ++i) {
if (i % 10 != 0) {
ASSERT_OK(Put(Key(i), r->RandomString(50)));
ASSERT_OK(Put(Key(i), r->RandomString(50)));
ASSERT_OK(Delete(Key(i)));
}
}
SetPerfLevel(PerfLevel::kEnableCount);
get_perf_context()->Reset();
ReadOptions ro;
std::unique_ptr<Iterator> iter(db_->NewIterator(ro));
iter->Seek(Key(1));
ASSERT_GT(get_perf_context()->next_on_memtable_count, kAvgTrigger);
// Re-seek to trigger check for flush trigger
iter->Seek(Key(1));
// Should not flush since total entries skipped is below
// memtable_op_scan_flush_trigger
ASSERT_FALSE(static_cast<ColumnFamilyHandleImpl*>(db_->DefaultColumnFamily())
->cfd()
->mem()
->IsMarkedForFlush());
ASSERT_OK(Put(Key(0), "dummy write"));
ASSERT_OK(Put(Key(0), "dummy write"));
ASSERT_OK(db_->WaitForCompact({}));
ASSERT_EQ(0, NumTableFilesAtLevel(0));
get_perf_context()->Reset();
int num_ops = 1;
iter->Seek(Key(1));
while (iter->Valid()) {
num_ops++;
iter->Next();
}
ASSERT_GT(get_perf_context()->next_on_memtable_count, num_ops * kAvgTrigger);
// Re-seek should check conditions for marking memtable for flush
iter->Seek(Key(80));
// Average hidden entries scanned from memtable per operation is 2.
ASSERT_OK(Put(Key(0), "dummy write"));
// Before a write, we schedule memtables for flush if requested.
ASSERT_OK(Put(Key(0), "dummy write"));
ASSERT_OK(db_->WaitForCompact({}));
ASSERT_EQ(1, NumTableFilesAtLevel(0));
}
} // namespace ROCKSDB_NAMESPACE
int main(int argc, char** argv) {
-18
View File
@@ -151,7 +151,6 @@ TEST_F(DBTest, RequestIdPlumbingTest) {
options.env = env_;
// Create a mock environment to capture IODebugContext during reads
IODebugContext dbgCopy;
const std::string* captured_request_id_dbg;
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
@@ -161,8 +160,6 @@ TEST_F(DBTest, RequestIdPlumbingTest) {
captured_request_id_dbg = nullptr;
} else {
captured_request_id_dbg = dbg->request_id;
// Test IODebugContext assignment operator
dbgCopy = *dbg;
}
});
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
@@ -181,10 +178,6 @@ TEST_F(DBTest, RequestIdPlumbingTest) {
// Verify the request_id was propagated to the file system
ASSERT_NE(captured_request_id_dbg, nullptr);
ASSERT_EQ(*captured_request_id_dbg, test_request_id);
ASSERT_NE(dbgCopy.request_id, nullptr);
ASSERT_NE(dbgCopy.request_id, captured_request_id_dbg);
ASSERT_EQ(*dbgCopy.request_id, test_request_id);
}
captured_request_id_dbg = nullptr;
@@ -204,17 +197,6 @@ TEST_F(DBTest, RequestIdPlumbingTest) {
// Verify the request_id was propagated to the file system
ASSERT_NE(captured_request_id_dbg, nullptr);
ASSERT_EQ(*captured_request_id_dbg, request_id);
ASSERT_NE(dbgCopy.request_id, nullptr);
ASSERT_NE(dbgCopy.request_id, captured_request_id_dbg);
ASSERT_EQ(*dbgCopy.request_id, request_id);
// Test IODebugContext copy constructor
IODebugContext dbgCopy2(dbgCopy);
ASSERT_NE(dbgCopy2.request_id, nullptr);
ASSERT_NE(dbgCopy2.request_id, captured_request_id_dbg);
ASSERT_NE(dbgCopy2.request_id, dbgCopy.request_id);
ASSERT_EQ(*dbgCopy2.request_id, request_id);
}
// test request_id plumbing during multiget
+2 -319
View File
@@ -10,6 +10,7 @@
#include <atomic>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <memory>
#include "db/db_test_util.h"
@@ -29,7 +30,6 @@
#include "test_util/testutil.h"
#include "util/defer.h"
#include "util/random.h"
#include "util/simple_mixed_compressor.h"
#include "utilities/fault_injection_env.h"
namespace ROCKSDB_NAMESPACE {
@@ -1883,225 +1883,6 @@ TEST_F(DBTest2, CompressionOptions) {
}
}
TEST_F(DBTest2, RoundRobinManager) {
if (ZSTD_Supported()) {
auto mgr = std::make_shared<RoundRobinManager>(
GetDefaultBuiltinCompressionManager());
for (CompressionType type : {kZSTD}) {
std::vector<std::string> values;
for (bool use_wrapper : {true}) {
SCOPED_TRACE("Compression type: " + std::to_string(type) +
(use_wrapper ? " with " : " no ") + "wrapper");
Options options = CurrentOptions();
options.compression = type;
options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
options.statistics->set_stats_level(StatsLevel::kExceptTimeForMutex);
BlockBasedTableOptions bbto;
bbto.enable_index_compression = false;
options.table_factory.reset(NewBlockBasedTableFactory(bbto));
options.compression_manager = use_wrapper ? mgr : nullptr;
DestroyAndReopen(options);
Random rnd(301);
constexpr int kCount = 13;
// Highly compressible blocks, except 1 non-compressible. Half of the
// compressible are morked for bypass and 1 marked for rejection. Values
// are large enough to ensure just 1 k-v per block.
for (int i = 0; i < kCount; ++i) {
std::string value;
if (i == 6) {
// One non-compressible block
value = rnd.RandomBinaryString(20000);
} else {
test::CompressibleString(&rnd, 0.1, 20000, &value);
}
values.push_back(value);
ASSERT_OK(Put(Key(i), value));
ASSERT_EQ(Get(Key(i)), value);
}
ASSERT_OK(Flush());
// Ensure well-formed for reads
for (int i = 0; i < kCount; ++i) {
ASSERT_NE(Get(Key(i)), "NOT_FOUND");
ASSERT_EQ(Get(Key(i)), values[i]);
}
ASSERT_EQ(Get(Key(kCount)), "NOT_FOUND");
}
}
}
}
TEST_F(DBTest2, RandomMixedCompressionManager) {
if (ZSTD_Supported()) {
auto mgr = std::make_shared<RandomMixedCompressionManager>(
GetDefaultBuiltinCompressionManager());
// Currently mixedmanager only supports with preffered compression manager
// zstd
for (CompressionType type : {kZSTD}) {
std::vector<std::string> values;
for (bool use_wrapper : {true}) {
SCOPED_TRACE("Compression type: " + std::to_string(type) +
(use_wrapper ? " with " : " no ") + "wrapper");
Options options = CurrentOptions();
options.compression = type;
options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
options.statistics->set_stats_level(StatsLevel::kExceptTimeForMutex);
BlockBasedTableOptions bbto;
bbto.enable_index_compression = false;
options.table_factory.reset(NewBlockBasedTableFactory(bbto));
options.compression_manager = use_wrapper ? mgr : nullptr;
DestroyAndReopen(options);
Random rnd(301);
constexpr int kCount = 13;
// Highly compressible blocks, except 1 non-compressible. Half of the
// compressible are morked for bypass and 1 marked for rejection. Values
// are large enough to ensure just 1 k-v per block.
for (int i = 0; i < kCount; ++i) {
std::string value;
if (i == 6) {
// One non-compressible block
value = rnd.RandomBinaryString(20000);
} else {
test::CompressibleString(&rnd, 0.1, 20000, &value);
}
values.push_back(value);
ASSERT_OK(Put(Key(i), value));
ASSERT_EQ(Get(Key(i)), value);
}
ASSERT_OK(Flush());
// Ensure well-formed for reads
for (int i = 0; i < kCount; ++i) {
ASSERT_NE(Get(Key(i)), "NOT_FOUND");
ASSERT_EQ(Get(Key(i)), values[i]);
}
ASSERT_EQ(Get(Key(kCount)), "NOT_FOUND");
}
}
}
}
TEST_F(DBTest2, CompressionManagerWrapper) {
// Test that we can use a custom CompressionManager to wrap the built-in
// CompressionManager, thus adopting a custom *strategy* based on existing
// algorithms. This will "mark" some blocks (in their contents) as "do not
// compress", i.e. no attempt to compress, and some blocks as "reject
// compression", i.e. compression attempted but rejected because of ratio
// or otherwise. These cases are distinguishable for statistics that
// approximate "wasted effort".
static std::string kDoNotCompress = "do_not_compress";
static std::string kRejectCompression = "reject_compression";
struct MyCompressor : public CompressorWrapper {
using CompressorWrapper::CompressorWrapper;
Status CompressBlock(Slice uncompressed_data,
std::string* compressed_output,
CompressionType* out_compression_type,
ManagedWorkingArea* working_area) override {
auto begin = uncompressed_data.data();
auto end = uncompressed_data.data() + uncompressed_data.size();
if (std::search(begin, end, kDoNotCompress.begin(),
kDoNotCompress.end()) != end) {
// Do not attempt compression
EXPECT_EQ(*out_compression_type, kNoCompression);
return Status::OK();
} else if (std::search(begin, end, kRejectCompression.begin(),
kRejectCompression.end()) != end) {
// Simulate attempted & rejected compression
*compressed_output = "blah";
EXPECT_EQ(*out_compression_type, kNoCompression);
return Status::OK();
} else {
return wrapped_->CompressBlock(uncompressed_data, compressed_output,
out_compression_type, working_area);
}
}
};
struct MyManager : public CompressionManagerWrapper {
using CompressionManagerWrapper::CompressionManagerWrapper;
const char* Name() const override { return wrapped_->Name(); }
std::unique_ptr<Compressor> GetCompressorForSST(
const FilterBuildingContext& context, const CompressionOptions& opts,
CompressionType preferred) override {
return std::make_unique<MyCompressor>(
wrapped_->GetCompressorForSST(context, opts, preferred));
}
};
auto mgr = std::make_shared<MyManager>(GetDefaultBuiltinCompressionManager());
for (CompressionType type : GetSupportedCompressions()) {
for (bool use_wrapper : {false, true}) {
if (type == kNoCompression) {
continue;
}
SCOPED_TRACE("Compression type: " + std::to_string(type) +
(use_wrapper ? " with " : " no ") + "wrapper");
Options options = CurrentOptions();
options.compression = type;
options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
options.statistics->set_stats_level(StatsLevel::kExceptTimeForMutex);
BlockBasedTableOptions bbto;
bbto.enable_index_compression = false;
options.table_factory.reset(NewBlockBasedTableFactory(bbto));
options.compression_manager = use_wrapper ? mgr : nullptr;
DestroyAndReopen(options);
auto PopStat = [&](Tickers t) -> uint64_t {
return options.statistics->getAndResetTickerCount(t);
};
Random rnd(301);
constexpr int kCount = 13;
// Highly compressible blocks, except 1 non-compressible. Half of the
// compressible are morked for bypass and 1 marked for rejection. Values
// are large enough to ensure just 1 k-v per block.
for (int i = 0; i < kCount; ++i) {
std::string value;
if (i == 6) {
// One non-compressible block
value = rnd.RandomBinaryString(20000);
} else {
test::CompressibleString(&rnd, 0.1, 20000, &value);
if ((i % 2) == 0) {
// Half for bypass
value += kDoNotCompress;
} else if (i == 7) {
// One for rejection
value += kRejectCompression;
}
}
ASSERT_OK(Put(Key(i), value));
}
ASSERT_OK(Flush());
if (use_wrapper) {
EXPECT_EQ(kCount / 2 - 1, PopStat(NUMBER_BLOCK_COMPRESSED));
EXPECT_EQ(kCount / 2, PopStat(NUMBER_BLOCK_COMPRESSION_BYPASSED));
EXPECT_EQ(1 + 1, PopStat(NUMBER_BLOCK_COMPRESSION_REJECTED));
} else {
EXPECT_EQ(kCount - 1, PopStat(NUMBER_BLOCK_COMPRESSED));
EXPECT_EQ(0, PopStat(NUMBER_BLOCK_COMPRESSION_BYPASSED));
EXPECT_EQ(1, PopStat(NUMBER_BLOCK_COMPRESSION_REJECTED));
}
// Ensure well-formed for reads
for (int i = 0; i < kCount; ++i) {
ASSERT_NE(Get(Key(i)), "NOT_FOUND");
}
ASSERT_EQ(Get(Key(kCount)), "NOT_FOUND");
}
}
}
class CompactionStallTestListener : public EventListener {
public:
CompactionStallTestListener()
@@ -3227,7 +3008,7 @@ TEST_F(DBTest2, PausingManualCompaction1) {
"TestCompactFiles:PausingManualCompaction:3", [&](void* arg) {
auto paused = static_cast<std::atomic<int>*>(arg);
// CompactFiles() relies on manual_compactions_paused to
// determine if this compaction should be paused or not
// determine if thie compaction should be paused or not
ASSERT_EQ(0, paused->load(std::memory_order_acquire));
paused->fetch_add(1, std::memory_order_release);
});
@@ -3339,7 +3120,6 @@ TEST_F(DBTest2, PausingManualCompaction3) {
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
dbfull()->DisableManualCompaction();
ASSERT_TRUE(dbfull()
->CompactRange(compact_options, nullptr, nullptr)
.IsManualCompactionPaused());
@@ -5639,103 +5419,6 @@ TEST_F(DBTest2, TestCompactFiles) {
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearAllCallBacks();
}
TEST_F(DBTest2, TestCancelCompactFiles) {
SyncPoint::GetInstance()->EnableProcessing();
Options options;
options.env = env_;
options.num_levels = 2;
options.disable_auto_compactions = true;
Reopen(options);
auto* handle = db_->DefaultColumnFamily();
ASSERT_EQ(db_->NumberLevels(handle), 2);
ROCKSDB_NAMESPACE::SstFileWriter sst_file_writer{
ROCKSDB_NAMESPACE::EnvOptions(), options};
// ingest large SST files
std::vector<std::string> external_sst_file_names;
int key_counter = 0;
const int num_keys_per_file = 100000;
const int num_files = 10;
for (int i = 0; i < num_files; ++i) {
std::string file_name =
dbname_ + "/test_compact_files" + std::to_string(i) + ".sst_t";
external_sst_file_names.push_back(file_name);
ASSERT_OK(sst_file_writer.Open(file_name));
for (int j = 0; j < num_keys_per_file; ++j) {
ASSERT_OK(sst_file_writer.Put(Key(j + num_keys_per_file * key_counter),
std::to_string(j)));
}
key_counter += 1;
ASSERT_OK(sst_file_writer.Finish());
}
ASSERT_OK(db_->IngestExternalFile(handle, external_sst_file_names,
IngestExternalFileOptions()));
ASSERT_EQ(NumTableFilesAtLevel(1, 0), num_files);
std::vector<std::string> files;
GetSstFiles(env_, dbname_, &files);
ASSERT_EQ(files.size(), num_files);
// Test that 0 compactions happen - canceled is set to True initially
CompactionOptions compaction_options;
std::atomic<bool> canceled(true);
compaction_options.canceled = &canceled;
ASSERT_TRUE(db_->CompactFiles(compaction_options, handle, files, 1)
.IsManualCompactionPaused());
ASSERT_EQ(NumTableFilesAtLevel(1, 0), num_files);
// Test cancellation before the check to cancel compaction happens -
// compaction should not occur
bool disable_compaction = false;
compaction_options.canceled->store(false, std::memory_order_release);
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
"TestCancelCompactFiles:SuccessfulCompaction", [&](void* arg) {
auto paused = static_cast<std::atomic<int>*>(arg);
if (disable_compaction) {
db_->DisableManualCompaction();
ASSERT_EQ(1, paused->load(std::memory_order_acquire));
} else {
compaction_options.canceled->store(true, std::memory_order_release);
ASSERT_EQ(0, paused->load(std::memory_order_acquire));
}
});
ASSERT_TRUE(db_->CompactFiles(compaction_options, handle, files, 1)
.IsManualCompactionPaused());
ASSERT_EQ(NumTableFilesAtLevel(1, 0), num_files);
// DisableManualCompaction() should successfully cancel compaction
disable_compaction = true;
compaction_options.canceled->store(false, std::memory_order_release);
ASSERT_TRUE(db_->CompactFiles(compaction_options, handle, files, 1)
.IsManualCompactionPaused());
ASSERT_EQ(NumTableFilesAtLevel(1, 0), num_files);
// unlike CompactRange, value of compaction_options.canceled will be
// unaffected by calling DisableManualCompactions()
ASSERT_FALSE(compaction_options.canceled->load());
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearAllCallBacks();
db_->EnableManualCompaction();
// Test cancelation after the check to cancel compaction - compaction should
// occur, leaving only 1 file
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
"CompactFilesImpl:0", [&](void* /*arg*/) {
compaction_options.canceled->store(true, std::memory_order_release);
});
compaction_options.canceled->store(false, std::memory_order_release);
ASSERT_OK(db_->CompactFiles(compaction_options, handle, files, 1));
ASSERT_EQ(NumTableFilesAtLevel(1, 0), 1);
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearAllCallBacks();
}
TEST_F(DBTest2, MultiDBParallelOpenTest) {
const int kNumDbs = 2;
Options options = CurrentOptions();
+43 -63
View File
@@ -1672,75 +1672,55 @@ TEST_P(DBTestUniversalCompaction, ConcurrentBottomPriLowPriCompactions) {
}
const int kNumFilesTrigger = 3;
Env::Default()->SetBackgroundThreads(1, Env::Priority::BOTTOM);
Options options = CurrentOptions();
options.compaction_style = kCompactionStyleUniversal;
options.max_background_compactions = 2;
options.num_levels = num_levels_;
options.write_buffer_size = 100 << 10; // 100KB
options.target_file_size_base = 32 << 10; // 32KB
options.level0_file_num_compaction_trigger = kNumFilesTrigger;
// Trigger compaction if size amplification exceeds 110%
options.compaction_options_universal.max_size_amplification_percent = 110;
DestroyAndReopen(options);
for (bool universal_reduce_file_locking : {true, false}) {
Options options = CurrentOptions();
options.compaction_style = kCompactionStyleUniversal;
options.compaction_options_universal.reduce_file_locking =
universal_reduce_file_locking;
options.max_background_compactions = 2;
options.num_levels = num_levels_;
options.write_buffer_size = 100 << 10; // 100KB
options.target_file_size_base = 32 << 10; // 32KB
options.level0_file_num_compaction_trigger = kNumFilesTrigger;
// Trigger compaction if size amplification exceeds 110%
options.compaction_options_universal.max_size_amplification_percent = 110;
DestroyAndReopen(options);
// Need to get a token to enable compaction parallelism up to
// `max_background_compactions` jobs.
auto pressure_token =
dbfull()->TEST_write_controler().GetCompactionPressureToken();
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
{// wait for the full compaction to be picked before adding files intended
// for the second one.
{"DBImpl::BackgroundCompaction:ForwardToBottomPriPool",
"DBTestUniversalCompaction:ConcurrentBottomPriLowPriCompactions:0"},
// the full (bottom-pri) compaction waits until a partial (low-pri)
// compaction has started to verify they can run in parallel.
{"DBImpl::BackgroundCompaction:NonTrivial",
"DBImpl::BGWorkBottomCompaction"}});
SyncPoint::GetInstance()->EnableProcessing();
// Need to get a token to enable compaction parallelism up to
// `max_background_compactions` jobs.
auto pressure_token =
dbfull()->TEST_write_controler().GetCompactionPressureToken();
if (universal_reduce_file_locking) {
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
{// Wait for the full compaction to be repicked before adding files
// intended for the second compaction.
{"DBImpl::BackgroundCompaction():AfterPickCompactionBottomPri",
"DBTestUniversalCompaction:ConcurrentBottomPriLowPriCompactions:0"},
// Wait for the second compaction to run before running the full
// compaction to verify they can run in parallel
{"DBImpl::BackgroundCompaction:NonTrivial:BeforeRun",
"DBImpl::BackgroundCompaction:NonTrivial:BeforeRunBottomPri"}});
} else {
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
{// Wait for the full compaction to be forwarded before adding files
// intended for the second compaction.
{"DBImpl::BackgroundCompaction:ForwardToBottomPriPool",
"DBTestUniversalCompaction:ConcurrentBottomPriLowPriCompactions:0"},
// Wait for the second compaction to run before running the full
// compaction to verify they can run in parallel
{"DBImpl::BackgroundCompaction:NonTrivial:BeforeRun",
"DBImpl::BackgroundCompaction:NonTrivial:BeforeRunBottomPri"}});
Random rnd(301);
for (int i = 0; i < 2; ++i) {
for (int num = 0; num < kNumFilesTrigger; num++) {
int key_idx = 0;
GenerateNewFile(&rnd, &key_idx, true /* no_wait */);
// use no_wait above because that one waits for flush and compaction. We
// don't want to wait for compaction because the full compaction is
// intentionally blocked while more files are flushed.
ASSERT_OK(dbfull()->TEST_WaitForFlushMemTable());
}
SyncPoint::GetInstance()->EnableProcessing();
Random rnd(301);
for (int i = 0; i < 2; ++i) {
for (int num = 0; num < kNumFilesTrigger; num++) {
int key_idx = 0;
GenerateNewFile(&rnd, &key_idx, true /* no_wait */);
// use no_wait above because that one waits for flush and compaction. We
// don't want to wait for compaction because the full compaction is
// intentionally blocked while more files are flushed.
ASSERT_OK(dbfull()->TEST_WaitForFlushMemTable());
}
if (i == 0) {
TEST_SYNC_POINT(
"DBTestUniversalCompaction:ConcurrentBottomPriLowPriCompactions:0");
}
if (i == 0) {
TEST_SYNC_POINT(
"DBTestUniversalCompaction:ConcurrentBottomPriLowPriCompactions:0");
}
ASSERT_OK(dbfull()->TEST_WaitForCompact());
// First compaction should output to bottom level. Second should output to
// L0 since older L0 files pending compaction prevent it from being placed
// lower.
ASSERT_EQ(NumSortedRuns(), 2);
ASSERT_GT(NumTableFilesAtLevel(0), 0);
ASSERT_GT(NumTableFilesAtLevel(num_levels_ - 1), 0);
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
}
ASSERT_OK(dbfull()->TEST_WaitForCompact());
// First compaction should output to bottom level. Second should output to L0
// since older L0 files pending compaction prevent it from being placed lower.
ASSERT_EQ(NumSortedRuns(), 2);
ASSERT_GT(NumTableFilesAtLevel(0), 0);
ASSERT_GT(NumTableFilesAtLevel(num_levels_ - 1), 0);
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
Env::Default()->SetBackgroundThreads(0, Env::Priority::BOTTOM);
}
+15 -33
View File
@@ -77,12 +77,7 @@ void EventHelpers::LogAndNotifyTableFileCreationFinished(
TableFileCreationReason reason, const Status& s,
const std::string& file_checksum,
const std::string& file_checksum_func_name) {
if (!event_logger && listeners.empty()) {
s.PermitUncheckedError();
return;
}
if (event_logger) {
if (s.ok() && event_logger) {
JSONWriter jwriter;
AppendCurrentTime(&jwriter);
jwriter << "cf_name" << cf_name << "job" << job_id << "event"
@@ -170,8 +165,6 @@ void EventHelpers::LogAndNotifyTableFileCreationFinished(
jwriter << "oldest_blob_file_number" << oldest_blob_file_number;
}
jwriter << "status" << s.ToString();
jwriter.EndObject();
event_logger->Log(jwriter);
@@ -202,22 +195,18 @@ void EventHelpers::LogAndNotifyTableFileDeletion(
const std::string& file_path, const Status& status,
const std::string& dbname,
const std::vector<std::shared_ptr<EventListener>>& listeners) {
if (!event_logger && listeners.empty()) {
status.PermitUncheckedError();
return;
JSONWriter jwriter;
AppendCurrentTime(&jwriter);
jwriter << "job" << job_id << "event" << "table_file_deletion"
<< "file_number" << file_number;
if (!status.ok()) {
jwriter << "status" << status.ToString();
}
if (event_logger) {
JSONWriter jwriter;
AppendCurrentTime(&jwriter);
jwriter.EndObject();
jwriter << "job" << job_id << "event" << "table_file_deletion"
<< "file_number" << file_number << "status" << status.ToString();
jwriter.EndObject();
event_logger->Log(jwriter);
}
event_logger->Log(jwriter);
if (listeners.empty()) {
return;
@@ -285,12 +274,7 @@ void EventHelpers::LogAndNotifyBlobFileCreationFinished(
const std::string& file_checksum,
const std::string& file_checksum_func_name, uint64_t total_blob_count,
uint64_t total_blob_bytes) {
if (!event_logger && listeners.empty()) {
s.PermitUncheckedError();
return;
}
if (event_logger) {
if (s.ok() && event_logger) {
JSONWriter jwriter;
AppendCurrentTime(&jwriter);
jwriter << "cf_name" << cf_name << "job" << job_id << "event"
@@ -321,17 +305,15 @@ void EventHelpers::LogAndNotifyBlobFileDeletion(
const std::vector<std::shared_ptr<EventListener>>& listeners, int job_id,
uint64_t file_number, const std::string& file_path, const Status& status,
const std::string& dbname) {
if (!event_logger && listeners.empty()) {
status.PermitUncheckedError();
return;
}
if (event_logger) {
JSONWriter jwriter;
AppendCurrentTime(&jwriter);
jwriter << "job" << job_id << "event" << "blob_file_deletion"
<< "file_number" << file_number << "status" << status.ToString();
<< "file_number" << file_number;
if (!status.ok()) {
jwriter << "status" << status.ToString();
}
jwriter.EndObject();
event_logger->Log(jwriter);
+34 -27
View File
@@ -92,10 +92,12 @@ FlushJob::FlushJob(
const MutableCFOptions& mutable_cf_options, uint64_t max_memtable_id,
const FileOptions& file_options, VersionSet* versions,
InstrumentedMutex* db_mutex, std::atomic<bool>* shutting_down,
JobContext* job_context, FlushReason flush_reason, LogBuffer* log_buffer,
FSDirectory* db_directory, FSDirectory* output_file_directory,
CompressionType output_compression, Statistics* stats,
EventLogger* event_logger, bool measure_io_stats,
std::vector<SequenceNumber> existing_snapshots,
SequenceNumber earliest_write_conflict_snapshot,
SnapshotChecker* snapshot_checker, JobContext* job_context,
FlushReason flush_reason, LogBuffer* log_buffer, FSDirectory* db_directory,
FSDirectory* output_file_directory, CompressionType output_compression,
Statistics* stats, EventLogger* event_logger, bool measure_io_stats,
const bool sync_output_directory, const bool write_manifest,
Env::Priority thread_pri, const std::shared_ptr<IOTracer>& io_tracer,
std::shared_ptr<const SeqnoToTimeMapping> seqno_to_time_mapping,
@@ -112,7 +114,12 @@ FlushJob::FlushJob(
versions_(versions),
db_mutex_(db_mutex),
shutting_down_(shutting_down),
earliest_snapshot_(job_context->GetEarliestSnapshotSequence()),
existing_snapshots_(std::move(existing_snapshots)),
earliest_snapshot_(existing_snapshots_.empty()
? kMaxSequenceNumber
: existing_snapshots_.at(0)),
earliest_write_conflict_snapshot_(earliest_write_conflict_snapshot),
snapshot_checker_(snapshot_checker),
job_context_(job_context),
flush_reason_(flush_reason),
log_buffer_(log_buffer),
@@ -133,7 +140,6 @@ FlushJob::FlushJob(
full_history_ts_low_(std::move(full_history_ts_low)),
blob_callback_(blob_callback),
seqno_to_time_mapping_(std::move(seqno_to_time_mapping)) {
assert(job_context->snapshot_context_initialized);
// Update the thread status to indicate flush.
ReportStartedFlush();
TEST_SYNC_POINT("FlushJob::FlushJob()");
@@ -450,7 +456,7 @@ Status FlushJob::MemPurge() {
const std::string* const full_history_ts_low = &(cfd_->GetFullHistoryTsLow());
std::unique_ptr<CompactionRangeDelAggregator> range_del_agg(
new CompactionRangeDelAggregator(&(cfd_->internal_comparator()),
job_context_->snapshot_seqs,
existing_snapshots_,
full_history_ts_low));
for (auto& rd_iter : range_del_iters) {
range_del_agg->AddTombstones(std::move(rd_iter));
@@ -489,19 +495,19 @@ Status FlushJob::MemPurge() {
Env* env = db_options_.env;
assert(env);
MergeHelper merge(env, (cfd_->internal_comparator()).user_comparator(),
(ioptions.merge_operator).get(), compaction_filter.get(),
ioptions.logger,
true /* internal key corruption is not ok */,
job_context_->GetLatestSnapshotSequence(),
job_context_->snapshot_checker);
MergeHelper merge(
env, (cfd_->internal_comparator()).user_comparator(),
(ioptions.merge_operator).get(), compaction_filter.get(),
ioptions.logger, true /* internal key corruption is not ok */,
existing_snapshots_.empty() ? 0 : existing_snapshots_.back(),
snapshot_checker_);
assert(job_context_);
SequenceNumber job_snapshot_seq = job_context_->GetJobSnapshotSequence();
const std::atomic<bool> kManualCompactionCanceledFalse{false};
CompactionIterator c_iter(
iter.get(), (cfd_->internal_comparator()).user_comparator(), &merge,
kMaxSequenceNumber, &job_context_->snapshot_seqs, earliest_snapshot_,
job_context_->earliest_write_conflict_snapshot,
job_context_->GetJobSnapshotSequence(), job_context_->snapshot_checker,
kMaxSequenceNumber, &existing_snapshots_, earliest_snapshot_,
earliest_write_conflict_snapshot_, job_snapshot_seq, snapshot_checker_,
env, ShouldReportDetailedTime(env, ioptions.stats),
true /* internal key corruption is not ok */, range_del_agg.get(),
nullptr, ioptions.allow_data_in_errors,
@@ -755,7 +761,7 @@ bool FlushJob::MemPurgeDecider(double threshold) {
// Pick the oldest existing snapshot that is more recent
// than the sequence number of the sampled entry.
min_seqno_snapshot = kMaxSequenceNumber;
for (SequenceNumber seq_num : job_context_->snapshot_seqs) {
for (SequenceNumber seq_num : existing_snapshots_) {
if (seq_num > res.sequence && seq_num < min_seqno_snapshot) {
min_seqno_snapshot = seq_num;
}
@@ -994,19 +1000,20 @@ Status FlushJob::WriteLevel0Table() {
preclude_last_level_min_seqno_ == kMaxSequenceNumber
? preclude_last_level_min_seqno_
: std::min(earliest_snapshot_, preclude_last_level_min_seqno_));
const SequenceNumber job_snapshot_seq =
job_context_->GetJobSnapshotSequence();
s = BuildTable(
dbname_, versions_, db_options_, tboptions, file_options_,
cfd_->table_cache(), iter.get(), std::move(range_del_iters), &meta_,
&blob_file_additions, job_context_->snapshot_seqs, earliest_snapshot_,
job_context_->earliest_write_conflict_snapshot,
job_context_->GetJobSnapshotSequence(),
job_context_->snapshot_checker,
mutable_cf_options_.paranoid_file_checks, cfd_->internal_stats(),
&io_s, io_tracer_, BlobFileCreationReason::kFlush,
seqno_to_time_mapping_.get(), event_logger_, job_context_->job_id,
&table_properties_, write_hint, full_history_ts_low, blob_callback_,
base_, &memtable_payload_bytes, &memtable_garbage_bytes,
&flush_stats);
&blob_file_additions, existing_snapshots_, earliest_snapshot_,
earliest_write_conflict_snapshot_, job_snapshot_seq,
snapshot_checker_, mutable_cf_options_.paranoid_file_checks,
cfd_->internal_stats(), &io_s, io_tracer_,
BlobFileCreationReason::kFlush, seqno_to_time_mapping_.get(),
event_logger_, job_context_->job_id, &table_properties_, write_hint,
full_history_ts_low, blob_callback_, base_, &memtable_payload_bytes,
&memtable_garbage_bytes, &flush_stats);
TEST_SYNC_POINT_CALLBACK("FlushJob::WriteLevel0Table:s", &s);
// TODO: Cleanup io_status in BuildTable and table builders
assert(!s.ok() || io_s.ok());
+8 -3
View File
@@ -63,9 +63,11 @@ class FlushJob {
const MutableCFOptions& mutable_cf_options, uint64_t max_memtable_id,
const FileOptions& file_options, VersionSet* versions,
InstrumentedMutex* db_mutex, std::atomic<bool>* shutting_down,
JobContext* job_context, FlushReason flush_reason,
LogBuffer* log_buffer, FSDirectory* db_directory,
FSDirectory* output_file_directory,
std::vector<SequenceNumber> existing_snapshots,
SequenceNumber earliest_write_conflict_snapshot,
SnapshotChecker* snapshot_checker, JobContext* job_context,
FlushReason flush_reason, LogBuffer* log_buffer,
FSDirectory* db_directory, FSDirectory* output_file_directory,
CompressionType output_compression, Statistics* stats,
EventLogger* event_logger, bool measure_io_stats,
const bool sync_output_directory, const bool write_manifest,
@@ -165,7 +167,10 @@ class FlushJob {
VersionSet* versions_;
InstrumentedMutex* db_mutex_;
std::atomic<bool>* shutting_down_;
std::vector<SequenceNumber> existing_snapshots_;
SequenceNumber earliest_snapshot_;
SequenceNumber earliest_write_conflict_snapshot_;
SnapshotChecker* snapshot_checker_;
JobContext* job_context_;
FlushReason flush_reason_;
LogBuffer* log_buffer_;
+65 -65
View File
@@ -186,16 +186,16 @@ TEST_F(FlushJobTest, Empty) {
JobContext job_context(0);
auto cfd = versions_->GetColumnFamilySet()->GetDefault();
EventLogger event_logger(db_options_.info_log.get());
job_context.InitSnapshotContext(nullptr, nullptr, kMaxSequenceNumber, {});
FlushJob flush_job(dbname_, versions_->GetColumnFamilySet()->GetDefault(),
db_options_, cfd->GetLatestMutableCFOptions(),
std::numeric_limits<uint64_t>::max() /* memtable_id */,
env_options_, versions_.get(), &mutex_, &shutting_down_,
&job_context, FlushReason::kTest, nullptr, nullptr,
nullptr, kNoCompression, nullptr, &event_logger, false,
true /* sync_output_directory */,
true /* write_manifest */, Env::Priority::USER,
nullptr /*IOTracer*/, empty_seqno_to_time_mapping_);
SnapshotChecker* snapshot_checker = nullptr; // not relavant
FlushJob flush_job(
dbname_, versions_->GetColumnFamilySet()->GetDefault(), db_options_,
cfd->GetLatestMutableCFOptions(),
std::numeric_limits<uint64_t>::max() /* memtable_id */, env_options_,
versions_.get(), &mutex_, &shutting_down_, {}, kMaxSequenceNumber,
snapshot_checker, &job_context, FlushReason::kTest, nullptr, nullptr,
nullptr, kNoCompression, nullptr, &event_logger, false,
true /* sync_output_directory */, true /* write_manifest */,
Env::Priority::USER, nullptr /*IOTracer*/, empty_seqno_to_time_mapping_);
{
InstrumentedMutexLock l(&mutex_);
flush_job.PickMemTable();
@@ -272,16 +272,16 @@ TEST_F(FlushJobTest, NonEmpty) {
}
EventLogger event_logger(db_options_.info_log.get());
job_context.InitSnapshotContext(nullptr, nullptr, kMaxSequenceNumber, {});
FlushJob flush_job(dbname_, versions_->GetColumnFamilySet()->GetDefault(),
db_options_, cfd->GetLatestMutableCFOptions(),
std::numeric_limits<uint64_t>::max() /* memtable_id */,
env_options_, versions_.get(), &mutex_, &shutting_down_,
&job_context, FlushReason::kTest, nullptr, nullptr,
nullptr, kNoCompression, db_options_.statistics.get(),
&event_logger, true, true /* sync_output_directory */,
true /* write_manifest */, Env::Priority::USER,
nullptr /*IOTracer*/, empty_seqno_to_time_mapping_);
SnapshotChecker* snapshot_checker = nullptr; // not relavant
FlushJob flush_job(
dbname_, versions_->GetColumnFamilySet()->GetDefault(), db_options_,
cfd->GetLatestMutableCFOptions(),
std::numeric_limits<uint64_t>::max() /* memtable_id */, env_options_,
versions_.get(), &mutex_, &shutting_down_, {}, kMaxSequenceNumber,
snapshot_checker, &job_context, FlushReason::kTest, nullptr, nullptr,
nullptr, kNoCompression, db_options_.statistics.get(), &event_logger,
true, true /* sync_output_directory */, true /* write_manifest */,
Env::Priority::USER, nullptr /*IOTracer*/, empty_seqno_to_time_mapping_);
HistogramData hist;
FileMetaData file_meta;
@@ -332,18 +332,18 @@ TEST_F(FlushJobTest, FlushMemTablesSingleColumnFamily) {
}
EventLogger event_logger(db_options_.info_log.get());
SnapshotChecker* snapshot_checker = nullptr; // not relavant
assert(memtable_ids.size() == num_mems);
uint64_t smallest_memtable_id = memtable_ids.front();
uint64_t flush_memtable_id = smallest_memtable_id + num_mems_to_flush - 1;
job_context.InitSnapshotContext(nullptr, nullptr, kMaxSequenceNumber, {});
FlushJob flush_job(
dbname_, versions_->GetColumnFamilySet()->GetDefault(), db_options_,
cfd->GetLatestMutableCFOptions(), flush_memtable_id, env_options_,
versions_.get(), &mutex_, &shutting_down_, &job_context,
FlushReason::kTest, nullptr, nullptr, nullptr, kNoCompression,
db_options_.statistics.get(), &event_logger, true,
true /* sync_output_directory */, true /* write_manifest */,
versions_.get(), &mutex_, &shutting_down_, {}, kMaxSequenceNumber,
snapshot_checker, &job_context, FlushReason::kTest, nullptr, nullptr,
nullptr, kNoCompression, db_options_.statistics.get(), &event_logger,
true, true /* sync_output_directory */, true /* write_manifest */,
Env::Priority::USER, nullptr /*IOTracer*/, empty_seqno_to_time_mapping_);
HistogramData hist;
FileMetaData file_meta;
@@ -405,17 +405,18 @@ TEST_F(FlushJobTest, FlushMemtablesMultipleColumnFamilies) {
}
EventLogger event_logger(db_options_.info_log.get());
SnapshotChecker* snapshot_checker = nullptr; // not relevant
std::vector<std::unique_ptr<FlushJob>> flush_jobs;
k = 0;
job_context.InitSnapshotContext(nullptr, nullptr, kMaxSequenceNumber, {});
for (auto cfd : all_cfds) {
std::vector<SequenceNumber> snapshot_seqs;
flush_jobs.emplace_back(new FlushJob(
dbname_, cfd, db_options_, cfd->GetLatestMutableCFOptions(),
memtable_ids[k], env_options_, versions_.get(), &mutex_,
&shutting_down_, &job_context, FlushReason::kTest, nullptr, nullptr,
nullptr, kNoCompression, db_options_.statistics.get(), &event_logger,
true, false /* sync_output_directory */, false /* write_manifest */,
&shutting_down_, snapshot_seqs, kMaxSequenceNumber, snapshot_checker,
&job_context, FlushReason::kTest, nullptr, nullptr, nullptr,
kNoCompression, db_options_.statistics.get(), &event_logger, true,
false /* sync_output_directory */, false /* write_manifest */,
Env::Priority::USER, nullptr /*IOTracer*/,
empty_seqno_to_time_mapping_));
k++;
@@ -531,17 +532,16 @@ TEST_F(FlushJobTest, Snapshots) {
}
EventLogger event_logger(db_options_.info_log.get());
job_context.InitSnapshotContext(nullptr, nullptr, kMaxSequenceNumber,
std::move(snapshots));
FlushJob flush_job(dbname_, versions_->GetColumnFamilySet()->GetDefault(),
db_options_, cfd->GetLatestMutableCFOptions(),
std::numeric_limits<uint64_t>::max() /* memtable_id */,
env_options_, versions_.get(), &mutex_, &shutting_down_,
&job_context, FlushReason::kTest, nullptr, nullptr,
nullptr, kNoCompression, db_options_.statistics.get(),
&event_logger, true, true /* sync_output_directory */,
true /* write_manifest */, Env::Priority::USER,
nullptr /*IOTracer*/, empty_seqno_to_time_mapping_);
SnapshotChecker* snapshot_checker = nullptr; // not relavant
FlushJob flush_job(
dbname_, versions_->GetColumnFamilySet()->GetDefault(), db_options_,
cfd->GetLatestMutableCFOptions(),
std::numeric_limits<uint64_t>::max() /* memtable_id */, env_options_,
versions_.get(), &mutex_, &shutting_down_, snapshots, kMaxSequenceNumber,
snapshot_checker, &job_context, FlushReason::kTest, nullptr, nullptr,
nullptr, kNoCompression, db_options_.statistics.get(), &event_logger,
true, true /* sync_output_directory */, true /* write_manifest */,
Env::Priority::USER, nullptr /*IOTracer*/, empty_seqno_to_time_mapping_);
mutex_.Lock();
flush_job.PickMemTable();
ASSERT_OK(flush_job.Run());
@@ -585,18 +585,18 @@ TEST_F(FlushJobTest, GetRateLimiterPriorityForWrite) {
}
EventLogger event_logger(db_options_.info_log.get());
SnapshotChecker* snapshot_checker = nullptr; // not relavant
assert(memtable_ids.size() == num_mems);
uint64_t smallest_memtable_id = memtable_ids.front();
uint64_t flush_memtable_id = smallest_memtable_id + num_mems_to_flush - 1;
job_context.InitSnapshotContext(nullptr, nullptr, kMaxSequenceNumber, {});
FlushJob flush_job(
dbname_, versions_->GetColumnFamilySet()->GetDefault(), db_options_,
cfd->GetLatestMutableCFOptions(), flush_memtable_id, env_options_,
versions_.get(), &mutex_, &shutting_down_, &job_context,
FlushReason::kTest, nullptr, nullptr, nullptr, kNoCompression,
db_options_.statistics.get(), &event_logger, true,
true /* sync_output_directory */, true /* write_manifest */,
versions_.get(), &mutex_, &shutting_down_, {}, kMaxSequenceNumber,
snapshot_checker, &job_context, FlushReason::kTest, nullptr, nullptr,
nullptr, kNoCompression, db_options_.statistics.get(), &event_logger,
true, true /* sync_output_directory */, true /* write_manifest */,
Env::Priority::USER, nullptr /*IOTracer*/, empty_seqno_to_time_mapping_);
// When the state from WriteController is normal.
@@ -658,16 +658,16 @@ TEST_F(FlushJobTest, ReplaceTimedPutWriteTimeWithPreferredSeqno) {
}
EventLogger event_logger(db_options_.info_log.get());
job_context.InitSnapshotContext(nullptr, nullptr, kMaxSequenceNumber, {});
FlushJob flush_job(dbname_, versions_->GetColumnFamilySet()->GetDefault(),
db_options_, cfd->GetLatestMutableCFOptions(),
std::numeric_limits<uint64_t>::max() /* memtable_id */,
env_options_, versions_.get(), &mutex_, &shutting_down_,
&job_context, FlushReason::kTest, nullptr, nullptr,
nullptr, kNoCompression, db_options_.statistics.get(),
&event_logger, true, true /* sync_output_directory */,
true /* write_manifest */, Env::Priority::USER,
nullptr /*IOTracer*/, seqno_to_time_mapping);
SnapshotChecker* snapshot_checker = nullptr; // not relevant
FlushJob flush_job(
dbname_, versions_->GetColumnFamilySet()->GetDefault(), db_options_,
cfd->GetLatestMutableCFOptions(),
std::numeric_limits<uint64_t>::max() /* memtable_id */, env_options_,
versions_.get(), &mutex_, &shutting_down_, {}, kMaxSequenceNumber,
snapshot_checker, &job_context, FlushReason::kTest, nullptr, nullptr,
nullptr, kNoCompression, db_options_.statistics.get(), &event_logger,
true, true /* sync_output_directory */, true /* write_manifest */,
Env::Priority::USER, nullptr /*IOTracer*/, seqno_to_time_mapping);
FileMetaData file_meta;
mutex_.Lock();
@@ -761,19 +761,19 @@ TEST_P(FlushJobTimestampTest, AllKeysExpired) {
}
std::vector<SequenceNumber> snapshots;
constexpr SnapshotChecker* const snapshot_checker = nullptr;
JobContext job_context(0);
EventLogger event_logger(db_options_.info_log.get());
std::string full_history_ts_low;
PutFixed64(&full_history_ts_low, std::numeric_limits<uint64_t>::max());
cfd->SetFullHistoryTsLow(full_history_ts_low);
job_context.InitSnapshotContext(nullptr, nullptr, kMaxSequenceNumber, {});
FlushJob flush_job(
dbname_, cfd, db_options_, cfd->GetLatestMutableCFOptions(),
std::numeric_limits<uint64_t>::max() /* memtable_id */, env_options_,
versions_.get(), &mutex_, &shutting_down_, &job_context,
FlushReason::kTest, nullptr, nullptr, nullptr, kNoCompression,
db_options_.statistics.get(), &event_logger, true,
true /* sync_output_directory */, true /* write_manifest */,
versions_.get(), &mutex_, &shutting_down_, snapshots, kMaxSequenceNumber,
snapshot_checker, &job_context, FlushReason::kTest, nullptr, nullptr,
nullptr, kNoCompression, db_options_.statistics.get(), &event_logger,
true, true /* sync_output_directory */, true /* write_manifest */,
Env::Priority::USER, nullptr /*IOTracer*/, empty_seqno_to_time_mapping_,
/*db_id=*/"",
/*db_session_id=*/"", full_history_ts_low);
@@ -823,8 +823,8 @@ TEST_P(FlushJobTimestampTest, NoKeyExpired) {
}
std::vector<SequenceNumber> snapshots;
SnapshotChecker* const snapshot_checker = nullptr;
JobContext job_context(0);
job_context.InitSnapshotContext(nullptr, nullptr, kMaxSequenceNumber, {});
EventLogger event_logger(db_options_.info_log.get());
std::string full_history_ts_low;
PutFixed64(&full_history_ts_low, 0);
@@ -832,10 +832,10 @@ TEST_P(FlushJobTimestampTest, NoKeyExpired) {
FlushJob flush_job(
dbname_, cfd, db_options_, cfd->GetLatestMutableCFOptions(),
std::numeric_limits<uint64_t>::max() /* memtable_id */, env_options_,
versions_.get(), &mutex_, &shutting_down_, &job_context,
FlushReason::kTest, nullptr, nullptr, nullptr, kNoCompression,
db_options_.statistics.get(), &event_logger, true,
true /* sync_output_directory */, true /* write_manifest */,
versions_.get(), &mutex_, &shutting_down_, snapshots, kMaxSequenceNumber,
snapshot_checker, &job_context, FlushReason::kTest, nullptr, nullptr,
nullptr, kNoCompression, db_options_.statistics.get(), &event_logger,
true, true /* sync_output_directory */, true /* write_manifest */,
Env::Priority::USER, nullptr /*IOTracer*/, empty_seqno_to_time_mapping_,
/*db_id=*/"",
/*db_session_id=*/"", full_history_ts_low);
+11 -49
View File
@@ -135,37 +135,6 @@ struct JobContext {
return kMaxSequenceNumber;
}
SequenceNumber GetLatestSnapshotSequence() const {
assert(snapshot_context_initialized);
if (snapshot_seqs.empty()) {
return 0;
}
return snapshot_seqs.back();
}
SequenceNumber GetEarliestSnapshotSequence() const {
assert(snapshot_context_initialized);
if (snapshot_seqs.empty()) {
return kMaxSequenceNumber;
}
return snapshot_seqs.front();
}
void InitSnapshotContext(SnapshotChecker* checker,
std::unique_ptr<ManagedSnapshot> managed_snapshot,
SequenceNumber earliest_write_conflict,
std::vector<SequenceNumber>&& snapshots) {
if (snapshot_context_initialized) {
return;
}
snapshot_context_initialized = true;
snapshot_checker = checker;
assert(!job_snapshot);
job_snapshot = std::move(managed_snapshot);
earliest_write_conflict_snapshot = earliest_write_conflict;
snapshot_seqs = std::move(snapshots);
}
// Structure to store information for candidate files to delete.
struct CandidateFileInfo {
std::string file_name;
@@ -177,6 +146,9 @@ struct JobContext {
}
};
// Unique job id
int job_id;
// a list of all files that we'll consider deleting
// (every once in a while this is filled up with all files
// in the DB directory)
@@ -225,14 +197,14 @@ struct JobContext {
// the current manifest_file_number, log_number and prev_log_number
// that corresponds to the set of files in 'live'.
uint64_t manifest_file_number = 0;
uint64_t pending_manifest_file_number = 0;
uint64_t manifest_file_number;
uint64_t pending_manifest_file_number;
// Used for remote compaction. To prevent OPTIONS files from getting
// purged by PurgeObsoleteFiles() of the primary host
uint64_t min_options_file_number;
uint64_t log_number = 0;
uint64_t prev_log_number = 0;
uint64_t log_number;
uint64_t prev_log_number;
uint64_t min_pending_output = 0;
uint64_t prev_wals_total_size = 0;
@@ -241,27 +213,17 @@ struct JobContext {
// Snapshot taken before flush/compaction job.
std::unique_ptr<ManagedSnapshot> job_snapshot;
SnapshotChecker* snapshot_checker = nullptr;
std::vector<SequenceNumber> snapshot_seqs;
// This is the earliest snapshot that could be used for write-conflict
// checking by a transaction. For any user-key newer than this snapshot, we
// should make sure not to remove evidence that a write occurred.
SequenceNumber earliest_write_conflict_snapshot = kMaxSequenceNumber;
// Unique job id
int job_id;
bool snapshot_context_initialized = false;
explicit JobContext(int _job_id, bool create_superversion = false) {
job_id = _job_id;
manifest_file_number = 0;
pending_manifest_file_number = 0;
log_number = 0;
prev_log_number = 0;
superversion_contexts.emplace_back(
SuperVersionContext(create_superversion));
}
// Delete the default constructor
JobContext() = delete;
// For non-empty JobContext Clean() has to be called at least once before
// before destruction (see asserts in ~JobContext()). Should be called with
// unlocked DB mutex. Destructor doesn't call Clean() to avoid accidentally
-41
View File
@@ -537,47 +537,6 @@ TEST_F(EventListenerTest, DisableBGCompaction) {
ASSERT_GE(listener->slowdown_count, kSlowdownTrigger * 9);
}
class TestNumInputFilesTotalInputBytesPouplatedInListener
: public EventListener {
public:
void OnCompactionCompleted(DB* /*db*/, const CompactionJobInfo& ci) override {
std::lock_guard<std::mutex> lock(mutex_);
num_input_files = ci.stats.num_input_files;
total_num_of_bytes = ci.stats.total_input_bytes;
}
size_t num_input_files = 0;
size_t total_num_of_bytes = 0;
std::mutex mutex_;
};
TEST_F(EventListenerTest, NumInputFilesTotalBytesPopulated) {
Options options;
options.level_compaction_dynamic_level_bytes = false;
options.env = CurrentOptions().env;
options.create_if_missing = true;
options.memtable_factory.reset(test::NewSpecialSkipListFactory(
DBTestBase::kNumKeysByGenerateNewRandomFile));
TestNumInputFilesTotalInputBytesPouplatedInListener* listener =
new TestNumInputFilesTotalInputBytesPouplatedInListener();
options.listeners.emplace_back(listener);
options.level0_file_num_compaction_trigger = 4;
options.compaction_style = kCompactionStyleLevel;
DestroyAndReopen(options);
Random rnd(301);
ASSERT_EQ(listener->num_input_files, 0);
ASSERT_EQ(listener->total_num_of_bytes, 0);
// Write 4 files in L0
for (int i = 0; i < 4; i++) {
GenerateNewRandomFile(&rnd);
}
ASSERT_OK(dbfull()->TEST_WaitForCompact());
ASSERT_EQ(listener->num_input_files, 4);
ASSERT_NE(listener->total_num_of_bytes, 0);
}
class TestCompactionReasonListener : public EventListener {
public:
void OnCompactionCompleted(DB* /*db*/, const CompactionJobInfo& ci) override {
-9
View File
@@ -1135,15 +1135,6 @@ void DumpManifestHandler::CheckIterationResult(const log::Reader& reader,
// Print out DebugStrings. Can include non-terminating null characters.
fwrite(cfd->current()->DebugString(hex_).data(), sizeof(char),
cfd->current()->DebugString(hex_).size(), stdout);
fprintf(stdout,
"By default, manifest file dump prints LSM trees as if %d levels "
"were configured, "
"which is not necessarily true for the column family (CF) this "
"manifest is associated with. "
"Please consult other DB files, such as the OPTIONS file, to "
"confirm.\n",
cfd->ioptions().num_levels);
}
fprintf(stdout,
"next_file_number %" PRIu64 " last_sequence %" PRIu64
-3
View File
@@ -398,7 +398,6 @@ DECLARE_bool(use_adaptive_mutex_lru);
DECLARE_uint32(compress_format_version);
DECLARE_uint64(manifest_preallocation_size);
DECLARE_bool(enable_checksum_handoff);
DECLARE_string(compression_manager);
DECLARE_uint64(max_total_wal_size);
DECLARE_double(high_pri_pool_ratio);
DECLARE_double(low_pri_pool_ratio);
@@ -425,9 +424,7 @@ DECLARE_bool(track_and_verify_wals);
DECLARE_bool(enable_remote_compaction);
DECLARE_bool(auto_refresh_iterator_with_snapshot);
DECLARE_uint32(memtable_op_scan_flush_trigger);
DECLARE_uint32(memtable_avg_op_scan_flush_trigger);
DECLARE_uint32(ingest_wbwi_one_in);
DECLARE_bool(universal_reduce_file_locking);
constexpr long KB = 1024;
constexpr int kRandomValueMaxFactor = 3;
+1 -14
View File
@@ -467,9 +467,7 @@ DEFINE_uint64(blob_file_size,
DEFINE_string(blob_compression_type, "none",
"[Integrated BlobDB] The compression algorithm to use for large "
"values stored in blob files.");
DEFINE_string(compression_manager, "mixed",
"Ability to change compression manager specified in "
"simple_mixed_manager.h (mixed -> roundRobin)");
DEFINE_bool(enable_blob_garbage_collection,
ROCKSDB_NAMESPACE::AdvancedColumnFamilyOptions()
.enable_blob_garbage_collection,
@@ -1484,15 +1482,4 @@ DEFINE_uint32(
ROCKSDB_NAMESPACE::ColumnFamilyOptions().memtable_op_scan_flush_trigger,
"Sets CF option memtable_op_scan_flush_trigger.");
DEFINE_uint32(
memtable_avg_op_scan_flush_trigger,
ROCKSDB_NAMESPACE::ColumnFamilyOptions().memtable_avg_op_scan_flush_trigger,
"Sets CF option memtable_avg_op_scan_flush_trigger.");
DEFINE_bool(
universal_reduce_file_locking,
ROCKSDB_NAMESPACE::ColumnFamilyOptions()
.compaction_options_universal.reduce_file_locking,
"Sets "
"ColumnFamilyOptions().compaciton_options_universal.reduce_file_locking.");
#endif // GFLAGS
-35
View File
@@ -34,7 +34,6 @@
#include "rocksdb/utilities/write_batch_with_index.h"
#include "test_util/testutil.h"
#include "util/cast_util.h"
#include "util/simple_mixed_compressor.h"
#include "utilities/backup/backup_engine_impl.h"
#include "utilities/fault_injection_fs.h"
#include "utilities/fault_injection_secondary_cache.h"
@@ -3412,39 +3411,7 @@ void StressTest::Open(SharedState* shared, bool reopen) {
InitializeOptionsFromFlags(cache_, filter_policy_, options_);
}
InitializeOptionsGeneral(cache_, filter_policy_, sqfc_factory_, options_);
if (!strcasecmp(FLAGS_compression_manager.c_str(), "mixed") ||
!strcasecmp(FLAGS_compression_manager.c_str(), "randommixed")) {
// Currently limited to ZSTD compression. Table property compression_name
// needs to set to zstd for now even when there can be more than one
// algorithm in the table under your compressor.
if (!ZSTD_Supported()) {
fprintf(stderr,
"ZSTD compression not supported thus mixed compression cannot be "
"used\n");
exit(1);
}
if (!strcasecmp(FLAGS_compression_manager.c_str(), "mixed")) {
auto mgr = std::make_shared<RoundRobinManager>(
GetDefaultBuiltinCompressionManager());
options_.compression_manager = mgr;
} else if (!strcasecmp(FLAGS_compression_manager.c_str(), "randommixed")) {
auto mgr = std::make_shared<RandomMixedCompressionManager>(
GetDefaultBuiltinCompressionManager());
options_.compression_manager = mgr;
}
options_.compression = kZSTD;
options_.bottommost_compression = kZSTD;
} else if (!strcasecmp(FLAGS_compression_manager.c_str(), "autoskip")) {
options_.compression_manager =
CreateAutoSkipCompressionManager(GetDefaultBuiltinCompressionManager());
} else if (!strcasecmp(FLAGS_compression_manager.c_str(), "none")) {
// Nothing to do using default compression manager
} else {
fprintf(stderr, "Unknown compression manager: %s\n",
FLAGS_compression_manager.c_str());
exit(1);
}
if (FLAGS_prefix_size == 0 && FLAGS_rep_factory == kHashSkipList) {
fprintf(stderr,
"prefeix_size cannot be zero if memtablerep == prefix_hash\n");
@@ -4370,8 +4337,6 @@ void InitializeOptionsFromFlags(
}
options.memtable_op_scan_flush_trigger = FLAGS_memtable_op_scan_flush_trigger;
options.compaction_options_universal.reduce_file_locking =
FLAGS_universal_reduce_file_locking;
}
void InitializeOptionsGeneral(
+3 -3
View File
@@ -687,9 +687,9 @@ IOStatus WritableFileWriter::WriteBufferedWithChecksum(const IOOptions& opts,
if (rate_limiter_ != nullptr && rate_limiter_priority_used != Env::IO_TOTAL) {
while (data_size > 0) {
size_t tmp_size;
tmp_size =
rate_limiter_->RequestToken(data_size, 0, rate_limiter_priority_used,
stats_, RateLimiter::OpType::kWrite);
tmp_size = rate_limiter_->RequestToken(data_size, buf_.Alignment(),
rate_limiter_priority_used, stats_,
RateLimiter::OpType::kWrite);
data_size -= tmp_size;
}
}
-515
View File
@@ -1,515 +0,0 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
//
// APIs for customizing compression in RocksDB.
//
// ***********************************************************************
// EXPERIMENTAL - subject to change while under development
// ***********************************************************************
#pragma once
#include "rocksdb/cache.h"
#include "rocksdb/compression_type.h"
#include "rocksdb/data_structure.h"
namespace ROCKSDB_NAMESPACE {
// TODO: alias/adapt for compression
struct FilterBuildingContext;
// A Compressor represents a very specific but potentially adapting strategy for
// compressing blocks, including the relevant algorithm(s), options, dictionary,
// etc. as applicable--every input except the sequence of bytes to compress.
// Compressor is generally thread-safe so can be shared by multiple threads. (It
// could make sense to convert unique_ptr<Compressor> to
// shared_ptr<Compressor>.) A Compressor for data files is expected to be used
// for just one file, so that compression strategy can be explicitly
// reconsidered for each new file. However, a Compressor for in-memory use could
// live indefinitely.
//
// If a single thread is doing many compressions under the same strategy, it
// should request a WorkingArea that will in some cases make repeated
// compression in a single thread more efficient. Unlike the rest of Compressor,
// each WorkingArea can only be used by one thread at a time. WorkingAreas can
// have pre-allocated space and/or data structures, and/or thread-local
// statistics that are later incorporated into shared statistics objects.
//
// The Compressor marks each block with a CompressionType to guide
// decompression. However, the compression dictionary (or whether there is one
// associated) is determined at Compressor creation time, though the process of
// getting a Compressor with a dictionary starts with a Compressor without
// dictionary (which will often be relevant alongside); see relevant functions.
// If the Compressor wants to decide block-by-block whether to apply the
// configured dictionary, that would need to be encoded in CompressionType or
// the compressed output. (NOTE: this was historically NOT encoded in
// CompressionType and instead implied by BlockType and the presence of a
// dictionary block in the file. Some of the resulting awkwardness includes
// a number of built-in CompressionTypes that ignore any dictionary block in
// the file; therefore they cannot accommodate dictionary compression in the
// future without a schema change / extension.)
class Compressor {
public:
Compressor() = default;
virtual ~Compressor() = default;
// Returns the max total bytes of for all sampled blocks for creating the data
// dictionary, or zero indicating dictionary compression should not be
// used/configured. This will typically be called after
// CompressionManager::GetCompressor() to see if samples should be accumulated
// and passed to MaybeCloneSpecialized().
virtual size_t GetMaxSampleSizeIfWantDict(CacheEntryRole block_type) const {
// Default implementation: no dictionary
(void)block_type;
return 0;
}
// Returns the serialized form of the data dictionary associated with this
// Compressor. NOTE: empty dict is equivalent to no dict.
virtual Slice GetSerializedDict() const { return Slice(); }
// If there's a dominant compression type returned by this compressor as
// configured, return it. Otherwise, return kDisableCompressionOption.
virtual CompressionType GetPreferredCompressionType() const {
return CompressionType::kDisableCompressionOption;
}
// Utility struct for providing sample data for the compression dictionary.
// Potentially extensible by callers of Compressor (but not recommended)
struct DictSampleArgs {
// All the sample input blocks stored contiguously
std::string sample_data;
// The lengths of each of the sample blocks in `sample_data`
std::vector<size_t> sample_lens;
bool empty() { return sample_data.empty(); }
bool Verify() {
size_t total_len = 0;
for (auto len : sample_lens) {
total_len += len;
}
return total_len == sample_data.size();
}
};
// Create potential variants of the same Compressor that might be
// (a) optimized for a particular block type (does not affect correct
// decompression), and/or
// (b) configured to use a compression dictionary, based on the given
// samples (decompression must provide the dictionary from
// GetSerializedDict())
// Return of nullptr indicates no specialization exists or was attempted
// and the caller is best to use the current Compressor for the desired
// scenario. Using CacheEntryRole:kMisc for block_type generally means
// "unspecified", and both parameters are merely suggestions. The exact
// dictionary associated with a returned compressor must be read from
// GetSerializedDict().
virtual std::unique_ptr<Compressor> MaybeCloneSpecialized(
CacheEntryRole block_type, DictSampleArgs&& dict_samples) {
// Default implementation: no specialization
(void)block_type;
(void)dict_samples;
// Caller should have checked GetMaxSampleSizeIfWantDict before attempting
// to provide dictionary samples
assert(dict_samples.empty());
return nullptr;
}
// A WorkingArea is an optional structure (both for callers and
// implementations) that can enable optimizing repeated compressions by
// reusing working space or thread-local tracking of statistics or trends.
// This enables use of ZSTD context, for example.
//
// EXTENSIBLE or reinterpret_cast-able by custom Compressor implementations
struct WorkingArea {};
protected:
// To allow for flexible re-use / reclaimation, we have explicit Get and
// Release functions, and usually wrap in a special RAII smart pointer.
// For example, a WorkingArea could be saved/recycled in thread-local or
// core-local storage, or heap managed, etc., though an explicit WorkingArea
// is only advised for repeated compression (by a single thread).
virtual void ReleaseWorkingArea(WorkingArea*) {}
public:
using ManagedWorkingArea =
ManagedPtr<WorkingArea, Compressor, &Compressor::ReleaseWorkingArea>;
// See struct WorkingArea above
virtual ManagedWorkingArea ObtainWorkingArea() {
// Default implementation: no working area
return {};
}
// Compress `uncompressed_data` to `compressed_output`, which should be
// passed in empty. Note that the compressed output will be decompressed
// by the sequence Decompressor::ExtractUncompressedSize() followed by
// Decompressor::DecompressBlock(), which must also be provided the same
// CompressionType saved in `out_compression_type`. (In many configurations,
// `compressed_output` will have a prefix storing the uncompressed_data size
// before the compressed bytes returned by the underlying compression
// algorithm. And the compression type is usually stored adjacent to the
// compressed data, or in some cases assumed/asserted based on the particular
// Compressor.)
//
// If return status is not OK, then some fatal condition has arisen. On OK
// status, setting `*out_compression_type = kNoCompression` means compression
// is declined and the caller should use the original uncompressed_data and
// ignore any result in `compressed_output`. Otherwise, compression has
// happened with results in `compressed_output` and `out_compression_type`,
// which are allowed to vary from call to call.
//
// The working area is optional and used to optimize repeated compression by
// a single thread. ManagedWorkingArea is provided rather than just
// WorkingArea so that it can be used only if the `owner` matches expectation.
// This could be useful for a Compressor wrapping more than one alternative
// underlying Compressor.
//
// TODO: instead of string, consider a buffer only large enough for max
// tolerable compressed size. Does that work for all existing algorithms?
// * Looks like Snappy doesn't support that. :(
// * Except perhaps using the Sink interface
// * But looks like everything else should. :)
// Could save CPU by eliminating extra zero-ing and giving up quicker when
// ratio is insufficient.
virtual Status CompressBlock(Slice uncompressed_data,
std::string* compressed_output,
CompressionType* out_compression_type,
ManagedWorkingArea* working_area) = 0;
// TODO: something to populate table properties based on settings, after all
// or as WorkingAreas released. Maybe also update stats, or that could be in
// thread-specific WorkingArea.
};
// A Decompressor usually has a wide capability to decompress all kinds of
// compressed data in the scope of a CompressionManager (see that class below),
// except
// (a) it might be optimized for or limited to a particular compression type(s)
// (see GetDecompressor* functions for in CompressionManager),
// (b) distinct Decompressors are required to decompress with compression
// dictionaries. (Decompressors are generally associated with empty/no
// dictionary unless created with MaybeCloneForDict().)
//
// Similar to Compressor, Decompressor is generally thread safe except that each
// WorkingArea can only be used by a single thread at a time.
//
// Decompressors known to be associated with no dictionary are typically
// returned as shared_ptr, because they are broadly usable across threads.
// Because compression dictionaries are externally managed (see
// MaybeCloneForDict()), Decompressors associated with compression dictionaries
// are typically returned as unique_ptr, so that they are more easily
// guaranteed not to outlive their dictionaries (e.g. in block cache).
// Decompressors associated with compression dictionaries might include a
// processed or "digested" form of the raw dictionary for efficient repeated
// compressions.
//
// NOTE: Splitting the interface between ExtractUncompressedSize and
// DecompressBlock leaves to the caller details of (and flexibility in)
// allocating buffers for decompressing into. For example, the data could be
// decompressed into part of a single buffer allocated to hold a block's
// uncompressed contents along with an in-memory object representation of the
// block (to reduce fragmentation and other overheads of separate objects).
class Decompressor {
public:
Decompressor() = default;
virtual ~Decompressor() = default;
// A name for logging / debugging purposes
virtual const char* Name() const = 0;
// A WorkingArea is an optional structure (both for callers and
// implementations) that can enable optimizing repeated decompressions by
// reusing working space or thread-local tracking of statistics. This enables
// use of ZSTD context, for example.
//
// EXTENSIBLE or reinterpret_cast-able by custom Compressor implementations
struct WorkingArea {};
protected:
// To allow for flexible re-use / reclaimation, we have explicit Obtain and
// Release functions, which are typically wrapped in a special RAII smart
// pointer. For example, a WorkingArea could be saved/recycled in thread-local
// or core-local storage, or heap managed, etc., though an explicit
// WorkingArea is only advised for repeated decompression (by a single
// thread).
virtual void ReleaseWorkingArea(WorkingArea* wa) {
// Default implementation: no working area
(void)wa;
assert(wa == nullptr);
}
public:
using ManagedWorkingArea =
ManagedPtr<WorkingArea, Decompressor, &Decompressor::ReleaseWorkingArea>;
virtual ManagedWorkingArea ObtainWorkingArea(CompressionType /*preferred*/) {
// Default implementation: no working area
return {};
}
// If this Decompressor is associated with a (de)compression dictionary
// (created with MaybeCloneForDict()), this returns a pointer to those raw (or
// "serialized") bytes, which are externally managed (see
// MaybeCloneForDict()).
// Default: empty slice => no dictionary
virtual const Slice& GetSerializedDict() const;
// Create a variant of this Decompressor in `out` using the specified raw
// ("serialized") dictionary. This step is required for decompressing data
// compressed with the same dictionary. The new Decompressor references the
// given Slice through its lifetime so the data it points to must be managed
// by the caller along with (or beyond) the new Decompressor. If the
// dictionary is processed into a form reusable by repeated compressions in
// many threads, that happens within this call.
//
// Must return OK if storing a result in `out`. Otherwise, could return values
// like NotSupported - dictionary compression is not (yet) supported for this
// kind of Decompressor.
// Corruption - dictionary is malformed (though many implementations will
// accept any data as a dictionary)
virtual Status MaybeCloneForDict(const Slice& /*serialized_dict*/,
std::unique_ptr<Decompressor>* /*out*/) {
return Status::NotSupported(
"Dictionary compression not (yet) supported by " + std::string(Name()));
}
// Memory size of this object and others it owns. Does not include the
// serialized dictionary (when used) which is externally managed.
virtual size_t ApproximateOwnedMemoryUsage() const {
// Default: negligible
return 0;
}
// Potentially extensible by callers of Decompressor (but not recommended)
struct Args {
CompressionType compression_type = kNoCompression;
Slice compressed_data;
uint64_t uncompressed_size = 0;
ManagedWorkingArea* working_area = nullptr;
};
// For efficiency on the read path, RocksDB strongly prefers the uncompressed
// data size to be encoded in the compressed data in an easily accessible way,
// so that allocation of a potentially long-lived buffer can be ideally sized.
// This function determines the uncompressed size and potentially modifies
// `args.compressed_data` to strip off the size metadata, for providing both
// to DecompressBlock along with an appropriate buffer based on that size.
// Some implementations will leave `compressed_data` unmodified and let
// DecompressBlock call a library function that processes a format that
// includes size metadata (e.g. Snappy).
//
// Even for legacy cases without size metadata (e.g. some very old RocksDB
// formats), an exact size is required and could require decompressing the
// data (here and in DecompressBlock()).
//
// Return non-OK in case of corrupt data or some other unworkable limitation
// or failure.
//
// The default implementation uses a standard format for prepending
// uncompressed size to the compressed payload. (RocksDB
// compress_format_version=2 except Snappy)
virtual Status ExtractUncompressedSize(Args& args);
// Called to decompress a block of data after running ExtractUncompressedSize
// on it. `args.compressed_data` is what ExtractUncompressedSize left there
// after potentially stripping off the uncompressed size metadata. Returns OK
// iff uncompressed data of size `uncompressed_size` is written to
// `uncompressed_output`.
virtual Status DecompressBlock(const Args& args,
char* uncompressed_output) = 0;
};
// A CompressionManager represents
// * When/where/how to use different compressions
// * A schema (or set of schemas) and implementation for mapping
// <CompressionType, dictionary, compressed data>
// to uncompressed data (or error), which can expand over time (error in fewer
// cases) for a given CompatibilityName() but can never change that mapping
// (because that would break backward compatibility, potential quiet
// corruption)
// TODO: consider adding optional streaming compression support (low priority)
class CompressionManager
: public std::enable_shared_from_this<CompressionManager>,
public Customizable {
public:
CompressionManager() = default;
virtual ~CompressionManager() = default;
static const char* Type() { return "CompressionManager"; }
// *************** Creating various Compression Managers *************** //
// A name for the schema family of this CompressionManager. In short, if
// two CompressionManagers have functionally the same Decompressor(s), they
// should have the same CompatibilityName(), so that a compatible
// CompressionManager/Decompressor might be used if the original is
// unavailable. (Name() can be useful in addition to CompatibilityName() for
// understanding what compression strategy was used.)
virtual const char* CompatibilityName() const = 0;
// Default implementation checks the current compatibility name and returns
// this CompressionManager (via `out`) if appropriate, and otherwise defers
// to CreateFromString().
virtual Status FindCompatibleCompressionManager(
Slice compatibility_name, std::shared_ptr<CompressionManager>* out);
// Create a CompressionManager from a string, including built-in
// CompressionManager types.
// TODO: ObjectLibrary stuff
static Status CreateFromString(const ConfigOptions& config_options,
const std::string& id,
std::shared_ptr<CompressionManager>* result);
// ************************* Compressor creation *********************** //
// Returning nullptr means compression is entirely disabled for the file,
// which is valid at the discretion of the CompressionManager. Returning
// nullptr should normally be the result if preferred == kNoCompression.
//
// These functions must be thread-safe.
// Get a compressor for an SST file.
// SUBJECT TO CHANGE
// TODO: is it practical to get ColumnFamilyOptions plumbed into here?
virtual std::unique_ptr<Compressor> GetCompressorForSST(
const FilterBuildingContext&, const CompressionOptions& opts,
CompressionType preferred) {
return GetCompressor(opts, preferred);
}
// Get a compressor for a generic/unspecified purpose (e.g. in-memory
// compression).
virtual std::unique_ptr<Compressor> GetCompressor(
const CompressionOptions& opts, CompressionType type) = 0;
// **************************** Decompressors ************************** //
// Get a decompressor that is compatible with any blocks compressed by
// compressors returned by this CompressionManager (at least this code
// revision and earlier). (NOTE: recommended to return a shared_ptr alias of
// this shared_ptr to a field that is a Decompressor.)
// Justification for not making CompressionManager inherit Decompressor: this
// tends to run into the diamond inheritance problem in implementations and
// potential overheads of virtual inheritance.
virtual std::shared_ptr<Decompressor> GetDecompressor() = 0;
// Compatible with same as above, but potentially optimized for a certain
// expected CompressionType
virtual std::shared_ptr<Decompressor> GetDecompressorOptimizeFor(
CompressionType /*optimize_for_type*/) {
// Safe default implementation
return GetDecompressor();
}
// Get a decompressor that is allowed to have support only for the
// CompressionTypes in the given start-to-end array (unique, sorted by
// unsigned char)
virtual std::shared_ptr<Decompressor> GetDecompressorForTypes(
const CompressionType* /*types_begin*/,
const CompressionType* /*types_end*/) {
// Safe default implementation
return GetDecompressor();
}
};
// ************************* Utility wrappers etc. *********************** //
class CompressorWrapper : public Compressor {
public:
explicit CompressorWrapper(std::unique_ptr<Compressor> compressor)
: wrapped_(std::move(compressor)) {}
// No copies
CompressorWrapper(const CompressorWrapper&) = delete;
CompressorWrapper& operator=(const CompressorWrapper&) = delete;
size_t GetMaxSampleSizeIfWantDict(CacheEntryRole block_type) const override {
return wrapped_->GetMaxSampleSizeIfWantDict(block_type);
}
Slice GetSerializedDict() const override {
return wrapped_->GetSerializedDict();
}
CompressionType GetPreferredCompressionType() const override {
return wrapped_->GetPreferredCompressionType();
}
std::unique_ptr<Compressor> MaybeCloneSpecialized(
CacheEntryRole block_type, DictSampleArgs&& dict_samples) override {
return wrapped_->MaybeCloneSpecialized(block_type, std::move(dict_samples));
}
ManagedWorkingArea ObtainWorkingArea() override {
return wrapped_->ObtainWorkingArea();
}
Status CompressBlock(Slice uncompressed_data, std::string* compressed_output,
CompressionType* out_compression_type,
ManagedWorkingArea* working_area) override {
return wrapped_->CompressBlock(uncompressed_data, compressed_output,
out_compression_type, working_area);
}
protected:
std::unique_ptr<Compressor> wrapped_;
};
// TODO: CompressorBase, for custom compressions
class CompressionManagerWrapper : public CompressionManager {
public:
explicit CompressionManagerWrapper(
std::shared_ptr<CompressionManager> wrapped)
: wrapped_(std::move(wrapped)) {}
const char* CompatibilityName() const override {
return wrapped_->CompatibilityName();
}
Status FindCompatibleCompressionManager(
Slice compatibility_name,
std::shared_ptr<CompressionManager>* out) override {
return wrapped_->FindCompatibleCompressionManager(compatibility_name, out);
}
std::unique_ptr<Compressor> GetCompressorForSST(
const FilterBuildingContext& context, const CompressionOptions& opts,
CompressionType preferred) override {
return wrapped_->GetCompressorForSST(context, opts, preferred);
}
std::unique_ptr<Compressor> GetCompressor(const CompressionOptions& opts,
CompressionType type) override {
return wrapped_->GetCompressor(opts, type);
}
std::shared_ptr<Decompressor> GetDecompressor() override {
return wrapped_->GetDecompressor();
}
std::shared_ptr<Decompressor> GetDecompressorOptimizeFor(
CompressionType optimize_for_type) override {
return wrapped_->GetDecompressorOptimizeFor(optimize_for_type);
}
std::shared_ptr<Decompressor> GetDecompressorForTypes(
const CompressionType* types_begin,
const CompressionType* types_end) override {
return wrapped_->GetDecompressorForTypes(types_begin, types_end);
}
protected:
std::shared_ptr<CompressionManager> wrapped_;
};
// Compression manager that implements built-in compression strategy. The
// behavior of
// compression_manager=nullptr with this
const std::shared_ptr<CompressionManager>&
GetDefaultBuiltinCompressionManager();
// Gets CompressionManager designed for the automated compression strategy.
// This may include deciding to compress or not.
// In future should be able to select compression algorithm based on the CPU
// utilization and IO constraints.
std::shared_ptr<CompressionManagerWrapper> CreateAutoSkipCompressionManager(
std::shared_ptr<CompressionManager> wrapped);
} // namespace ROCKSDB_NAMESPACE
+2 -21
View File
@@ -863,7 +863,7 @@ struct AdvancedColumnFamilyOptions {
//
// Default: 0 (disable the feature)
//
// Dynamically changeable through the SetOptions() API
// Not dynamically changeable, change it requires db restart.
uint64_t preclude_last_level_data_seconds = 0;
// EXPERIMENTAL
@@ -886,7 +886,7 @@ struct AdvancedColumnFamilyOptions {
//
// Default: 0 (disable the feature)
//
// Dynamically changeable through the SetOptions() API
// Not dynamically changeable, change it requires db restart.
uint64_t preserve_internal_time_seconds = 0;
// When set, large values (blobs) are written to separate blob files, and
@@ -1127,25 +1127,6 @@ struct AdvancedColumnFamilyOptions {
// Dynamically changeable through the SetOptions() API.
uint32_t memtable_op_scan_flush_trigger = 0;
// Similar to `memtable_op_scan_flush_trigger`, but this option applies to
// Next() calls between Seeks or until iterator destruction. If the average
// of the number of invisible entries scanned from the active memtable, the
// memtable will be marked for flush.
// Note that to avoid the case where the window between Seeks is too small,
// the option only takes effect if the total number of hidden entries scanned
// within a window is at least `memtable_op_scan_flush_trigger`. So this
// option is only effective when `memtable_op_scan_flush_trigger` is set.
//
// This option should be set to a lower value than
// `memtable_op_scan_flush_trigger`. It covers the case where an iterator
// scans through an expensive key range with many invisible entries from the
// active memtable, but the number of invisible entries per operation does not
// exceed `memtable_op_scan_flush_trigger`.
//
// Default: 0 (disabled)
// Dynamically changeable through the SetOptions() API.
uint32_t memtable_avg_op_scan_flush_trigger = 0;
// Create ColumnFamilyOptions with default values for all fields
AdvancedColumnFamilyOptions();
// Create ColumnFamilyOptions from Options
-6
View File
@@ -1507,12 +1507,6 @@ rocksdb_options_set_memtable_op_scan_flush_trigger(rocksdb_options_t*,
extern ROCKSDB_LIBRARY_API uint32_t
rocksdb_options_get_memtable_op_scan_flush_trigger(rocksdb_options_t*);
extern ROCKSDB_LIBRARY_API void
rocksdb_options_set_memtable_avg_op_scan_flush_trigger(rocksdb_options_t*,
uint32_t);
extern ROCKSDB_LIBRARY_API uint32_t
rocksdb_options_get_memtable_avg_op_scan_flush_trigger(rocksdb_options_t*);
enum {
rocksdb_statistics_level_disable_all = 0,
rocksdb_statistics_level_except_tickers =
-3
View File
@@ -182,7 +182,4 @@ struct CompressionOptions {
#endif
};
// See advanced_compression.h
class CompressionManager;
} // namespace ROCKSDB_NAMESPACE
+34 -132
View File
@@ -7,9 +7,9 @@
#include <assert.h>
#include <array>
#include <cstddef>
#include <cstdint>
#include <vector>
#include "rocksdb/rocksdb_namespace.h"
@@ -17,33 +17,24 @@ namespace ROCKSDB_NAMESPACE {
namespace detail {
int CountTrailingZeroBitsForSmallEnumSet(uint64_t);
int BitsSetToOneForSmallEnumSet(uint64_t);
} // namespace detail
// Represents a set of values of some enum type with a small number of possible
// enumerators. Assumes that any combination of enumerators with values 0
// through MAX_ENUMERATOR (inclusive) might be part of the set. NOTE: would like
// to use std::bitset, but it doesn't support constexpr (in C++17) operations
// and doesn't support efficient iteration over sparse "set to true" entries.
// Represents a set of values of some enum type with a small number of
// possible enumerators. For now, it supports enums where no enumerator
// exceeds 63 when converted to int.
template <typename ENUM_TYPE, ENUM_TYPE MAX_ENUMERATOR>
class SmallEnumSet {
private:
using StateT = uint64_t;
static constexpr int kStateBits = sizeof(StateT) * 8;
static constexpr int kMaxMax = kStateBits - 1;
static constexpr int kMaxValue = static_cast<int>(MAX_ENUMERATOR);
static_assert(kMaxValue >= 0);
static_assert(kMaxValue < 1024, "MAX_ENUMERATOR is suspiciously large");
using PieceT = uint64_t;
static constexpr int kPieceBits = 64;
static constexpr int kPieceMask = 63;
static constexpr int kPieceShift = 6;
static constexpr int kPieceCount = kMaxValue / kPieceBits + 1;
using StateT = std::array<PieceT, kPieceCount>;
static constexpr int kStateBits = kPieceBits * kPieceCount;
static_assert(kStateBits == sizeof(StateT) * 8);
static_assert(kMaxValue <= kStateBits - 1);
static_assert(kMaxValue <= kMaxMax);
public:
// construct / create empty set
SmallEnumSet() : state_{} {}
// construct / create
SmallEnumSet() : state_(0) {}
template <class... TRest>
/*implicit*/ constexpr SmallEnumSet(const ENUM_TYPE e, TRest... rest) {
@@ -53,16 +44,8 @@ class SmallEnumSet {
// Return the set that includes all valid values, assuming the enum
// is "dense" (includes all values converting to 0 through kMaxValue)
static constexpr SmallEnumSet All() {
StateT tmp;
for (int i = 0; i < kPieceCount - 1; ++i) {
tmp[i] = ~PieceT{0};
}
if constexpr (((kMaxValue + 1) & kPieceMask) != 0) {
tmp[kPieceCount - 1] = (PieceT{1} << ((kMaxValue + 1) & kPieceMask)) - 1;
} else {
tmp[kPieceCount - 1] = ~PieceT{0};
}
return SmallEnumSet(RawStateMarker(), tmp);
StateT tmp = StateT{1} << kMaxValue;
return SmallEnumSet(RawStateMarker(), tmp | (tmp - 1));
}
// equality
@@ -77,17 +60,11 @@ class SmallEnumSet {
bool Contains(const ENUM_TYPE e) const {
int value = static_cast<int>(e);
assert(value >= 0 && value <= kMaxValue);
return GetPiece(value) & (PieceT{1} << (value & kPieceMask));
StateT tmp = 1;
return state_ & (tmp << value);
}
bool empty() const {
for (int i = 0; i < kPieceCount; ++i) {
if (state_[i] != 0) {
return false;
}
}
return true;
}
bool empty() const { return state_ == 0; }
// iterator
class const_iterator {
@@ -115,7 +92,7 @@ class SmallEnumSet {
if (pos_ < kMaxValue) {
pos_ = set_->SkipUnset(pos_ + 1);
} else {
pos_ = kMaxValue + 1;
pos_ = kStateBits;
}
return *this;
}
@@ -141,15 +118,7 @@ class SmallEnumSet {
const_iterator begin() const { return const_iterator(this, SkipUnset(0)); }
const_iterator end() const { return const_iterator(this, kMaxValue + 1); }
size_t count() const {
size_t rv = 0;
for (int i = 0; i < kPieceCount; ++i) {
rv += static_cast<size_t>(detail::BitsSetToOneForSmallEnumSet(state_[i]));
}
return rv;
}
const_iterator end() const { return const_iterator(this, kStateBits); }
// mutable ops
@@ -158,10 +127,9 @@ class SmallEnumSet {
bool Add(const ENUM_TYPE e) {
int value = static_cast<int>(e);
assert(value >= 0 && value <= kMaxValue);
PieceT& piece_ref = RefPiece(value);
PieceT old_piece = piece_ref;
piece_ref |= (PieceT{1} << (value & kPieceMask));
return old_piece != piece_ref;
StateT old_state = state_;
state_ |= (StateT{1} << value);
return old_state != state_;
}
// Modifies the set (if needed) not to include the given value. Returns true
@@ -169,20 +137,18 @@ class SmallEnumSet {
bool Remove(const ENUM_TYPE e) {
int value = static_cast<int>(e);
assert(value >= 0 && value <= kMaxValue);
PieceT& piece_ref = RefPiece(value);
PieceT old_piece = piece_ref;
piece_ref &= ~(PieceT{1} << (value & kPieceMask));
return old_piece != piece_ref;
StateT old_state = state_;
state_ &= ~(StateT{1} << value);
return old_state != state_;
}
// applicative ops
// Return a new set based on this one with the additional value(s) inserted
constexpr SmallEnumSet With(const ENUM_TYPE e) const {
assert(static_cast<int>(e) >= 0 && static_cast<int>(e) <= kMaxValue);
SmallEnumSet rv(*this);
rv.Add(e);
return rv;
int value = static_cast<int>(e);
assert(value >= 0 && value <= kMaxValue);
return SmallEnumSet(RawStateMarker(), state_ | (StateT{1} << value));
}
template <class... TRest>
constexpr SmallEnumSet With(const ENUM_TYPE e1, const ENUM_TYPE e2,
@@ -192,10 +158,9 @@ class SmallEnumSet {
// Return a new set based on this one excluding the given value(s)
constexpr SmallEnumSet Without(const ENUM_TYPE e) const {
assert(static_cast<int>(e) >= 0 && static_cast<int>(e) <= kMaxValue);
SmallEnumSet rv(*this);
rv.Remove(e);
return rv;
int value = static_cast<int>(e);
assert(value >= 0 && value <= kMaxValue);
return SmallEnumSet(RawStateMarker(), state_ & ~(StateT{1} << value));
}
template <class... TRest>
constexpr SmallEnumSet Without(const ENUM_TYPE e1, const ENUM_TYPE e2,
@@ -205,80 +170,17 @@ class SmallEnumSet {
private:
int SkipUnset(int pos) const {
while (pos <= kMaxValue) {
PieceT remainder = GetPiece(pos) >> (pos & kPieceMask);
if (remainder != 0) {
return pos + detail::CountTrailingZeroBitsForSmallEnumSet(remainder);
}
pos = (pos + kPieceBits) & ~kPieceMask;
StateT tmp = state_ >> pos;
if (tmp == 0) {
return kStateBits;
} else {
return pos + detail::CountTrailingZeroBitsForSmallEnumSet(tmp);
}
return kMaxValue + 1;
}
struct RawStateMarker {};
explicit SmallEnumSet(RawStateMarker, StateT state) : state_(state) {}
PieceT GetPiece(int pos) const {
if constexpr (kPieceCount == 1) {
return state_[0];
} else {
return state_[pos >> kPieceShift];
}
}
PieceT& RefPiece(int pos) {
if constexpr (kPieceCount == 1) {
return state_[0];
} else {
return state_[pos >> kPieceShift];
}
}
StateT state_;
};
// A smart pointer that tracks an object and an owner, using a statically
// determined function on those to reclaim the object, if both object and owner
// are non-null
template <typename T, class Owner, auto Fn>
class ManagedPtr {
public:
ManagedPtr() = default;
ManagedPtr(T* ptr, Owner* owner) : ptr_(ptr), owner_(owner) {}
~ManagedPtr() {
if (ptr_ && owner_) {
if constexpr (std::is_member_function_pointer_v<decltype(Fn)>) {
(owner_->*Fn)(ptr_);
} else {
Fn(owner_, ptr_);
}
}
}
// No copies
ManagedPtr(const ManagedPtr&) = delete;
ManagedPtr& operator=(const ManagedPtr&) = delete;
// Moves
ManagedPtr(ManagedPtr&& other) noexcept {
ptr_ = other.ptr_;
owner_ = other.owner_;
other.ptr_ = nullptr;
other.owner_ = nullptr;
}
ManagedPtr& operator=(ManagedPtr&& other) noexcept {
ptr_ = other.ptr_;
owner_ = other.owner_;
other.ptr_ = nullptr;
other.owner_ = nullptr;
return *this;
}
T* get() const { return ptr_; }
T* operator->() const { return ptr_; }
T& operator*() const { return *ptr_; }
operator bool() const { return ptr_ != nullptr; }
Owner* owner() const { return owner_; }
private:
T* ptr_ = nullptr;
Owner* owner_ = nullptr;
};
} // namespace ROCKSDB_NAMESPACE
+1 -1
View File
@@ -269,7 +269,7 @@ class ExternalTableFactory : public Customizable {
// Allocate a TableFactory that wraps around an ExternalTableFactory. Use this
// to allocate and set in ColumnFamilyOptions::table_factory.
std::shared_ptr<TableFactory> NewExternalTableFactory(
std::unique_ptr<TableFactory> NewExternalTableFactory(
std::shared_ptr<ExternalTableFactory> inner_factory);
} // namespace ROCKSDB_NAMESPACE
+2 -37
View File
@@ -18,7 +18,6 @@
#include <stdint.h>
#include <any>
#include <chrono>
#include <cstdarg>
#include <functional>
@@ -251,44 +250,16 @@ struct IODebugContext {
};
uint64_t trace_data = 0;
// Arbitrary structure containing cost information about the IO request
std::any cost_info;
IODebugContext() {}
// Copy constructor
IODebugContext(const IODebugContext& other)
: file_path(other.file_path),
counters(other.counters),
msg(other.msg),
trace_data(other.trace_data),
cost_info(other.cost_info),
_request_id(other.request_id ? *other.request_id : "") {
request_id = other.request_id ? &_request_id : nullptr;
}
// Copy assignment operator
IODebugContext& operator=(const IODebugContext& other) {
if (this != &other) {
file_path = other.file_path;
counters = other.counters;
msg = other.msg;
trace_data = other.trace_data;
cost_info = other.cost_info;
_request_id = other.request_id ? *other.request_id : "";
request_id = other.request_id ? &_request_id : nullptr;
}
return *this;
}
void AddCounter(std::string& name, uint64_t value) {
counters.emplace(name, value);
}
// Called by underlying file system to set request_id and log request_id in
// IOTracing.
void SetRequestId(const std::string* updated_request_id) {
request_id = updated_request_id;
void SetRequestId(const std::string* _request_id) {
request_id = _request_id;
trace_data |= (1 << TraceData::kRequestID);
}
@@ -301,12 +272,6 @@ struct IODebugContext {
ss << msg;
return ss.str();
}
private:
// Private member that allows for safe copying of IODebugContext without any
// memory ownership issues. After copying, request_id can point directly to
// this field.
std::string _request_id;
};
// A function pointer type for custom destruction of void pointer passed to
+2 -20
View File
@@ -233,14 +233,6 @@ struct ColumnFamilyOptions : public AdvancedColumnFamilyOptions {
// different options for compression algorithms
CompressionOptions compression_opts;
// EXPERIMENTAL
// Customized compression through a callback interface. When non-nullptr,
// supersedes the above compression options, except that the above options are
// still processed as they historically would be and passed to
// CompressionManager::GetCompressorForSST as hints or suggestions. See
// advanced_compression.h
std::shared_ptr<CompressionManager> compression_manager;
// Number of files to trigger level-0 compaction. A value <0 means that
// level-0 compaction will not be triggered by number of files at all.
//
@@ -2222,20 +2214,10 @@ struct CompactionOptions {
// If > 0, it will replace the option in the DBOptions for this compaction.
uint32_t max_subcompactions;
// Allows cancellation of an in-progress manual compaction.
//
// Cancellation can be delayed waiting on automatic compactions when used
// together with `exclusive_manual_compaction == true`.
std::atomic<bool>* canceled;
// NOTE: Calling DisableManualCompaction() will not override the
// canceled variable in CompactionOptions, as it does for CompactRangeOptions
// - this is because ManualCompactionState is not used
CompactionOptions()
: compression(kDisableCompressionOption),
output_file_size_limit(std::numeric_limits<uint64_t>::max()),
max_subcompactions(0),
canceled(nullptr) {}
max_subcompactions(0) {}
};
// For level based compaction, we can configure if we want to skip/force
@@ -2302,7 +2284,7 @@ struct CompactRangeOptions {
// Cancellation can be delayed waiting on automatic compactions when used
// together with `exclusive_manual_compaction == true`.
std::atomic<bool>* canceled = nullptr;
// NOTE: Calling DisableManualCompaction() overwrites the user-provided
// NOTE: Calling DisableManualCompaction() overwrites the uer-provided
// canceled variable in CompactRangeOptions.
// Typically, when CompactRange is being called in one thread (t1) with
// canceled = false, and DisableManualCompaction is being called in the
-1
View File
@@ -5,7 +5,6 @@
#pragma once
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
+1 -22
View File
@@ -111,26 +111,6 @@ class CompactionOptionsUniversal {
// Default: false
bool incremental;
// EXPERIMENTAL
//
// If true, auto universal compaction picking will adjust to minimize locking
// of input files when bottom priority compactions are waiting to run. This
// can increase the likelihood of existing L0s being selected for compaction,
// thereby improving write stall and reducing read regression. It may increase
// the overrall write amplification and compaction load on low priority
// threads.
//
// Default: false (disabled)
//
// This options does not apply to manual compactions.
//
// This option is temporary in case turning on this feature causes problems
// and users need to undo it quickly. This option is planned for removal in
// the near future with default value set to true.
//
// Dynamically changeable through the SetOptions() API.
bool reduce_file_locking;
// Default set of parameters
CompactionOptionsUniversal()
: size_ratio(1),
@@ -141,8 +121,7 @@ class CompactionOptionsUniversal {
max_read_amp(-1),
stop_style(kCompactionStopStyleTotalSize),
allow_trivial_move(false),
incremental(false),
reduce_file_locking(false) {}
incremental(false) {}
#if __cplusplus >= 202002L
bool operator==(const CompactionOptionsUniversal& rhs) const = default;
+2 -2
View File
@@ -12,8 +12,8 @@
// NOTE: in 'main' development branch, this should be the *next*
// minor or major version number planned for release.
#define ROCKSDB_MAJOR 10
#define ROCKSDB_MINOR 4
#define ROCKSDB_PATCH 0
#define ROCKSDB_MINOR 3
#define ROCKSDB_PATCH 4
// Do not use these. We made the mistake of declaring macros starting with
// double underscore. Now we have to live with our choice. We'll deprecate these
+1 -17
View File
@@ -349,10 +349,6 @@ static std::unordered_map<std::string, OptionTypeInfo>
OptionTypeFlags::kMutable}},
{"allow_trivial_move",
{offsetof(class CompactionOptionsUniversal, allow_trivial_move),
OptionType::kBoolean, OptionVerificationType::kNormal,
OptionTypeFlags::kMutable}},
{"reduce_file_locking",
{offsetof(class CompactionOptionsUniversal, reduce_file_locking),
OptionType::kBoolean, OptionVerificationType::kNormal,
OptionTypeFlags::kMutable}}};
@@ -702,11 +698,6 @@ static std::unordered_map<std::string, OptionTypeInfo>
name, value, addr);
}
})},
{"compression_manager",
OptionTypeInfo::AsCustomSharedPtr<CompressionManager>(
offsetof(struct MutableCFOptions, compression_manager),
OptionVerificationType::kByNameAllowNull,
(OptionTypeFlags::kMutable | OptionTypeFlags::kAllowNull))},
// End special case properties
{"memtable_max_range_deletions",
{offsetof(struct MutableCFOptions, memtable_max_range_deletions),
@@ -716,10 +707,6 @@ static std::unordered_map<std::string, OptionTypeInfo>
{offsetof(struct MutableCFOptions, memtable_op_scan_flush_trigger),
OptionType::kUInt32T, OptionVerificationType::kNormal,
OptionTypeFlags::kMutable}},
{"memtable_avg_op_scan_flush_trigger",
{offsetof(struct MutableCFOptions, memtable_avg_op_scan_flush_trigger),
OptionType::kUInt32T, OptionVerificationType::kNormal,
OptionTypeFlags::kMutable}},
};
static std::unordered_map<std::string, OptionTypeInfo>
@@ -1203,8 +1190,7 @@ void MutableCFOptions::Dump(Logger* log) const {
uncache_aggressiveness);
ROCKS_LOG_INFO(log, " memtable_op_scan_flush_trigger: %" PRIu32,
memtable_op_scan_flush_trigger);
ROCKS_LOG_INFO(log, " memtable_avg_op_scan_flush_trigger: %" PRIu32,
memtable_avg_op_scan_flush_trigger);
// Universal Compaction Options
ROCKS_LOG_INFO(log, "compaction_options_universal.size_ratio : %d",
compaction_options_universal.size_ratio);
@@ -1227,8 +1213,6 @@ void MutableCFOptions::Dump(Logger* log) const {
static_cast<int>(compaction_options_universal.allow_trivial_move));
ROCKS_LOG_INFO(log, "compaction_options_universal.incremental : %d",
static_cast<int>(compaction_options_universal.incremental));
ROCKS_LOG_INFO(log, "compaction_options_universal.reduce_file_locking : %d",
compaction_options_universal.reduce_file_locking);
// FIFO Compaction Options
ROCKS_LOG_INFO(log, "compaction_options_fifo.max_table_files_size : %" PRIu64,
+2 -8
View File
@@ -161,7 +161,6 @@ struct MutableCFOptions {
bottommost_compression(options.bottommost_compression),
compression_opts(options.compression_opts),
bottommost_compression_opts(options.bottommost_compression_opts),
compression_manager(options.compression_manager),
last_level_temperature(options.last_level_temperature),
default_write_temperature(options.default_write_temperature),
memtable_protection_bytes_per_key(
@@ -175,9 +174,7 @@ struct MutableCFOptions {
bottommost_file_compaction_delay(
options.bottommost_file_compaction_delay),
uncache_aggressiveness(options.uncache_aggressiveness),
memtable_op_scan_flush_trigger(options.memtable_op_scan_flush_trigger),
memtable_avg_op_scan_flush_trigger(
options.memtable_avg_op_scan_flush_trigger) {
memtable_op_scan_flush_trigger(options.memtable_op_scan_flush_trigger) {
RefreshDerivedOptions(options.num_levels, options.compaction_style);
}
@@ -233,8 +230,7 @@ struct MutableCFOptions {
memtable_max_range_deletions(0),
bottommost_file_compaction_delay(0),
uncache_aggressiveness(0),
memtable_op_scan_flush_trigger(0),
memtable_avg_op_scan_flush_trigger(0) {}
memtable_op_scan_flush_trigger(0) {}
explicit MutableCFOptions(const Options& options);
@@ -331,7 +327,6 @@ struct MutableCFOptions {
CompressionType bottommost_compression;
CompressionOptions compression_opts;
CompressionOptions bottommost_compression_opts;
std::shared_ptr<CompressionManager> compression_manager;
Temperature last_level_temperature;
Temperature default_write_temperature;
uint32_t memtable_protection_bytes_per_key;
@@ -344,7 +339,6 @@ struct MutableCFOptions {
uint32_t bottommost_file_compaction_delay;
uint32_t uncache_aggressiveness;
uint32_t memtable_op_scan_flush_trigger;
uint32_t memtable_avg_op_scan_flush_trigger;
// Derived options
// Per-level target file size.
+4 -12
View File
@@ -112,9 +112,7 @@ AdvancedColumnFamilyOptions::AdvancedColumnFamilyOptions(const Options& options)
blob_cache(options.blob_cache),
prepopulate_blob_cache(options.prepopulate_blob_cache),
persist_user_defined_timestamps(options.persist_user_defined_timestamps),
memtable_op_scan_flush_trigger(options.memtable_op_scan_flush_trigger),
memtable_avg_op_scan_flush_trigger(
options.memtable_avg_op_scan_flush_trigger) {
memtable_op_scan_flush_trigger(options.memtable_op_scan_flush_trigger) {
assert(memtable_factory.get() != nullptr);
if (max_bytes_for_level_multiplier_additional.size() <
static_cast<unsigned int>(num_levels)) {
@@ -286,12 +284,9 @@ void ColumnFamilyOptions::Dump(Logger* log) const {
ROCKS_LOG_HEADER(log,
" Options.max_sequential_skip_in_iterations: %" PRIu64,
max_sequential_skip_in_iterations);
ROCKS_LOG_HEADER(log,
" Options.memtable_op_scan_flush_trigger: %" PRIu32,
memtable_op_scan_flush_trigger);
ROCKS_LOG_HEADER(log,
" Options.memtable_avg_op_scan_flush_trigger: %" PRIu32,
memtable_avg_op_scan_flush_trigger);
ROCKS_LOG_HEADER(
log, " Options.memtable_op_scan_flush_trigger: %" PRIu32,
memtable_op_scan_flush_trigger);
ROCKS_LOG_HEADER(log,
" Options.max_compaction_bytes: %" PRIu64,
max_compaction_bytes);
@@ -358,9 +353,6 @@ void ColumnFamilyOptions::Dump(Logger* log) const {
str_compaction_stop_style.c_str());
ROCKS_LOG_HEADER(log, "Options.compaction_options_universal.max_read_amp: %d",
compaction_options_universal.max_read_amp);
ROCKS_LOG_HEADER(
log, "Options.compaction_options_universal.reduce_file_locking: %d",
compaction_options_universal.reduce_file_locking);
ROCKS_LOG_HEADER(
log, "Options.compaction_options_fifo.max_table_files_size: %" PRIu64,
compaction_options_fifo.max_table_files_size);
+1 -3
View File
@@ -293,7 +293,6 @@ void UpdateColumnFamilyOptions(const MutableCFOptions& moptions,
cf_opts->compression_opts = moptions.compression_opts;
cf_opts->bottommost_compression = moptions.bottommost_compression;
cf_opts->bottommost_compression_opts = moptions.bottommost_compression_opts;
cf_opts->compression_manager = moptions.compression_manager;
cf_opts->sample_for_compression = moptions.sample_for_compression;
cf_opts->compression_per_level = moptions.compression_per_level;
cf_opts->last_level_temperature = moptions.last_level_temperature;
@@ -302,8 +301,6 @@ void UpdateColumnFamilyOptions(const MutableCFOptions& moptions,
cf_opts->uncache_aggressiveness = moptions.uncache_aggressiveness;
cf_opts->memtable_op_scan_flush_trigger =
moptions.memtable_op_scan_flush_trigger;
cf_opts->memtable_avg_op_scan_flush_trigger =
moptions.memtable_avg_op_scan_flush_trigger;
}
void UpdateColumnFamilyOptions(const ImmutableCFOptions& ioptions,
@@ -568,6 +565,7 @@ bool SerializeSingleOptionHelper(const void* opt_address,
return SerializeEnum<CompressionType>(
compression_type_string_map,
*(static_cast<const CompressionType*>(opt_address)), value);
break;
case OptionType::kChecksumType:
return SerializeEnum<ChecksumType>(
checksum_type_string_map,
+1 -9
View File
@@ -530,8 +530,6 @@ TEST_F(OptionsSettableTest, ColumnFamilyOptionsAllFieldsSettable) {
sizeof(const CompactionFilter*)},
{offsetof(struct ColumnFamilyOptions, compaction_filter_factory),
sizeof(std::shared_ptr<CompactionFilterFactory>)},
{offsetof(struct ColumnFamilyOptions, compression_manager),
sizeof(std::shared_ptr<CompressionManager>)},
{offsetof(struct ColumnFamilyOptions, prefix_extractor),
sizeof(std::shared_ptr<const SliceTransform>)},
{offsetof(struct ColumnFamilyOptions, snap_refresh_nanos),
@@ -621,7 +619,6 @@ TEST_F(OptionsSettableTest, ColumnFamilyOptionsAllFieldsSettable) {
"strategy=7;max_dict_bytes=8;level=9;window_bits=10;max_compressed_bytes_"
"per_kb=876;checksum=true};"
"bottommost_compression=kDisableCompressionOption;"
"compression_manager=BuiltinV2;"
"level0_stop_writes_trigger=33;"
"num_levels=99;"
"level0_slowdown_writes_trigger=22;"
@@ -678,8 +675,7 @@ TEST_F(OptionsSettableTest, ColumnFamilyOptionsAllFieldsSettable) {
"bottommost_file_compaction_delay=7200;"
"uncache_aggressiveness=1234;"
"paranoid_memory_checks=1;"
"memtable_op_scan_flush_trigger=123;"
"memtable_avg_op_scan_flush_trigger=12;",
"memtable_op_scan_flush_trigger=123;",
new_options));
ASSERT_NE(new_options->blob_cache.get(), nullptr);
@@ -703,8 +699,6 @@ TEST_F(OptionsSettableTest, ColumnFamilyOptionsAllFieldsSettable) {
new_options->compaction_options_fifo.file_temperature_age_thresholds[0]
.age,
12345);
ASSERT_EQ(new_options->compression_manager,
GetBuiltinCompressionManager(/*compression_format_version*/ 2));
ColumnFamilyOptions rnd_filled_options = *new_options;
@@ -724,8 +718,6 @@ TEST_F(OptionsSettableTest, ColumnFamilyOptionsAllFieldsSettable) {
sizeof(std::vector<int>)},
{offsetof(struct MutableCFOptions, compaction_options_fifo),
sizeof(struct CompactionOptionsFIFO)},
{offsetof(struct MutableCFOptions, compression_manager),
sizeof(std::shared_ptr<CompressionManager>)},
{offsetof(struct MutableCFOptions, compression_per_level),
sizeof(std::vector<CompressionType>)},
{offsetof(struct MutableCFOptions, max_file_size),
-3
View File
@@ -243,7 +243,6 @@ LIB_SOURCES = \
util/compaction_job_stats_impl.cc \
util/comparator.cc \
util/compression.cc \
util/auto_skip_compressor.cc \
util/compression_context_cache.cc \
util/concurrent_task_limiter_impl.cc \
util/crc32c.cc \
@@ -257,7 +256,6 @@ LIB_SOURCES = \
util/ribbon_config.cc \
util/slice.cc \
util/file_checksum_helper.cc \
util/simple_mixed_compressor.cc \
util/status.cc \
util/stderr_logger.cc \
util/string_util.cc \
@@ -593,7 +591,6 @@ TEST_MAIN_SOURCES = \
table/table_test.cc \
table/block_fetcher_test.cc \
test_util/testutil_test.cc \
util/compression_test.cc \
tools/block_cache_analyzer/block_cache_trace_analyzer_test.cc \
tools/io_tracer_parser_test.cc \
tools/ldb_cmd_test.cc \
+478 -481
View File
@@ -190,6 +190,484 @@ struct BlockBasedTableBuilder::WorkingAreaPair {
Decompressor::ManagedWorkingArea verify;
};
struct BlockBasedTableBuilder::Rep {
const ImmutableOptions ioptions;
// BEGIN from MutableCFOptions
std::shared_ptr<const SliceTransform> prefix_extractor;
// END from MutableCFOptions
const WriteOptions write_options;
const BlockBasedTableOptions table_options;
const InternalKeyComparator& internal_comparator;
// Size in bytes for the user-defined timestamps.
size_t ts_sz;
// When `ts_sz` > 0 and this flag is false, the user-defined timestamp in the
// user key will be stripped when creating the block based table. This
// stripping happens for all user keys, including the keys in data block,
// index block for data block, index block for index block (if index type is
// `kTwoLevelIndexSearch`), index for filter blocks (if using partitioned
// filters), the `first_internal_key` in `IndexValue`, the `end_key` for range
// deletion entries.
// As long as the user keys are sorted when added via `Add` API, their logic
// ordering won't change after timestamps are stripped. However, for each user
// key to be logically equivalent before and after timestamp is stripped, the
// user key should contain the minimum timestamp.
bool persist_user_defined_timestamps;
WritableFileWriter* file;
std::atomic<uint64_t> offset;
size_t alignment;
BlockBuilder data_block;
// Buffers uncompressed data blocks to replay later. Needed when
// compression dictionary is enabled so we can finalize the dictionary before
// compressing any data blocks.
std::vector<std::string> data_block_buffers;
BlockBuilder range_del_block;
InternalKeySliceTransform internal_prefix_transform;
std::unique_ptr<IndexBuilder> index_builder;
std::string index_separator_scratch;
PartitionedIndexBuilder* p_index_builder_ = nullptr;
std::string last_ikey; // Internal key or empty (unset)
const Slice* first_key_in_next_block = nullptr;
bool warm_cache = false;
uint64_t sample_for_compression;
std::atomic<uint64_t> compressible_input_data_bytes;
std::atomic<uint64_t> uncompressible_input_data_bytes;
std::atomic<uint64_t> sampled_input_data_bytes;
std::atomic<uint64_t> sampled_output_slow_data_bytes;
std::atomic<uint64_t> sampled_output_fast_data_bytes;
uint32_t compression_parallel_threads;
int max_compressed_bytes_per_kb;
size_t max_dict_sample_bytes = 0;
// *** Compressors & decompressors - Yes, it seems like a lot here but ***
// *** these are distinct fields to minimize extra conditionals and ***
// *** field reads on hot code paths. ***
// A compressor for blocks in general, without dictionary compression
std::unique_ptr<Compressor> basic_compressor;
// A compressor using dictionary compression (when applicable)
std::unique_ptr<Compressor> compressor_with_dict;
// Once configured/determined, points to one of the above Compressors to
// use on data blocks.
Compressor* data_block_compressor = nullptr;
// A decompressor corresponding to basic_compressor (when non-nullptr).
// Used for verification and cache warming.
std::shared_ptr<Decompressor> basic_decompressor;
// When needed, a decompressor for verifying compression using a
// dictionary sampled/trained from this file.
std::unique_ptr<Decompressor> verify_decompressor_with_dict;
// When non-nullptr, compression should be verified with this corresponding
// decompressor, except for data blocks. (Points to same as basic_decompressor
// when verify_compression is set.)
UnownedPtr<Decompressor> verify_decompressor;
// Once configured/determined, points to one of the above Decompressors to use
// in verifying data blocks.
UnownedPtr<Decompressor> data_block_verify_decompressor;
// Working area for basic_compressor when compression_parallel_threads==1
WorkingAreaPair basic_working_area;
// Working areas for data_block_compressor, for each of
// compression_parallel_threads
std::vector<WorkingAreaPair> data_block_working_areas;
size_t data_begin_offset = 0;
TableProperties props;
// States of the builder.
//
// - `kBuffered`: This is the initial state where zero or more data blocks are
// accumulated uncompressed in-memory. From this state, call
// `EnterUnbuffered()` to finalize the compression dictionary if enabled,
// compress/write out any buffered blocks, and proceed to the `kUnbuffered`
// state.
//
// - `kUnbuffered`: This is the state when compression dictionary is finalized
// either because it wasn't enabled in the first place or it's been created
// from sampling previously buffered data. In this state, blocks are simply
// compressed/written out as they fill up. From this state, call `Finish()`
// to complete the file (write meta-blocks, etc.), or `Abandon()` to delete
// the partially created file.
//
// - `kClosed`: This indicates either `Finish()` or `Abandon()` has been
// called, so the table builder is no longer usable. We must be in this
// state by the time the destructor runs.
enum class State {
kBuffered,
kUnbuffered,
kClosed,
};
State state = State::kUnbuffered;
// `kBuffered` state is allowed only as long as the buffering of uncompressed
// data blocks (see `data_block_buffers`) does not exceed `buffer_limit`.
uint64_t buffer_limit = 0;
std::shared_ptr<CacheReservationManager>
compression_dict_buffer_cache_res_mgr;
const bool use_delta_encoding_for_index_values;
std::unique_ptr<FilterBlockBuilder> filter_builder;
OffsetableCacheKey base_cache_key;
const TableFileCreationReason reason;
BlockHandle pending_handle; // Handle to add to index block
std::string single_threaded_compressed_output;
std::unique_ptr<FlushBlockPolicy> flush_block_policy;
std::vector<std::unique_ptr<InternalTblPropColl>> table_properties_collectors;
std::unique_ptr<ParallelCompressionRep> pc_rep;
BlockCreateContext create_context;
// The size of the "tail" part of a SST file. "Tail" refers to
// all blocks after data blocks till the end of the SST file.
uint64_t tail_size;
// The total size of all blocks in this file before they are compressed.
// This is used for logging compaction stats.
uint64_t pre_compression_size = 0;
// See class Footer
uint32_t base_context_checksum;
uint64_t get_offset() { return offset.load(std::memory_order_relaxed); }
void set_offset(uint64_t o) { offset.store(o, std::memory_order_relaxed); }
bool IsParallelCompressionEnabled() const {
return compression_parallel_threads > 1;
}
Status GetStatus() {
// We need to make modifications of status visible when status_ok is set
// to false, and this is ensured by status_mutex, so no special memory
// order for status_ok is required.
if (status_ok.load(std::memory_order_relaxed)) {
return Status::OK();
} else {
return CopyStatus();
}
}
Status CopyStatus() {
std::lock_guard<std::mutex> lock(status_mutex);
return status;
}
IOStatus GetIOStatus() {
// We need to make modifications of io_status visible when status_ok is set
// to false, and this is ensured by io_status_mutex, so no special memory
// order for io_status_ok is required.
if (io_status_ok.load(std::memory_order_relaxed)) {
#ifdef ROCKSDB_ASSERT_STATUS_CHECKED // Avoid unnecessary lock acquisition
auto ios = CopyIOStatus();
ios.PermitUncheckedError();
// Assume no races in unit tests
assert(ios.ok());
#endif // ROCKSDB_ASSERT_STATUS_CHECKED
return IOStatus::OK();
} else {
return CopyIOStatus();
}
}
IOStatus CopyIOStatus() {
std::lock_guard<std::mutex> lock(io_status_mutex);
return io_status;
}
// Never erase an existing status that is not OK.
void SetStatus(Status s) {
if (!s.ok() && status_ok.load(std::memory_order_relaxed)) {
// Locking is an overkill for non compression_parallel_threads
// case but since it's unlikely that s is not OK, we take this cost
// to be simplicity.
std::lock_guard<std::mutex> lock(status_mutex);
status = s;
status_ok.store(false, std::memory_order_relaxed);
}
}
// Never erase an existing I/O status that is not OK.
// Calling this will also SetStatus(ios)
void SetIOStatus(IOStatus ios) {
if (!ios.ok() && io_status_ok.load(std::memory_order_relaxed)) {
// Locking is an overkill for non compression_parallel_threads
// case but since it's unlikely that s is not OK, we take this cost
// to be simplicity.
std::lock_guard<std::mutex> lock(io_status_mutex);
io_status = ios;
io_status_ok.store(false, std::memory_order_relaxed);
}
SetStatus(ios);
}
Rep(const BlockBasedTableOptions& table_opt, const TableBuilderOptions& tbo,
WritableFileWriter* f)
: ioptions(tbo.ioptions),
prefix_extractor(tbo.moptions.prefix_extractor),
write_options(tbo.write_options),
table_options(table_opt),
internal_comparator(tbo.internal_comparator),
ts_sz(tbo.internal_comparator.user_comparator()->timestamp_size()),
persist_user_defined_timestamps(
tbo.ioptions.persist_user_defined_timestamps),
file(f),
offset(0),
alignment(table_options.block_align
? std::min(static_cast<size_t>(table_options.block_size),
kDefaultPageSize)
: 0),
data_block(table_options.block_restart_interval,
table_options.use_delta_encoding,
false /* use_value_delta_encoding */,
tbo.internal_comparator.user_comparator()
->CanKeysWithDifferentByteContentsBeEqual()
? BlockBasedTableOptions::kDataBlockBinarySearch
: table_options.data_block_index_type,
table_options.data_block_hash_table_util_ratio, ts_sz,
persist_user_defined_timestamps),
range_del_block(
1 /* block_restart_interval */, true /* use_delta_encoding */,
false /* use_value_delta_encoding */,
BlockBasedTableOptions::kDataBlockBinarySearch /* index_type */,
0.75 /* data_block_hash_table_util_ratio */, ts_sz,
persist_user_defined_timestamps),
internal_prefix_transform(prefix_extractor.get()),
sample_for_compression(tbo.moptions.sample_for_compression),
compressible_input_data_bytes(0),
uncompressible_input_data_bytes(0),
sampled_input_data_bytes(0),
sampled_output_slow_data_bytes(0),
sampled_output_fast_data_bytes(0),
compression_parallel_threads(tbo.compression_opts.parallel_threads),
max_compressed_bytes_per_kb(
tbo.compression_opts.max_compressed_bytes_per_kb),
data_block_working_areas(compression_parallel_threads),
use_delta_encoding_for_index_values(table_opt.format_version >= 4 &&
!table_opt.block_align),
reason(tbo.reason),
flush_block_policy(
table_options.flush_block_policy_factory->NewFlushBlockPolicy(
table_options, data_block)),
create_context(&table_options, &ioptions, ioptions.stats,
/*decompressor=*/nullptr,
tbo.moptions.block_protection_bytes_per_key,
tbo.internal_comparator.user_comparator(),
!use_delta_encoding_for_index_values,
table_opt.index_type ==
BlockBasedTableOptions::kBinarySearchWithFirstKey),
tail_size(0),
status_ok(true),
io_status_ok(true) {
FilterBuildingContext filter_context(table_options);
filter_context.info_log = ioptions.logger;
filter_context.column_family_name = tbo.column_family_name;
filter_context.reason = reason;
// Only populate other fields if known to be in LSM rather than
// generating external SST file
if (reason != TableFileCreationReason::kMisc) {
filter_context.compaction_style = ioptions.compaction_style;
filter_context.num_levels = ioptions.num_levels;
filter_context.level_at_creation = tbo.level_at_creation;
filter_context.is_bottommost = tbo.is_bottommost;
assert(filter_context.level_at_creation < filter_context.num_levels);
}
// TODO: get CompressionManager from options and sort out properties
auto mgr = GetBuiltinCompressionManager(
GetCompressFormatForVersion(table_opt.format_version));
props.compression_name = CompressionTypeToString(tbo.compression_type);
props.compression_options =
CompressionOptionsToString(tbo.compression_opts);
// Sanitize to only allowing compression when it saves space.
max_compressed_bytes_per_kb =
std::min(int{1023}, tbo.compression_opts.max_compressed_bytes_per_kb);
basic_compressor = mgr->GetCompressorForSST(
filter_context, tbo.compression_opts, tbo.compression_type);
if (basic_compressor) {
if (table_options.enable_index_compression) {
basic_working_area.compress = basic_compressor->ObtainWorkingArea();
}
max_dict_sample_bytes = basic_compressor->GetMaxSampleSizeIfWantDict(
CacheEntryRole::kDataBlock);
if (max_dict_sample_bytes > 0) {
state = State::kBuffered;
if (tbo.target_file_size == 0) {
buffer_limit = tbo.compression_opts.max_dict_buffer_bytes;
} else if (tbo.compression_opts.max_dict_buffer_bytes == 0) {
buffer_limit = tbo.target_file_size;
} else {
buffer_limit = std::min(tbo.target_file_size,
tbo.compression_opts.max_dict_buffer_bytes);
}
} else {
// No distinct data block compressor using dictionary
data_block_compressor = basic_compressor.get();
for (uint32_t i = 0; i < compression_parallel_threads; i++) {
data_block_working_areas[i].compress =
data_block_compressor->ObtainWorkingArea();
}
}
basic_decompressor =
mgr->GetDecompressorOptimizeFor(tbo.compression_type);
create_context.decompressor = basic_decompressor.get();
if (table_options.verify_compression) {
verify_decompressor = basic_decompressor.get();
if (table_options.enable_index_compression) {
basic_working_area.verify =
verify_decompressor->ObtainWorkingArea(tbo.compression_type);
}
if (state == State::kUnbuffered) {
for (uint32_t i = 0; i < compression_parallel_threads; i++) {
data_block_working_areas[i].verify =
verify_decompressor->ObtainWorkingArea(tbo.compression_type);
}
data_block_verify_decompressor = verify_decompressor.get();
}
}
}
switch (table_options.prepopulate_block_cache) {
case BlockBasedTableOptions::PrepopulateBlockCache::kFlushOnly:
warm_cache = (reason == TableFileCreationReason::kFlush);
break;
case BlockBasedTableOptions::PrepopulateBlockCache::kDisable:
warm_cache = false;
break;
default:
// missing case
assert(false);
warm_cache = false;
}
const auto compress_dict_build_buffer_charged =
table_options.cache_usage_options.options_overrides
.at(CacheEntryRole::kCompressionDictionaryBuildingBuffer)
.charged;
if (table_options.block_cache &&
(compress_dict_build_buffer_charged ==
CacheEntryRoleOptions::Decision::kEnabled ||
compress_dict_build_buffer_charged ==
CacheEntryRoleOptions::Decision::kFallback)) {
compression_dict_buffer_cache_res_mgr =
std::make_shared<CacheReservationManagerImpl<
CacheEntryRole::kCompressionDictionaryBuildingBuffer>>(
table_options.block_cache);
} else {
compression_dict_buffer_cache_res_mgr = nullptr;
}
if (table_options.index_type ==
BlockBasedTableOptions::kTwoLevelIndexSearch) {
p_index_builder_ = PartitionedIndexBuilder::CreateIndexBuilder(
&internal_comparator, use_delta_encoding_for_index_values,
table_options, ts_sz, persist_user_defined_timestamps);
index_builder.reset(p_index_builder_);
} else {
index_builder.reset(IndexBuilder::CreateIndexBuilder(
table_options.index_type, &internal_comparator,
&this->internal_prefix_transform, use_delta_encoding_for_index_values,
table_options, ts_sz, persist_user_defined_timestamps));
}
if (ioptions.optimize_filters_for_hits && tbo.is_bottommost) {
// Apply optimize_filters_for_hits setting here when applicable by
// skipping filter generation
filter_builder.reset();
} else if (tbo.skip_filters) {
// For SstFileWriter skip_filters
filter_builder.reset();
} else if (!table_options.filter_policy) {
// Null filter_policy -> no filter
filter_builder.reset();
} else {
filter_builder.reset(CreateFilterBlockBuilder(
ioptions, tbo.moptions, filter_context,
use_delta_encoding_for_index_values, p_index_builder_, ts_sz,
persist_user_defined_timestamps));
}
assert(tbo.internal_tbl_prop_coll_factories);
for (auto& factory : *tbo.internal_tbl_prop_coll_factories) {
assert(factory);
std::unique_ptr<InternalTblPropColl> collector{
factory->CreateInternalTblPropColl(
tbo.column_family_id, tbo.level_at_creation,
tbo.ioptions.num_levels,
tbo.last_level_inclusive_max_seqno_threshold)};
if (collector) {
table_properties_collectors.emplace_back(std::move(collector));
}
}
table_properties_collectors.emplace_back(
new BlockBasedTablePropertiesCollector(
table_options.index_type, table_options.whole_key_filtering,
prefix_extractor != nullptr,
table_options.decouple_partitioned_filters));
if (ts_sz > 0 && persist_user_defined_timestamps) {
table_properties_collectors.emplace_back(
new TimestampTablePropertiesCollector(
tbo.internal_comparator.user_comparator()));
}
// These are only needed for populating table properties
props.column_family_id = tbo.column_family_id;
props.column_family_name = tbo.column_family_name;
props.oldest_key_time = tbo.oldest_key_time;
props.newest_key_time = tbo.newest_key_time;
props.file_creation_time = tbo.file_creation_time;
props.orig_file_number = tbo.cur_file_num;
props.db_id = tbo.db_id;
props.db_session_id = tbo.db_session_id;
props.db_host_id = ioptions.db_host_id;
props.format_version = table_options.format_version;
if (!ReifyDbHostIdProperty(ioptions.env, &props.db_host_id).ok()) {
ROCKS_LOG_INFO(ioptions.logger, "db_host_id property will not be set");
}
// Default is UINT64_MAX for unknown. Setting it to 0 here
// to allow updating it by taking max in BlockBasedTableBuilder::Add().
props.key_largest_seqno = 0;
if (FormatVersionUsesContextChecksum(table_options.format_version)) {
// Must be non-zero and semi- or quasi-random
// TODO: ideally guaranteed different for related files (e.g. use file
// number and db_session, for benefit of SstFileWriter)
do {
base_context_checksum = Random::GetTLSInstance()->Next();
} while (UNLIKELY(base_context_checksum == 0));
} else {
base_context_checksum = 0;
}
if (alignment > 0 && basic_compressor) {
// With better sanitization in `CompactionPicker::CompactFiles()`, we
// would not need to handle this case here and could change it to an
// assertion instead.
SetStatus(Status::InvalidArgument(
"Enable block_align, but compression enabled"));
}
}
Rep(const Rep&) = delete;
Rep& operator=(const Rep&) = delete;
private:
// Synchronize status & io_status accesses across threads from main thread,
// compression thread and write thread in parallel compression.
std::mutex status_mutex;
std::atomic<bool> status_ok;
Status status;
std::mutex io_status_mutex;
std::atomic<bool> io_status_ok;
IOStatus io_status;
};
struct BlockBasedTableBuilder::ParallelCompressionRep {
// TODO: consider replacing with autovector or similar
// Keys is a wrapper of vector of strings avoiding
@@ -484,487 +962,6 @@ struct BlockBasedTableBuilder::ParallelCompressionRep {
}
};
struct BlockBasedTableBuilder::Rep {
const ImmutableOptions ioptions;
// BEGIN from MutableCFOptions
std::shared_ptr<const SliceTransform> prefix_extractor;
// END from MutableCFOptions
const WriteOptions write_options;
const BlockBasedTableOptions table_options;
const InternalKeyComparator& internal_comparator;
// Size in bytes for the user-defined timestamps.
size_t ts_sz;
// When `ts_sz` > 0 and this flag is false, the user-defined timestamp in the
// user key will be stripped when creating the block based table. This
// stripping happens for all user keys, including the keys in data block,
// index block for data block, index block for index block (if index type is
// `kTwoLevelIndexSearch`), index for filter blocks (if using partitioned
// filters), the `first_internal_key` in `IndexValue`, the `end_key` for range
// deletion entries.
// As long as the user keys are sorted when added via `Add` API, their logic
// ordering won't change after timestamps are stripped. However, for each user
// key to be logically equivalent before and after timestamp is stripped, the
// user key should contain the minimum timestamp.
bool persist_user_defined_timestamps;
WritableFileWriter* file;
std::atomic<uint64_t> offset;
size_t alignment;
BlockBuilder data_block;
// Buffers uncompressed data blocks to replay later. Needed when
// compression dictionary is enabled so we can finalize the dictionary before
// compressing any data blocks.
std::vector<std::string> data_block_buffers;
BlockBuilder range_del_block;
InternalKeySliceTransform internal_prefix_transform;
std::unique_ptr<IndexBuilder> index_builder;
std::string index_separator_scratch;
PartitionedIndexBuilder* p_index_builder_ = nullptr;
std::string last_ikey; // Internal key or empty (unset)
const Slice* first_key_in_next_block = nullptr;
bool warm_cache = false;
uint64_t sample_for_compression;
std::atomic<uint64_t> compressible_input_data_bytes;
std::atomic<uint64_t> uncompressible_input_data_bytes;
std::atomic<uint64_t> sampled_input_data_bytes;
std::atomic<uint64_t> sampled_output_slow_data_bytes;
std::atomic<uint64_t> sampled_output_fast_data_bytes;
uint32_t compression_parallel_threads;
int max_compressed_bytes_per_kb;
size_t max_dict_sample_bytes = 0;
// *** Compressors & decompressors - Yes, it seems like a lot here but ***
// *** these are distinct fields to minimize extra conditionals and ***
// *** field reads on hot code paths. ***
// A compressor for blocks in general, without dictionary compression
std::unique_ptr<Compressor> basic_compressor;
// A compressor using dictionary compression (when applicable)
std::unique_ptr<Compressor> compressor_with_dict;
// Once configured/determined, points to one of the above Compressors to
// use on data blocks.
Compressor* data_block_compressor = nullptr;
// A decompressor corresponding to basic_compressor (when non-nullptr).
// Used for verification and cache warming.
std::shared_ptr<Decompressor> basic_decompressor;
// When needed, a decompressor for verifying compression using a
// dictionary sampled/trained from this file.
std::unique_ptr<Decompressor> verify_decompressor_with_dict;
// When non-nullptr, compression should be verified with this corresponding
// decompressor, except for data blocks. (Points to same as basic_decompressor
// when verify_compression is set.)
UnownedPtr<Decompressor> verify_decompressor;
// Once configured/determined, points to one of the above Decompressors to use
// in verifying data blocks.
UnownedPtr<Decompressor> data_block_verify_decompressor;
// Working area for basic_compressor when compression_parallel_threads==1
WorkingAreaPair basic_working_area;
// Working areas for data_block_compressor, for each of
// compression_parallel_threads
std::vector<WorkingAreaPair> data_block_working_areas;
size_t data_begin_offset = 0;
TableProperties props;
// States of the builder.
//
// - `kBuffered`: This is the initial state where zero or more data blocks are
// accumulated uncompressed in-memory. From this state, call
// `EnterUnbuffered()` to finalize the compression dictionary if enabled,
// compress/write out any buffered blocks, and proceed to the `kUnbuffered`
// state.
//
// - `kUnbuffered`: This is the state when compression dictionary is finalized
// either because it wasn't enabled in the first place or it's been created
// from sampling previously buffered data. In this state, blocks are simply
// compressed/written out as they fill up. From this state, call `Finish()`
// to complete the file (write meta-blocks, etc.), or `Abandon()` to delete
// the partially created file.
//
// - `kClosed`: This indicates either `Finish()` or `Abandon()` has been
// called, so the table builder is no longer usable. We must be in this
// state by the time the destructor runs.
enum class State {
kBuffered,
kUnbuffered,
kClosed,
};
State state = State::kUnbuffered;
// `kBuffered` state is allowed only as long as the buffering of uncompressed
// data blocks (see `data_block_buffers`) does not exceed `buffer_limit`.
uint64_t buffer_limit = 0;
std::shared_ptr<CacheReservationManager>
compression_dict_buffer_cache_res_mgr;
const bool use_delta_encoding_for_index_values;
std::unique_ptr<FilterBlockBuilder> filter_builder;
OffsetableCacheKey base_cache_key;
const TableFileCreationReason reason;
BlockHandle pending_handle; // Handle to add to index block
std::string single_threaded_compressed_output;
std::unique_ptr<FlushBlockPolicy> flush_block_policy;
std::vector<std::unique_ptr<InternalTblPropColl>> table_properties_collectors;
std::unique_ptr<ParallelCompressionRep> pc_rep;
BlockCreateContext create_context;
// The size of the "tail" part of a SST file. "Tail" refers to
// all blocks after data blocks till the end of the SST file.
uint64_t tail_size;
// The total size of all blocks in this file before they are compressed.
// This is used for logging compaction stats.
uint64_t pre_compression_size = 0;
// See class Footer
uint32_t base_context_checksum;
uint64_t get_offset() { return offset.load(std::memory_order_relaxed); }
void set_offset(uint64_t o) { offset.store(o, std::memory_order_relaxed); }
bool IsParallelCompressionEnabled() const {
return compression_parallel_threads > 1;
}
Status GetStatus() {
// We need to make modifications of status visible when status_ok is set
// to false, and this is ensured by status_mutex, so no special memory
// order for status_ok is required.
if (status_ok.load(std::memory_order_relaxed)) {
return Status::OK();
} else {
return CopyStatus();
}
}
Status CopyStatus() {
std::lock_guard<std::mutex> lock(status_mutex);
return status;
}
IOStatus GetIOStatus() {
// We need to make modifications of io_status visible when status_ok is set
// to false, and this is ensured by io_status_mutex, so no special memory
// order for io_status_ok is required.
if (io_status_ok.load(std::memory_order_relaxed)) {
#ifdef ROCKSDB_ASSERT_STATUS_CHECKED // Avoid unnecessary lock acquisition
auto ios = CopyIOStatus();
ios.PermitUncheckedError();
// Assume no races in unit tests
assert(ios.ok());
#endif // ROCKSDB_ASSERT_STATUS_CHECKED
return IOStatus::OK();
} else {
return CopyIOStatus();
}
}
IOStatus CopyIOStatus() {
std::lock_guard<std::mutex> lock(io_status_mutex);
return io_status;
}
// Never erase an existing status that is not OK.
void SetStatus(Status s) {
if (!s.ok() && status_ok.load(std::memory_order_relaxed)) {
// Locking is an overkill for non compression_parallel_threads
// case but since it's unlikely that s is not OK, we take this cost
// to be simplicity.
std::lock_guard<std::mutex> lock(status_mutex);
status = s;
status_ok.store(false, std::memory_order_relaxed);
}
}
// Never erase an existing I/O status that is not OK.
// Calling this will also SetStatus(ios)
void SetIOStatus(IOStatus ios) {
if (!ios.ok() && io_status_ok.load(std::memory_order_relaxed)) {
// Locking is an overkill for non compression_parallel_threads
// case but since it's unlikely that s is not OK, we take this cost
// to be simplicity.
std::lock_guard<std::mutex> lock(io_status_mutex);
io_status = ios;
io_status_ok.store(false, std::memory_order_relaxed);
}
SetStatus(ios);
}
Rep(const BlockBasedTableOptions& table_opt, const TableBuilderOptions& tbo,
WritableFileWriter* f)
: ioptions(tbo.ioptions),
prefix_extractor(tbo.moptions.prefix_extractor),
write_options(tbo.write_options),
table_options(table_opt),
internal_comparator(tbo.internal_comparator),
ts_sz(tbo.internal_comparator.user_comparator()->timestamp_size()),
persist_user_defined_timestamps(
tbo.ioptions.persist_user_defined_timestamps),
file(f),
offset(0),
alignment(table_options.block_align
? std::min(static_cast<size_t>(table_options.block_size),
kDefaultPageSize)
: 0),
data_block(table_options.block_restart_interval,
table_options.use_delta_encoding,
false /* use_value_delta_encoding */,
tbo.internal_comparator.user_comparator()
->CanKeysWithDifferentByteContentsBeEqual()
? BlockBasedTableOptions::kDataBlockBinarySearch
: table_options.data_block_index_type,
table_options.data_block_hash_table_util_ratio, ts_sz,
persist_user_defined_timestamps),
range_del_block(
1 /* block_restart_interval */, true /* use_delta_encoding */,
false /* use_value_delta_encoding */,
BlockBasedTableOptions::kDataBlockBinarySearch /* index_type */,
0.75 /* data_block_hash_table_util_ratio */, ts_sz,
persist_user_defined_timestamps),
internal_prefix_transform(prefix_extractor.get()),
sample_for_compression(tbo.moptions.sample_for_compression),
compressible_input_data_bytes(0),
uncompressible_input_data_bytes(0),
sampled_input_data_bytes(0),
sampled_output_slow_data_bytes(0),
sampled_output_fast_data_bytes(0),
compression_parallel_threads(tbo.compression_opts.parallel_threads),
max_compressed_bytes_per_kb(
tbo.compression_opts.max_compressed_bytes_per_kb),
data_block_working_areas(compression_parallel_threads),
use_delta_encoding_for_index_values(table_opt.format_version >= 4 &&
!table_opt.block_align),
reason(tbo.reason),
flush_block_policy(
table_options.flush_block_policy_factory->NewFlushBlockPolicy(
table_options, data_block)),
create_context(&table_options, &ioptions, ioptions.stats,
/*decompressor=*/nullptr,
tbo.moptions.block_protection_bytes_per_key,
tbo.internal_comparator.user_comparator(),
!use_delta_encoding_for_index_values,
table_opt.index_type ==
BlockBasedTableOptions::kBinarySearchWithFirstKey),
tail_size(0),
status_ok(true),
io_status_ok(true) {
FilterBuildingContext filter_context(table_options);
filter_context.info_log = ioptions.logger;
filter_context.column_family_name = tbo.column_family_name;
filter_context.reason = reason;
// Only populate other fields if known to be in LSM rather than
// generating external SST file
if (reason != TableFileCreationReason::kMisc) {
filter_context.compaction_style = ioptions.compaction_style;
filter_context.num_levels = ioptions.num_levels;
filter_context.level_at_creation = tbo.level_at_creation;
filter_context.is_bottommost = tbo.is_bottommost;
assert(filter_context.level_at_creation < filter_context.num_levels);
}
// TODO: get CompressionManager from options and sort out properties
auto mgr = tbo.moptions.compression_manager;
if (mgr == nullptr) {
mgr = GetBuiltinCompressionManager(
GetCompressFormatForVersion(table_opt.format_version));
}
props.compression_name = CompressionTypeToString(tbo.compression_type);
props.compression_options =
CompressionOptionsToString(tbo.compression_opts);
// Sanitize to only allowing compression when it saves space.
max_compressed_bytes_per_kb =
std::min(int{1023}, tbo.compression_opts.max_compressed_bytes_per_kb);
basic_compressor = mgr->GetCompressorForSST(
filter_context, tbo.compression_opts, tbo.compression_type);
if (basic_compressor) {
if (table_options.enable_index_compression) {
basic_working_area.compress = basic_compressor->ObtainWorkingArea();
}
max_dict_sample_bytes = basic_compressor->GetMaxSampleSizeIfWantDict(
CacheEntryRole::kDataBlock);
if (max_dict_sample_bytes > 0) {
state = State::kBuffered;
if (tbo.target_file_size == 0) {
buffer_limit = tbo.compression_opts.max_dict_buffer_bytes;
} else if (tbo.compression_opts.max_dict_buffer_bytes == 0) {
buffer_limit = tbo.target_file_size;
} else {
buffer_limit = std::min(tbo.target_file_size,
tbo.compression_opts.max_dict_buffer_bytes);
}
} else {
// No distinct data block compressor using dictionary
data_block_compressor = basic_compressor.get();
for (uint32_t i = 0; i < compression_parallel_threads; i++) {
data_block_working_areas[i].compress =
data_block_compressor->ObtainWorkingArea();
}
}
basic_decompressor =
mgr->GetDecompressorOptimizeFor(tbo.compression_type);
create_context.decompressor = basic_decompressor.get();
if (table_options.verify_compression) {
verify_decompressor = basic_decompressor.get();
if (table_options.enable_index_compression) {
basic_working_area.verify =
verify_decompressor->ObtainWorkingArea(tbo.compression_type);
}
if (state == State::kUnbuffered) {
for (uint32_t i = 0; i < compression_parallel_threads; i++) {
data_block_working_areas[i].verify =
verify_decompressor->ObtainWorkingArea(tbo.compression_type);
}
data_block_verify_decompressor = verify_decompressor.get();
}
}
}
switch (table_options.prepopulate_block_cache) {
case BlockBasedTableOptions::PrepopulateBlockCache::kFlushOnly:
warm_cache = (reason == TableFileCreationReason::kFlush);
break;
case BlockBasedTableOptions::PrepopulateBlockCache::kDisable:
warm_cache = false;
break;
default:
// missing case
assert(false);
warm_cache = false;
}
const auto compress_dict_build_buffer_charged =
table_options.cache_usage_options.options_overrides
.at(CacheEntryRole::kCompressionDictionaryBuildingBuffer)
.charged;
if (table_options.block_cache &&
(compress_dict_build_buffer_charged ==
CacheEntryRoleOptions::Decision::kEnabled ||
compress_dict_build_buffer_charged ==
CacheEntryRoleOptions::Decision::kFallback)) {
compression_dict_buffer_cache_res_mgr =
std::make_shared<CacheReservationManagerImpl<
CacheEntryRole::kCompressionDictionaryBuildingBuffer>>(
table_options.block_cache);
} else {
compression_dict_buffer_cache_res_mgr = nullptr;
}
if (table_options.index_type ==
BlockBasedTableOptions::kTwoLevelIndexSearch) {
p_index_builder_ = PartitionedIndexBuilder::CreateIndexBuilder(
&internal_comparator, use_delta_encoding_for_index_values,
table_options, ts_sz, persist_user_defined_timestamps);
index_builder.reset(p_index_builder_);
} else {
index_builder.reset(IndexBuilder::CreateIndexBuilder(
table_options.index_type, &internal_comparator,
&this->internal_prefix_transform, use_delta_encoding_for_index_values,
table_options, ts_sz, persist_user_defined_timestamps));
}
if (ioptions.optimize_filters_for_hits && tbo.is_bottommost) {
// Apply optimize_filters_for_hits setting here when applicable by
// skipping filter generation
filter_builder.reset();
} else if (tbo.skip_filters) {
// For SstFileWriter skip_filters
filter_builder.reset();
} else if (!table_options.filter_policy) {
// Null filter_policy -> no filter
filter_builder.reset();
} else {
filter_builder.reset(CreateFilterBlockBuilder(
ioptions, tbo.moptions, filter_context,
use_delta_encoding_for_index_values, p_index_builder_, ts_sz,
persist_user_defined_timestamps));
}
assert(tbo.internal_tbl_prop_coll_factories);
for (auto& factory : *tbo.internal_tbl_prop_coll_factories) {
assert(factory);
std::unique_ptr<InternalTblPropColl> collector{
factory->CreateInternalTblPropColl(
tbo.column_family_id, tbo.level_at_creation,
tbo.ioptions.num_levels,
tbo.last_level_inclusive_max_seqno_threshold)};
if (collector) {
table_properties_collectors.emplace_back(std::move(collector));
}
}
table_properties_collectors.emplace_back(
new BlockBasedTablePropertiesCollector(
table_options.index_type, table_options.whole_key_filtering,
prefix_extractor != nullptr,
table_options.decouple_partitioned_filters));
if (ts_sz > 0 && persist_user_defined_timestamps) {
table_properties_collectors.emplace_back(
new TimestampTablePropertiesCollector(
tbo.internal_comparator.user_comparator()));
}
// These are only needed for populating table properties
props.column_family_id = tbo.column_family_id;
props.column_family_name = tbo.column_family_name;
props.oldest_key_time = tbo.oldest_key_time;
props.newest_key_time = tbo.newest_key_time;
props.file_creation_time = tbo.file_creation_time;
props.orig_file_number = tbo.cur_file_num;
props.db_id = tbo.db_id;
props.db_session_id = tbo.db_session_id;
props.db_host_id = ioptions.db_host_id;
props.format_version = table_options.format_version;
if (!ReifyDbHostIdProperty(ioptions.env, &props.db_host_id).ok()) {
ROCKS_LOG_INFO(ioptions.logger, "db_host_id property will not be set");
}
// Default is UINT64_MAX for unknown. Setting it to 0 here
// to allow updating it by taking max in BlockBasedTableBuilder::Add().
props.key_largest_seqno = 0;
if (FormatVersionUsesContextChecksum(table_options.format_version)) {
// Must be non-zero and semi- or quasi-random
// TODO: ideally guaranteed different for related files (e.g. use file
// number and db_session, for benefit of SstFileWriter)
do {
base_context_checksum = Random::GetTLSInstance()->Next();
} while (UNLIKELY(base_context_checksum == 0));
} else {
base_context_checksum = 0;
}
if (alignment > 0 && basic_compressor) {
// With better sanitization in `CompactionPicker::CompactFiles()`, we
// would not need to handle this case here and could change it to an
// assertion instead.
SetStatus(Status::InvalidArgument(
"Enable block_align, but compression enabled"));
}
}
Rep(const Rep&) = delete;
Rep& operator=(const Rep&) = delete;
private:
// Synchronize status & io_status accesses across threads from main thread,
// compression thread and write thread in parallel compression.
std::mutex status_mutex;
std::atomic<bool> status_ok;
Status status;
std::mutex io_status_mutex;
std::atomic<bool> io_status_ok;
IOStatus io_status;
};
BlockBasedTableBuilder::BlockBasedTableBuilder(
const BlockBasedTableOptions& table_options, const TableBuilderOptions& tbo,
WritableFileWriter* file) {
@@ -34,7 +34,6 @@
#include "table/two_level_iterator.h"
#include "trace_replay/block_cache_tracer.h"
#include "util/atomic.h"
#include "util/cast_util.h"
#include "util/coro_utils.h"
#include "util/hash_containers.h"
-1
View File
@@ -14,7 +14,6 @@
#include "table/block_based/block_type.h"
#include "table/format.h"
#include "table/persistent_cache_options.h"
#include "util/cast_util.h"
namespace ROCKSDB_NAMESPACE {
+3 -3
View File
@@ -473,10 +473,10 @@ class ExternalTableFactoryAdapter : public TableFactory {
} // namespace
std::shared_ptr<TableFactory> NewExternalTableFactory(
std::unique_ptr<TableFactory> NewExternalTableFactory(
std::shared_ptr<ExternalTableFactory> inner_factory) {
std::shared_ptr<TableFactory> res;
res.reset(new ExternalTableFactoryAdapter(std::move(inner_factory)));
std::unique_ptr<TableFactory> res;
res = std::make_unique<ExternalTableFactoryAdapter>(std::move(inner_factory));
return res;
}
+6 -11
View File
@@ -4729,18 +4729,13 @@ static void DoCompressionTest(CompressionType comp) {
const ImmutableOptions ioptions(options);
const MutableCFOptions moptions(options);
c.Finish(options, ioptions, moptions, table_options, ikc, &keys, &kvmap);
size_t file_size = c.TEST_GetSink()->contents().size();
EXPECT_EQ(c.ApproximateOffsetOf("abc"), 0);
EXPECT_EQ(c.ApproximateOffsetOf("k01"), 0);
EXPECT_EQ(c.ApproximateOffsetOf("k02"), 0);
EXPECT_NEAR2(c.ApproximateOffsetOf("k03"), file_size / 2, file_size / 10);
EXPECT_NEAR2(c.ApproximateOffsetOf("k04"), file_size / 2, file_size / 10);
EXPECT_NEAR2(c.ApproximateOffsetOf("xyz"), file_size, file_size / 10);
size_t data_blocks_size = c.GetTableReader()->GetTableProperties()->data_size;
// Near expected compressed size ~= (0.25 + 0.25) * 10000
EXPECT_NEAR2(data_blocks_size, 5000, 1500);
ASSERT_TRUE(Between(c.ApproximateOffsetOf("abc"), 0, 0));
ASSERT_TRUE(Between(c.ApproximateOffsetOf("k01"), 0, 0));
ASSERT_TRUE(Between(c.ApproximateOffsetOf("k02"), 0, 0));
ASSERT_TRUE(Between(c.ApproximateOffsetOf("k03"), 2000, 3555));
ASSERT_TRUE(Between(c.ApproximateOffsetOf("k04"), 2000, 3555));
ASSERT_TRUE(Between(c.ApproximateOffsetOf("xyz"), 4000, 7110));
c.ResetTableReader();
}
+2 -2
View File
@@ -91,9 +91,9 @@ bool ShouldPersistUDT(const UserDefinedTimestampTestMode& test_mode) {
return test_mode != UserDefinedTimestampTestMode::kStripUserDefinedTimestamp;
}
Slice CompressibleString(Random* rnd, double compressed_to_fraction, int len,
Slice CompressibleString(Random* rnd, double compressed_fraction, int len,
std::string* dst) {
int raw = static_cast<int>(len * compressed_to_fraction);
int raw = static_cast<int>(len * compressed_fraction);
if (raw < 1) {
raw = 1;
}
+14 -24
View File
@@ -11,8 +11,6 @@
# Return value 0 means all regression tests pass. 1 if not pass.
#
# Environment options:
# SANITY_CHECK=1 - Do a syntax check and git checkout test as a sanity check
# that the script hasn't been broken by e.g. adding a new release wrongly.
# SHORT_TEST=1 - Test only the oldest branch for each kind of test. This is
# a good choice for PR validation as it is relatively fast and will find
# most issues.
@@ -137,7 +135,7 @@ EOF
# To check for DB forward compatibility with loading options (old version
# reading data from new), as well as backward compatibility
declare -a db_forward_with_options_refs=("8.6.fb" "8.7.fb" "8.8.fb" "8.9.fb" "8.10.fb" "8.11.fb" "9.0.fb" "9.1.fb" "9.2.fb" "9.3.fb" "9.4.fb" "9.5.fb" "9.6.fb" "9.7.fb" "9.8.fb" "9.9.fb" "9.10.fb" "9.11.fb" "10.0.fb" "10.1.fb" "10.2.fb" "10.3.fb")
declare -a db_forward_with_options_refs=("8.6.fb" "8.7.fb" "8.8.fb" "8.9.fb" "8.10.fb" "8.11.fb" "9.0.fb" "9.1.fb" "9.2.fb" "9.3.fb" "9.4.fb" "9.5.fb" "9.6.fb" "9.7.fb" "9.8.fb" "9.9.fb" "9.10.fb" "9.11.fb" "10.0.fb" "10.1.fb" "10.2.fb")
# To check for DB forward compatibility without loading options (in addition
# to the "with loading options" set), as well as backward compatibility
declare -a db_forward_no_options_refs=() # N/A at the moment
@@ -197,14 +195,10 @@ if [ "$SHORT_TEST" == "" ]; then
done
fi
invoke_make()
{
[ "$SANITY_CHECK" ] || make "$@"
}
generate_db()
{
set +e
[ "$SANITY_CHECK" ] || bash "$script_copy_dir"/generate_random_db.sh "$1" "$2"
bash "$script_copy_dir"/generate_random_db.sh "$1" "$2"
if [ $? -ne 0 ]; then
echo ==== Error loading data from $2 to $1 ====
exit 1
@@ -215,7 +209,7 @@ generate_db()
compare_db()
{
set +e
[ "$SANITY_CHECK" ] || bash "$script_copy_dir"/verify_random_db.sh "$1" "$2" "$3" "$4" "$5"
bash "$script_copy_dir"/verify_random_db.sh "$1" "$2" "$3" "$4" "$5"
if [ $? -ne 0 ]; then
echo ==== Read different content from $1 and $2 or error happened. ====
exit 1
@@ -226,7 +220,7 @@ compare_db()
write_external_sst()
{
set +e
[ "$SANITY_CHECK" ] || bash "$script_copy_dir"/write_external_sst.sh "$1" "$2" "$3"
bash "$script_copy_dir"/write_external_sst.sh "$1" "$2" "$3"
if [ $? -ne 0 ]; then
echo ==== Error writing external SST file using data from $1 to $3 ====
exit 1
@@ -237,7 +231,7 @@ write_external_sst()
ingest_external_sst()
{
set +e
[ "$SANITY_CHECK" ] || bash "$script_copy_dir"/ingest_external_sst.sh "$1" "$2"
bash "$script_copy_dir"/ingest_external_sst.sh "$1" "$2"
if [ $? -ne 0 ]; then
echo ==== Error ingesting external SST in $2 to DB at $1 ====
exit 1
@@ -248,7 +242,7 @@ ingest_external_sst()
backup_db()
{
set +e
[ "$SANITY_CHECK" ] || bash "$script_copy_dir"/backup_db.sh "$1" "$2"
bash "$script_copy_dir"/backup_db.sh "$1" "$2"
if [ $? -ne 0 ]; then
echo ==== Error backing up DB $1 to $2 ====
exit 1
@@ -259,7 +253,7 @@ backup_db()
restore_db()
{
set +e
[ "$SANITY_CHECK" ] || bash "$script_copy_dir"/restore_db.sh "$1" "$2"
bash "$script_copy_dir"/restore_db.sh "$1" "$2"
if [ $? -ne 0 ]; then
echo ==== Error restoring from $1 to $2 ====
exit 1
@@ -303,8 +297,8 @@ current_checkout_name="$current_checkout_name ($current_checkout_hash)"
echo "== Building $current_checkout_name debug"
git checkout -B $tmp_branch $current_checkout_hash
force_no_fbcode
invoke_make clean
DISABLE_WARNING_AS_ERROR=1 invoke_make ldb -j$J
make clean
DISABLE_WARNING_AS_ERROR=1 make ldb -j$J
echo "== Using $current_checkout_name, generate DB with extern SST and ingest"
current_ext_test_dir=$ext_test_dir"/current"
@@ -324,8 +318,8 @@ do
echo "== Building $checkout_ref debug"
git reset --hard $tmp_origin/$checkout_ref
force_no_fbcode
invoke_make clean
DISABLE_WARNING_AS_ERROR=1 invoke_make ldb -j$J
make clean
DISABLE_WARNING_AS_ERROR=1 make ldb -j$J
# We currently assume DB backward compatibility for every branch listed
echo "== Use $checkout_ref to generate a DB ..."
@@ -382,8 +376,8 @@ done
echo "== Building $current_checkout_name debug (again, final)"
git reset --hard $current_checkout_hash
force_no_fbcode
invoke_make clean
DISABLE_WARNING_AS_ERROR=1 invoke_make ldb -j$J
make clean
DISABLE_WARNING_AS_ERROR=1 make ldb -j$J
for checkout_ref in "${checkout_refs[@]}"
do
@@ -410,8 +404,4 @@ do
fi
done
if [ "$SANITY_CHECK" ]; then
echo "==== check_format_compatible.sh sanity check PASSED ===="
else
echo ==== Compatibility Test PASSED ====
fi
echo ==== Compatibility Test PASSED ====
+10 -67
View File
@@ -83,7 +83,6 @@
#include "util/gflags_compat.h"
#include "util/mutexlock.h"
#include "util/random.h"
#include "util/simple_mixed_compressor.h"
#include "util/stderr_logger.h"
#include "util/string_util.h"
#include "util/xxhash.h"
@@ -93,6 +92,7 @@
#include "utilities/merge_operators/bytesxor.h"
#include "utilities/merge_operators/sortlist.h"
#include "utilities/persistent_cache/block_cache_tier.h"
#ifdef MEMKIND
#include "memory/memkind_kmem_allocator.h"
#endif
@@ -596,9 +596,6 @@ static enum ROCKSDB_NAMESPACE::CompressionType
FLAGS_compressed_secondary_cache_compression_type_e =
ROCKSDB_NAMESPACE::kLZ4Compression;
DEFINE_string(compression_manager, "none",
"Set the compression manager type to mixed(roundrobin) or other "
"type. None for BuilInCompressor");
DEFINE_int32(compressed_secondary_cache_compression_level,
ROCKSDB_NAMESPACE::CompressionOptions().level,
"Compression level. The meaning of this value is library-"
@@ -1814,15 +1811,6 @@ DEFINE_bool(track_and_verify_wals_in_manifest, false,
DEFINE_bool(track_and_verify_wals, false, "See Options.track_and_verify_wals");
DEFINE_int32(same_value_percentage, 0,
"Percentage of time value will be same i.e good for compression "
"of the block");
DEFINE_bool(universal_reduce_file_locking,
ROCKSDB_NAMESPACE::Options()
.compaction_options_universal.reduce_file_locking,
"See Options().compaction_options_universal.reduce_file_locking");
namespace ROCKSDB_NAMESPACE {
namespace {
static Status CreateMemTableRepFactory(
@@ -1943,10 +1931,9 @@ class RandomGenerator {
std::string data_;
unsigned int pos_;
std::unique_ptr<BaseDistribution> dist_;
Random rnd;
public:
RandomGenerator() : rnd(301) {
RandomGenerator() {
auto max_value_size = FLAGS_value_size_max;
switch (FLAGS_value_size_distribution_type_e) {
case kUniform:
@@ -1965,6 +1952,7 @@ class RandomGenerator {
// We use a limited amount of data over and over again and ensure
// that it is larger than the compression window (32KB), and also
// large enough to serve all typical value sizes we want to write.
Random rnd(301);
std::string piece;
while (data_.size() < (unsigned)std::max(1048576, max_value_size)) {
// Add a short fragment that is as compressible as specified
@@ -1977,15 +1965,11 @@ class RandomGenerator {
Slice Generate(unsigned int len) {
assert(len <= data_.size());
if (rnd.PercentTrue(FLAGS_same_value_percentage)) {
return Slice(data_.data(), len);
} else {
if (pos_ + len > data_.size()) {
pos_ = 0;
}
pos_ += len;
return Slice(data_.data() + pos_ - len, len);
if (pos_ + len > data_.size()) {
pos_ = 0;
}
pos_ += len;
return Slice(data_.data() + pos_ - len, len);
}
Slice Generate() {
@@ -2900,15 +2884,8 @@ class Benchmark {
}
#endif
}
// mixed compression manager expect compression type to be expliciltiy
// configured through Options to be zstd
auto compression = std::string("zstd");
if (!strcasecmp(FLAGS_compression_manager.c_str(), "none")) {
compression = CompressionTypeToString(FLAGS_compression_type_e);
} else {
fprintf(stdout, "Compression manager: %s\n",
FLAGS_compression_manager.c_str());
}
auto compression = CompressionTypeToString(FLAGS_compression_type_e);
fprintf(stdout, "Compression: %s\n", compression.c_str());
fprintf(stdout, "Compression sampling rate: %" PRId64 "\n",
FLAGS_sample_for_compression);
@@ -4633,39 +4610,7 @@ class Benchmark {
FLAGS_level0_file_num_compaction_trigger;
options.level0_slowdown_writes_trigger =
FLAGS_level0_slowdown_writes_trigger;
if (!strcasecmp(FLAGS_compression_manager.c_str(), "none")) {
options.compression = FLAGS_compression_type_e;
} else {
std::shared_ptr<CompressionManagerWrapper> mgr;
if (!strcasecmp(FLAGS_compression_manager.c_str(), "mixed")) {
// Need to list zstd in the compression_name table property if it's
// potentially used by being in the mix (i.e., potentially at least one
// data block in the table is compressed by zstd). This ensures proper
// context and dictionary handling, and prevents crashes in older
// RocksDB versions.
options.compression = kZSTD;
options.bottommost_compression = kZSTD;
mgr = std::make_shared<RoundRobinManager>(
GetDefaultBuiltinCompressionManager());
} else if (!strcasecmp(FLAGS_compression_manager.c_str(), "autoskip")) {
options.compression = FLAGS_compression_type_e;
if (FLAGS_compression_type_e == kNoCompression) {
fprintf(stderr,
"Compression type must not be no Compression when using "
"autoskip");
ErrorExit();
}
mgr = CreateAutoSkipCompressionManager(
GetDefaultBuiltinCompressionManager());
} else {
// not defined -> exit with error
fprintf(stderr, "Requested compression manager not supported");
ErrorExit();
}
options.compression_manager = mgr;
}
options.compression = FLAGS_compression_type_e;
if (FLAGS_simulate_hybrid_fs_file != "") {
options.last_level_temperature = Temperature::kWarm;
}
@@ -4811,8 +4756,6 @@ class Benchmark {
options.paranoid_memory_checks = FLAGS_paranoid_memory_checks;
options.memtable_op_scan_flush_trigger =
FLAGS_memtable_op_scan_flush_trigger;
options.compaction_options_universal.reduce_file_locking =
FLAGS_universal_reduce_file_locking;
}
void InitializeOptionsGeneral(Options* opts, ToolHooks& hooks) {
+5 -35
View File
@@ -107,8 +107,7 @@ default_params = {
"iterpercent": 10,
"lock_wal_one_in": lambda: random.choice([10000, 1000000]),
"mark_for_compaction_one_file_in": lambda: 10 * random.randint(0, 1),
"max_background_compactions": lambda: random.choice([2, 20]),
"num_bottom_pri_threads": lambda: random.choice([0, 1, 20]),
"max_background_compactions": 20,
"max_bytes_for_level_base": 10485760,
# max_key has to be the same across invocations for verification to work, hence no lambda
"max_key": random.choice([100000, 25000000]),
@@ -346,14 +345,8 @@ default_params = {
"enable_remote_compaction": lambda: random.choice([0, 1]),
"auto_refresh_iterator_with_snapshot": lambda: random.choice([0, 1]),
"memtable_op_scan_flush_trigger": lambda: random.choice([0, 10, 100, 1000]),
"memtable_avg_op_scan_flush_trigger": lambda: random.choice([0, 2, 20, 200]),
"ingest_wbwi_one_in": lambda: random.choice([0, 0, 100, 500]),
"universal_reduce_file_locking": lambda: random.randint(0, 1),
"compression_manager": lambda: random.choice(
["mixed"] * 1 + ["none"] * 2 + ["autoskip"] * 2 + ["randommixed"] * 2
),
}
_TEST_DIR_ENV_VAR = "TEST_TMPDIR"
# If TEST_TMPDIR_EXPECTED is not specified, default value will be TEST_TMPDIR
_TEST_EXPECTED_DIR_ENV_VAR = "TEST_TMPDIR_EXPECTED"
@@ -1001,33 +994,10 @@ def finalize_and_sanitize(src_params):
# have to disable metadata write fault injection to other file
dest_params["exclude_wal_from_write_fault_injection"] = 1
dest_params["metadata_write_fault_one_in"] = 0
# Disabling block align if mixed manager is neing used
if (
dest_params.get("compression_manager") == "mixed"
or dest_params.get("compression_manager") == "randommixed"
):
if dest_params.get("block_align") == 1:
dest_params["block_align"] = 0
dest_params["compression_type"] = "zstd"
dest_params["bottommost_compression_type"] = "zstd"
elif dest_params.get("compression_manager") == "autoskip":
# disabling compression parallel threads if auto skip manager is being used as the predictor is not thread safe
dest_params["compression_parallel_threads"] = 1
# esuring the compression is being used
if dest_params.get("compression_type") == "none":
dest_params["compression_type"] = random.choice(
["snappy", "zlib", "lz4", "lz4hc", "xpress", "zstd"]
)
if dest_params.get("bottommost_compression_type") == "none":
dest_params["bottommost_compression_type"] = random.choice(
["snappy", "zlib", "lz4", "lz4hc", "xpress", "zstd"]
)
dest_params["block_align"] = 0
else:
# Enabling block_align with compression is not supported
if dest_params.get("block_align") == 1:
dest_params["compression_type"] = "none"
dest_params["bottommost_compression_type"] = "none"
# Enabling block_align with compression is not supported
if dest_params.get("block_align") == 1:
dest_params["compression_type"] = "none"
dest_params["bottommost_compression_type"] = "none"
# If periodic_compaction_seconds is not set, daily_offpeak_time_utc doesn't do anything
if dest_params.get("periodic_compaction_seconds") == 0:
dest_params["daily_offpeak_time_utc"] = ""
+7 -16
View File
@@ -44,7 +44,6 @@
#include "util/cast_util.h"
#include "util/coding.h"
#include "util/file_checksum_helper.h"
#include "util/simple_mixed_compressor.h"
#include "util/stderr_logger.h"
#include "util/string_util.h"
#include "util/write_batch_util.h"
@@ -868,21 +867,13 @@ bool LDBCommand::ParseCompressionTypeOption(
"No compressions are supported in this build for \"mixed\".");
return false;
}
options_.compression = kZSTD;
options_.bottommost_compression = kZSTD;
auto mgr = std::make_shared<RoundRobinManager>(
GetDefaultBuiltinCompressionManager());
options_.compression_manager = mgr;
// Need to list zstd in the compression_name table property if it's
// potentially used by being in the mix (i.e., potentially at least one
// data block in the table is compressed by zstd). This ensures proper
// context and dictionary handling, and prevents crashes in older RocksDB
// versions.
//
// To achieve this, set `value` (the compression_type in Options which
// will be used to set compression_name table property) to kZSTD, even if
// multiple compression types are used within a single table.
// A temporary hack to generate an SST file with a mix of compression
// types, as this has been *de facto* supported for a long time on the
// read side with no code to generate them on the write side. We can test
// that functionality, e.g. in check_format_compatible.sh, with this hack
g_hack_mixed_compression.StoreRelaxed(1);
// Need to list zstd in compression_name table property if it's
// potentially in the mix, for proper handling of context and dictionary.
value = ZSTD_Supported() ? kZSTD : GetSupportedCompressions()[0];
return true;
#endif // !NDEBUG
@@ -1 +0,0 @@
* `TransactionOptions::large_txn_commit_optimize_threshold` now has default value 0 for disabled. `TransactionDBOptions::txn_commit_bypass_memtable_threshold` now has no effect on transactions.
@@ -1 +0,0 @@
* Fix a bug where CreateColumnFamilyWithImport() could miss the SST file for the memtable flush it triggered. The exported CF then may not contain the updates in the memtable when CreateColumnFamilyWithImport() is called.
@@ -1 +0,0 @@
Fix iterator operations returning NotImplemented status if disallow_memtable_writes and paranoid_memory_checks CF options are both set.
@@ -1 +0,0 @@
* Add a new CF option `memtable_avg_op_scan_flush_trigger` that supports triggering memtable flush when an iterator scans through an expensive range of keys, with the average number of skipped keys from the active memtable exceeding the threshold.
@@ -1 +0,0 @@
* Add new experimental `TransactionOptions::large_txn_commit_optimize_byte_threshold` to enable optimizations for large transaction commit by transaction batch data size.
@@ -1 +0,0 @@
Add a new option `CompactionOptionsUniversal::reduce_file_locking` and if it's true, auto universal compaction picking will adjust to minimize locking of input files when bottom priority compactions are waiting to run. This can increase the likelihood of existing L0s being selected for compaction, thereby improving write stall and reducing read regression.
-108
View File
@@ -1,108 +0,0 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
//
#include "util/auto_skip_compressor.h"
#include "options/options_helper.h"
#include "rocksdb/advanced_compression.h"
#include "test_util/sync_point.h"
#include "util/random.h"
namespace ROCKSDB_NAMESPACE {
int CompressionRejectionProbabilityPredictor::Predict() const {
return pred_rejection_prob_percentage_;
}
size_t CompressionRejectionProbabilityPredictor::attempted_compression_count()
const {
return rejected_count_ + compressed_count_;
}
bool CompressionRejectionProbabilityPredictor::Record(
Slice uncompressed_block_data, std::string* compressed_output,
const CompressionOptions& opts) {
if (compressed_output->size() >
(static_cast<uint64_t>(opts.max_compressed_bytes_per_kb) *
uncompressed_block_data.size()) >>
10) {
rejected_count_++;
} else {
compressed_count_++;
}
auto attempted = attempted_compression_count();
if (attempted >= window_size_) {
pred_rejection_prob_percentage_ =
static_cast<int>(rejected_count_ * 100 / attempted);
compressed_count_ = 0;
rejected_count_ = 0;
assert(attempted_compression_count() == 0);
}
return true;
}
AutoSkipCompressorWrapper::AutoSkipCompressorWrapper(
std::unique_ptr<Compressor> compressor, const CompressionOptions& opts)
: CompressorWrapper::CompressorWrapper(std::move(compressor)),
opts_(opts),
predictor_(
std::make_shared<CompressionRejectionProbabilityPredictor>(10)) {}
Status AutoSkipCompressorWrapper::CompressBlock(
Slice uncompressed_data, std::string* compressed_output,
CompressionType* out_compression_type, ManagedWorkingArea* wa) {
bool exploration =
Random::GetTLSInstance()->PercentTrue(kExplorationPercentage);
TEST_SYNC_POINT_CALLBACK(
"AutoSkipCompressorWrapper::CompressBlock::exploitOrExplore",
&exploration);
if (exploration) {
return CompressBlockAndRecord(uncompressed_data, compressed_output,
out_compression_type, wa);
} else {
auto prediction = predictor_->Predict();
if (prediction <= kProbabilityCutOff) {
// decide to compress
return CompressBlockAndRecord(uncompressed_data, compressed_output,
out_compression_type, wa);
} else {
// decide to bypass compression
*out_compression_type = kNoCompression;
return Status::OK();
}
}
return Status::OK();
}
Status AutoSkipCompressorWrapper::CompressBlockAndRecord(
Slice uncompressed_data, std::string* compressed_output,
CompressionType* out_compression_type, ManagedWorkingArea* wa) {
Status status = wrapped_->CompressBlock(uncompressed_data, compressed_output,
out_compression_type, wa);
// determine if it was rejected or compressed
predictor_->Record(uncompressed_data, compressed_output, opts_);
return status;
}
const char* AutoSkipCompressorManager::Name() const {
// should have returned "AutoSkipCompressorManager" but we currently have an
// error so for now returning name of the wrapped container
return wrapped_->Name();
}
std::unique_ptr<Compressor> AutoSkipCompressorManager::GetCompressorForSST(
const FilterBuildingContext& context, const CompressionOptions& opts,
CompressionType preferred) {
assert(GetSupportedCompressions().size() > 1);
assert(preferred != kNoCompression);
return std::make_unique<AutoSkipCompressorWrapper>(
wrapped_->GetCompressorForSST(context, opts, preferred), opts);
}
std::shared_ptr<CompressionManagerWrapper> CreateAutoSkipCompressionManager(
std::shared_ptr<CompressionManager> wrapped) {
return std::make_shared<AutoSkipCompressorManager>(
wrapped == nullptr ? GetDefaultBuiltinCompressionManager() : wrapped);
}
} // namespace ROCKSDB_NAMESPACE
-65
View File
@@ -1,65 +0,0 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
//
// Creates auto skip compressor wrapper which intelligently decides bypassing
// compression based on past data
#pragma once
#include <memory>
#include "rocksdb/advanced_compression.h"
#include "util/compression.h"
namespace ROCKSDB_NAMESPACE {
// Predict rejection probability using a moving window approach
// This class is not thread safe
class CompressionRejectionProbabilityPredictor {
public:
CompressionRejectionProbabilityPredictor(int window_size)
: pred_rejection_prob_percentage_(0),
rejected_count_(0),
compressed_count_(0),
window_size_(window_size) {}
int Predict() const;
bool Record(Slice uncompressed_block_data, std::string* compressed_output,
const CompressionOptions& opts);
size_t attempted_compression_count() const;
protected:
int pred_rejection_prob_percentage_;
size_t rejected_count_;
size_t compressed_count_;
size_t window_size_;
};
class AutoSkipCompressorWrapper : public CompressorWrapper {
public:
explicit AutoSkipCompressorWrapper(std::unique_ptr<Compressor> compressor,
const CompressionOptions& opts);
Status CompressBlock(Slice uncompressed_data, std::string* compressed_output,
CompressionType* out_compression_type,
ManagedWorkingArea* wa) override;
private:
Status CompressBlockAndRecord(Slice uncompressed_data,
std::string* compressed_output,
CompressionType* out_compression_type,
ManagedWorkingArea* wa);
static constexpr int kExplorationPercentage = 10;
static constexpr int kProbabilityCutOff = 50;
const CompressionOptions opts_;
std::shared_ptr<CompressionRejectionProbabilityPredictor> predictor_;
};
class AutoSkipCompressorManager : public CompressionManagerWrapper {
using CompressionManagerWrapper::CompressionManagerWrapper;
const char* Name() const override;
std::unique_ptr<Compressor> GetCompressorForSST(
const FilterBuildingContext& context, const CompressionOptions& opts,
CompressionType preferred) override;
};
} // namespace ROCKSDB_NAMESPACE
+47
View File
@@ -85,4 +85,51 @@ class UnownedPtr {
T* ptr_ = nullptr;
};
// A smart pointer that tracks an object and an owner, using a statically
// determined function on those to reclaim the object, if both object and owner
// are non-null
template <typename T, class Owner, auto Fn>
class ManagedPtr {
public:
ManagedPtr() = default;
ManagedPtr(T* ptr, Owner* owner) : ptr_(ptr), owner_(owner) {}
~ManagedPtr() {
if (ptr_ && owner_) {
if constexpr (std::is_member_function_pointer_v<decltype(Fn)>) {
(owner_->*Fn)(ptr_);
} else {
Fn(owner_, ptr_);
}
}
}
// No copies
ManagedPtr(const ManagedPtr&) = delete;
ManagedPtr& operator=(const ManagedPtr&) = delete;
// Moves
ManagedPtr(ManagedPtr&& other) noexcept {
ptr_ = other.ptr_;
owner_ = other.owner_;
other.ptr_ = nullptr;
other.owner_ = nullptr;
}
ManagedPtr& operator=(ManagedPtr&& other) noexcept {
ptr_ = other.ptr_;
owner_ = other.owner_;
other.ptr_ = nullptr;
other.owner_ = nullptr;
return *this;
}
T* get() const { return ptr_; }
T* operator->() const { return ptr_; }
T& operator*() const { return *ptr_; }
operator bool() const { return ptr_ != nullptr; }
Owner* owner() const { return owner_; }
private:
T* ptr_ = nullptr;
Owner* owner_ = nullptr;
};
} // namespace ROCKSDB_NAMESPACE
+25 -50
View File
@@ -6,7 +6,6 @@
#include "util/compression.h"
#include "options/options_helper.h"
#include "rocksdb/convenience.h"
namespace ROCKSDB_NAMESPACE {
@@ -125,26 +124,6 @@ void ZSTDStreamingUncompress::Reset() {
// ***********************************************************************
// BEGIN built-in implementation of customization interface
// ***********************************************************************
Status Decompressor::ExtractUncompressedSize(Args& args) {
// Default implementation:
//
// Standard format for prepending uncompressed size to the compressed
// payload. (RocksDB compress_format_version=2 except Snappy)
//
// This is historically a varint32, but it is preliminarily generalized
// to varint64. (TODO: support that on the write side, at least for some
// codecs, in BBT format_version=7)
if (LIKELY(GetVarint64(&args.compressed_data, &args.uncompressed_size))) {
if (LIKELY(args.uncompressed_size <= SIZE_MAX)) {
return Status::OK();
} else {
return Status::MemoryLimit("Uncompressed size too large for platform");
}
} else {
return Status::Corruption("Unable to extract uncompressed size");
}
}
const Slice& Decompressor::GetSerializedDict() const {
// Default: empty slice => no dictionary
static Slice kEmptySlice;
@@ -254,6 +233,7 @@ class BuiltinCompressorV2 : public Compressor {
void ReleaseWorkingArea(WorkingArea* wa) override {
delete static_cast<CompressionContext*>(wa);
}
Status CompressBlock(Slice uncompressed_data, std::string* compressed_output,
CompressionType* out_compression_type,
ManagedWorkingArea* wa) override {
@@ -263,6 +243,16 @@ class BuiltinCompressorV2 : public Compressor {
ctx = static_cast<CompressionContext*>(wa->get());
}
CompressionType type = type_;
#ifndef NDEBUG
if (type != kNoCompression && g_hack_mixed_compression.LoadRelaxed() > 0U) {
// If zstd is in the mix, the compression_name table property needs to be
// set to it, for proper handling of context and dictionaries.
assert(!ZSTD_Supported() || type == kZSTD);
const auto& compressions = GetSupportedCompressions();
auto counter = g_hack_mixed_compression.FetchAddRelaxed(1);
type = compressions[counter % compressions.size()];
}
#endif // !NDEBUG
if (ctx == nullptr) {
tmp_ctx.emplace(type, opts_);
ctx = &*tmp_ctx;
@@ -809,6 +799,7 @@ Status BuiltinDecompressorV2OptimizeZstd::MaybeCloneForDict(
serialized_dict);
return Status::OK();
}
class BuiltinCompressionManagerV2 : public CompressionManager {
public:
BuiltinCompressionManagerV2() = default;
@@ -881,36 +872,22 @@ const std::shared_ptr<BuiltinCompressionManagerV2>
} // namespace
Status CompressionManager::CreateFromString(
const ConfigOptions& /*config_options*/, const std::string& id,
std::shared_ptr<CompressionManager>* result) {
if (id == kNullptrString || id.empty()) {
result->reset();
return Status::OK();
} else if (id.compare(kBuiltinCompressionManagerV1->CompatibilityName()) ==
0 ||
id.compare(kBuiltinCompressionManagerV1->Name()) == 0) {
*result = kBuiltinCompressionManagerV1;
return Status::OK();
} else if (id.compare(kBuiltinCompressionManagerV2->CompatibilityName()) ==
0 ||
id.compare(kBuiltinCompressionManagerV2->Name()) == 0) {
*result = kBuiltinCompressionManagerV2;
return Status::OK();
} else {
return Status::NotFound("Compatible compression manager for \"" + id +
"\"");
}
}
Status CompressionManager::FindCompatibleCompressionManager(
Slice compatibility_name, std::shared_ptr<CompressionManager>* out) {
if (compatibility_name.compare(CompatibilityName()) == 0) {
*out = shared_from_this();
return Status::OK();
} else if (compatibility_name.compare(
kBuiltinCompressionManagerV1->CompatibilityName()) == 0) {
*out = kBuiltinCompressionManagerV1;
return Status::OK();
} else if (compatibility_name.compare(
kBuiltinCompressionManagerV2->CompatibilityName()) == 0) {
*out = kBuiltinCompressionManagerV2;
return Status::OK();
} else {
return CreateFromString(ConfigOptions(), compatibility_name.ToString(),
out);
return Status::NotFound("Compatible compression manager for \"" +
compatibility_name.ToString() + "\"");
}
}
@@ -932,13 +909,11 @@ const std::shared_ptr<CompressionManager>& GetBuiltinCompressionManager(
}
}
const std::shared_ptr<CompressionManager>&
GetDefaultBuiltinCompressionManager() {
return GetBuiltinCompressionManager(2);
}
// ***********************************************************************
// END built-in implementation of customization interface
// ***********************************************************************
#ifndef NDEBUG
RelaxedAtomic<uint64_t> g_hack_mixed_compression{0};
#endif // !NDEBUG
} // namespace ROCKSDB_NAMESPACE
+426 -11
View File
@@ -12,6 +12,9 @@
#include <algorithm>
#include <limits>
#include "port/likely.h"
#include "util/atomic.h"
#include "util/cast_util.h"
#ifdef ROCKSDB_MALLOC_USABLE_SIZE
#ifdef OS_FREEBSD
#include <malloc_np.h>
@@ -22,12 +25,10 @@
#include <string>
#include "memory/memory_allocator_impl.h"
#include "port/likely.h"
#include "rocksdb/advanced_compression.h"
#include "rocksdb/options.h"
#include "rocksdb/table.h"
#include "table/block_based/block_type.h"
#include "test_util/sync_point.h"
#include "util/atomic.h"
#include "util/coding.h"
#include "util/compression_context_cache.h"
#include "util/string_util.h"
@@ -147,6 +148,422 @@ class ZSTDUncompressCachedData {
namespace ROCKSDB_NAMESPACE {
// ***********************************************************************
// BEGIN future compression customization interface
// ***********************************************************************
// TODO: alias/adapt for compression
struct FilterBuildingContext;
// A Compressor represents a very specific but potentially adapting strategy for
// compressing blocks, including the relevant algorithm(s), options, dictionary,
// etc. as applicable--every input except the sequence of bytes to compress.
// Compressor is generally thread-safe so can be shared by multiple threads. (It
// could make sense to convert unique_ptr<Compressor> to
// shared_ptr<Compressor>.) A Compressor for data files is expected to be used
// for just one file, so that compression strategy can be explicitly
// reconsidered for each new file. However, a Compressor for in-memory use could
// live indefinitely.
//
// If a single thread is doing many compressions under the same strategy, it
// should request a WorkingArea that will in some cases make repeated
// compression in a single thread more efficient. Unlike the rest of Compressor,
// each WorkingArea can only be used by one thread at a time. WorkingAreas can
// have pre-allocated space and/or data structures, and/or thread-local
// statistics that are later incorporated into shared statistics objects.
//
// The Compressor marks each block with a CompressionType to guide
// decompression. However, the compression dictionary (or whether there is one
// associated) is determined at Compressor creation time, though the process of
// getting a Compressor with a dictionary starts with a Compressor without
// dictionary (which will often be relevant alongside); see relevant functions.
// If the Compressor wants to decide block-by-block whether to apply the
// configured dictionary, that would need to be encoded in CompressionType or
// the compressed output. (NOTE: this was historically NOT encoded in
// CompressionType and instead implied by BlockType and the presence of a
// dictionary block in the file. Some of the resulting awkwardness includes
// a number of built-in CompressionTypes that ignore any dictionary block in
// the file; therefore they cannot accommodate dictionary compression in the
// future without a schema change / extension.)
class Compressor {
public:
Compressor() = default;
virtual ~Compressor() = default;
// Returns the max total bytes of for all sampled blocks for creating the data
// dictionary, or zero indicating dictionary compression should not be
// used/configured. This will typically be called after
// CompressionManager::GetCompressor() to see if samples should be accumulated
// and passed to MaybeCloneSpecialized().
virtual size_t GetMaxSampleSizeIfWantDict(CacheEntryRole block_type) const {
// Default implementation: no dictionary
(void)block_type;
return 0;
}
// Returns the serialized form of the data dictionary associated with this
// Compressor. NOTE: empty dict is equivalent to no dict.
virtual Slice GetSerializedDict() const { return Slice(); }
// If there's a dominant compression type returned by this compressor as
// configured, return it. Otherwise, return kDisableCompressionOption.
virtual CompressionType GetPreferredCompressionType() const {
return CompressionType::kDisableCompressionOption;
}
// Utility struct for providing sample data for the compression dictionary.
// Potentially extensible by callers of Compressor (but not recommended)
struct DictSampleArgs {
// All the sample input blocks stored contiguously
std::string sample_data;
// The lengths of each of the sample blocks in `sample_data`
std::vector<size_t> sample_lens;
bool empty() { return sample_data.empty(); }
bool Verify() {
size_t total_len = 0;
for (auto len : sample_lens) {
total_len += len;
}
return total_len == sample_data.size();
}
};
// Create potential variants of the same Compressor that might be
// (a) optimized for a particular block type (does not affect correct
// decompression), and/or
// (b) configured to use a compression dictionary, based on the given
// samples (decompression must provide the dictionary from
// GetSerializedDict())
// Return of nullptr indicates no specialization exists or was attempted
// and the caller is best to use the current Compressor for the desired
// scenario. Using CacheEntryRole:kMisc for block_type generally means
// "unspecified", and both parameters are merely suggestions. The exact
// dictionary associated with a returned compressor must be read from
// GetSerializedDict().
virtual std::unique_ptr<Compressor> MaybeCloneSpecialized(
CacheEntryRole block_type, DictSampleArgs&& dict_samples) {
// Default implementation: no specialization
(void)block_type;
(void)dict_samples;
// Caller should have checked GetMaxSampleSizeIfWantDict before attempting
// to provide dictionary samples
assert(dict_samples.empty());
return nullptr;
}
// A WorkingArea is an optional structure (both for callers and
// implementations) that can enable optimizing repeated compressions by
// reusing working space or thread-local tracking of statistics or trends.
// This enables use of ZSTD context, for example.
//
// EXTENSIBLE or reinterpret_cast-able by custom Compressor implementations
struct WorkingArea {};
protected:
// To allow for flexible re-use / reclaimation, we have explicit Get and
// Release functions, and usually wrap in a special RAII smart pointer.
// For example, a WorkingArea could be saved/recycled in thread-local or
// core-local storage, or heap managed, etc., though an explicit WorkingArea
// is only advised for repeated compression (by a single thread).
virtual void ReleaseWorkingArea(WorkingArea*) {}
public:
using ManagedWorkingArea =
ManagedPtr<WorkingArea, Compressor, &Compressor::ReleaseWorkingArea>;
// See struct WorkingArea above
virtual ManagedWorkingArea ObtainWorkingArea() {
// Default implementation: no working area
return {};
}
// Compress `uncompressed_data` to `compressed_output`, which should be
// passed in empty. Note that the compressed output will be decompressed
// by the sequence Decompressor::ExtractUncompressedSize() followed by
// Decompressor::DecompressBlock(), which must also be provided the same
// CompressionType saved in `out_compression_type`. (In many configurations,
// `compressed_output` will have a prefix storing the uncompressed_data size
// before the compressed bytes returned by the underlying compression
// algorithm. And the compression type is usually stored adjacent to the
// compressed data, or in some cases assumed/asserted based on the particular
// Compressor.)
//
// If return status is not OK, then some fatal condition has arisen. On OK
// status, setting `*out_compression_type = kNoCompression` means compression
// is declined and the caller should use the original uncompressed_data and
// ignore any result in `compressed_output`. Otherwise, compression has
// happened with results in `compressed_output` and `out_compression_type`,
// which are allowed to vary from call to call.
//
// The working area is optional and used to optimize repeated compression by
// a single thread. ManagedWorkingArea is provided rather than just
// WorkingArea so that it can be used only if the `owner` matches expectation.
// This could be useful for a Compressor wrapping more than one alternative
// underlying Compressor.
//
// TODO: instead of string, consider a buffer only large enough for max
// tolerable compressed size. Does that work for all existing algorithms?
// * Looks like Snappy doesn't support that. :(
// * But looks like everything else should. :)
// Could save CPU by eliminating extra zero-ing and giving up quicker when
// ratio is insufficient.
virtual Status CompressBlock(Slice uncompressed_data,
std::string* compressed_output,
CompressionType* out_compression_type,
ManagedWorkingArea* working_area) = 0;
// TODO: something to populate table properties based on settings, after all
// or as WorkingAreas released. Maybe also update stats, or that could be in
// thread-specific WorkingArea.
};
// TODO: CompressorBase and CompressorWrapper
// A Decompressor usually has a wide capability to decompress all kinds of
// compressed data in the scope of a CompressionManager (see that class below),
// except
// (a) it might be optimized for or limited to a particular compression type(s)
// (see GetDecompressor* functions for in CompressionManager),
// (b) distinct Decompressors are required to decompress with compression
// dictionaries. (Decompressors are generally associated with empty/no
// dictionary unless created with MaybeCloneForDict().)
//
// Similar to Compressor, Decompressor is generally thread safe except that each
// WorkingArea can only be used by a single thread at a time.
//
// Decompressors known to be associated with no dictionary are typically
// returned as shared_ptr, because they are broadly usable across threads.
// Because compression dictionaries are externally managed (see
// MaybeCloneForDict()), Decompressors associated with compression dictionaries
// are typically returned as unique_ptr, so that they are more easily
// guaranteed not to outlive their dictionaries (e.g. in block cache).
// Decompressors associated with compression dictionaries might include a
// processed or "digested" form of the raw dictionary for efficient repeated
// compressions.
//
// NOTE: Splitting the interface between ExtractUncompressedSize and
// DecompressBlock leaves to the caller details of (and flexibility in)
// allocating buffers for decompressing into. For example, the data could be
// decompressed into part of a single buffer allocated to hold a block's
// uncompressed contents along with an in-memory object representation of the
// block (to reduce fragmentation and other overheads of separate objects).
class Decompressor {
public:
Decompressor() = default;
virtual ~Decompressor() = default;
// A name for logging / debugging purposes
virtual const char* Name() const = 0;
// A WorkingArea is an optional structure (both for callers and
// implementations) that can enable optimizing repeated decompressions by
// reusing working space or thread-local tracking of statistics. This enables
// use of ZSTD context, for example.
//
// EXTENSIBLE or reinterpret_cast-able by custom Compressor implementations
struct WorkingArea {};
protected:
// To allow for flexible re-use / reclaimation, we have explicit Obtain and
// Release functions, which are typically wrapped in a special RAII smart
// pointer. For example, a WorkingArea could be saved/recycled in thread-local
// or core-local storage, or heap managed, etc., though an explicit
// WorkingArea is only advised for repeated decompression (by a single
// thread).
virtual void ReleaseWorkingArea(WorkingArea* wa) {
// Default implementation: no working area
(void)wa;
assert(wa == nullptr);
}
public:
using ManagedWorkingArea =
ManagedPtr<WorkingArea, Decompressor, &Decompressor::ReleaseWorkingArea>;
virtual ManagedWorkingArea ObtainWorkingArea(CompressionType /*preferred*/) {
// Default implementation: no working area
return {};
}
// If this Decompressor is associated with a (de)compression dictionary
// (created with MaybeCloneForDict()), this returns a pointer to those raw (or
// "serialized") bytes, which are externally managed (see
// MaybeCloneForDict()).
// Default: empty slice => no dictionary
virtual const Slice& GetSerializedDict() const;
// Create a variant of this Decompressor in `out` using the specified raw
// ("serialized") dictionary. This step is required for decompressing data
// compressed with the same dictionary. The new Decompressor references the
// given Slice through its lifetime so the data it points to must be managed
// by the caller along with (or beyond) the new Decompressor. If the
// dictionary is processed into a form reusable by repeated compressions in
// many threads, that happens within this call.
//
// Must return OK if storing a result in `out`. Otherwise, could return values
// like NotSupported - dictionary compression is not (yet) supported for this
// kind of Decompressor.
// Corruption - dictionary is malformed (though many implementations will
// accept any data as a dictionary)
virtual Status MaybeCloneForDict(const Slice& /*serialized_dict*/,
std::unique_ptr<Decompressor>* /*out*/) {
return Status::NotSupported(
"Dictionary compression not (yet) supported by " + std::string(Name()));
}
// Memory size of this object and others it owns. Does not include the
// serialized dictionary (when used) which is externally managed.
virtual size_t ApproximateOwnedMemoryUsage() const {
// Default: negligible
return 0;
}
// Potentially extensible by callers of Decompressor (but not recommended)
struct Args {
CompressionType compression_type = kNoCompression;
Slice compressed_data;
uint64_t uncompressed_size = 0;
ManagedWorkingArea* working_area = nullptr;
};
// For efficiency on the read path, RocksDB strongly prefers the uncompressed
// data size to be encoded in the compressed data in an easily accessible way,
// so that allocation of a potentially long-lived buffer can be ideally sized.
// This function determines the uncompressed size and potentially modifies
// `args.compressed_data` to strip off the size metadata, for providing both
// to DecompressBlock along with an appropriate buffer based on that size.
// Some implementations will leave `compressed_data` unmodified and let
// DecompressBlock call a library function that processes a format that
// includes size metadata (e.g. Snappy).
//
// Even for legacy cases without size metadata (e.g. some very old RocksDB
// formats), an exact size is required and could require decompressing the
// data (here and in DecompressBlock()).
//
// Return non-OK in case of corrupt data or some other unworkable limitation
// or failure.
virtual Status ExtractUncompressedSize(Args& args) {
// Default implementation:
//
// Standard format for prepending uncompressed size to the compressed
// payload. (RocksDB compress_format_version=2 except Snappy)
//
// This is historically a varint32, but it is preliminarily generalized
// to varint64. (TODO: support that on the write side, at least for some
// codecs, in BBT format_version=7)
if (LIKELY(GetVarint64(&args.compressed_data, &args.uncompressed_size))) {
if (LIKELY(args.uncompressed_size <= SIZE_MAX)) {
return Status::OK();
} else {
return Status::MemoryLimit("Uncompressed size too large for platform");
}
} else {
return Status::Corruption("Unable to extract uncompressed size");
}
}
// Called to decompress a block of data after running ExtractUncompressedSize
// on it. `args.compressed_data` is what ExtractUncompressedSize left there
// after potentially stripping off the uncompressed size metadata. Returns OK
// iff uncompressed data of size `uncompressed_size` is written to
// `uncompressed_output`.
virtual Status DecompressBlock(const Args& args,
char* uncompressed_output) = 0;
};
// A CompressionManager represents
// * When/where/how to use different compressions
// * A schema (or set of schemas) and implementation for mapping
// <CompressionType, dictionary, compressed data>
// to uncompressed data (or error), which can expand over time (error in fewer
// cases) for a given CompatibilityName() but can never change that mapping
// (because that would break backward compatibility, potential quiet
// corruption)
// TODO: consider adding optional streaming compression support (low priority)
class CompressionManager
: public std::enable_shared_from_this<CompressionManager> {
public:
CompressionManager() = default;
virtual ~CompressionManager() = default;
// TODO: Customizable (for compression side configuration and recording our
// compression strategy)
virtual const char* Name() const = 0;
virtual std::string GetId() const {
std::string id = Name();
return id;
}
// *************** Peer or variant Compression Managers **************** //
// A name for the schema family of this CompressionManager. In short, if
// two CompressionManagers have functionally the same Decompressor(s), they
// should have the same CompatibilityName(), so that a compatible
// CompressionManager/Decompressor might be used if the original is
// unavailable. (Name() can be useful in addition to CompatibilityName() for
// understanding what compression strategy was used.)
virtual const char* CompatibilityName() const = 0;
// Default implementation checks the current compatibility name and returns
// this CompressionManager (via `out`) if appropriate, and otherwise looks
// for a matching built-in CompressionManager.
virtual Status FindCompatibleCompressionManager(
Slice compatibility_name, std::shared_ptr<CompressionManager>* out);
// ************************* Compressor creation *********************** //
// Returning nullptr means compression is entirely disabled for the file,
// which is valid at the discretion of the CompressionManager. Returning
// nullptr should normally be the result if preferred == kNoCompression.
//
// These functions must be thread-safe.
// Get a compressor for an SST file.
// SUBJECT TO CHANGE
// TODO: is it practical to get ColumnFamilyOptions plumbed into here?
virtual std::unique_ptr<Compressor> GetCompressorForSST(
const FilterBuildingContext&, const CompressionOptions& opts,
CompressionType preferred) {
return GetCompressor(opts, preferred);
}
// Get a compressor for a generic/unspecified purpose (e.g. in-memory
// compression).
virtual std::unique_ptr<Compressor> GetCompressor(
const CompressionOptions& opts, CompressionType type) = 0;
// **************************** Decompressors ************************** //
// Get a decompressor that is compatible with any blocks compressed by
// compressors returned by this CompressionManager (at least this code
// revision and earlier). (NOTE: recommended to return a shared_ptr alias of
// this shared_ptr to a field that is a Decompressor.)
// Justification for not making CompressionManager inherit Decompressor: this
// tends to run into the diamond inheritance problem in implementations and
// potential overheads of virtual inheritance.
virtual std::shared_ptr<Decompressor> GetDecompressor() = 0;
// Compatible with same as above, but potentially optimized for a certain
// expected CompressionType
virtual std::shared_ptr<Decompressor> GetDecompressorOptimizeFor(
CompressionType /*optimize_for_type*/) {
// Safe default implementation
return GetDecompressor();
}
// Get a decompressor that is allowed to have support only for the
// CompressionTypes in the given start-to-end array (unique, sorted by
// unsigned char)
virtual std::shared_ptr<Decompressor> GetDecompressorForTypes(
const CompressionType* /*types_begin*/,
const CompressionType* /*types_end*/) {
// Safe default implementation
return GetDecompressor();
}
};
// ***********************************************************************
// END future compression customization interface
// ***********************************************************************
class FailureDecompressor : public Decompressor {
public:
explicit FailureDecompressor(Status&& status) : status_(std::move(status)) {
@@ -826,8 +1243,6 @@ inline std::string CompressionOptionsToString(
result.append("zstd_max_train_bytes=")
.append(std::to_string(compression_options.zstd_max_train_bytes))
.append("; ");
// NOTE: parallel_threads is skipped because it doesn't really affect the file
// contents written, arguably doesn't belong in CompressionOptions
result.append("enabled=")
.append(std::to_string(compression_options.enabled))
.append("; ");
@@ -837,12 +1252,6 @@ inline std::string CompressionOptionsToString(
result.append("use_zstd_dict_trainer=")
.append(std::to_string(compression_options.use_zstd_dict_trainer))
.append("; ");
result.append("max_compressed_bytes_per_kb=")
.append(std::to_string(compression_options.max_compressed_bytes_per_kb))
.append("; ");
result.append("checksum=")
.append(std::to_string(compression_options.checksum))
.append("; ");
return result;
}
@@ -1988,4 +2397,10 @@ class ZSTDStreamingUncompress final : public StreamingUncompress {
#endif
};
#ifndef NDEBUG
// 0 == disable the hack
// > 0 => counter for rotating through compression types
extern RelaxedAtomic<uint64_t> g_hack_mixed_compression;
#endif
} // namespace ROCKSDB_NAMESPACE
-216
View File
@@ -1,216 +0,0 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
//
// Testing the features of auto skip compression manager
//
// ***********************************************************************
// EXPERIMENTAL - subject to change while under development
// ***********************************************************************
#include <cstdlib>
#include <memory>
#include "db/db_test_util.h"
#include "port/stack_trace.h"
#include "rocksdb/flush_block_policy.h"
#include "table/block_based/block_builder.h"
#include "test_util/testutil.h"
#include "util/random.h"
namespace ROCKSDB_NAMESPACE {
class AutoSkipTestFlushBlockPolicy : public FlushBlockPolicy {
public:
explicit AutoSkipTestFlushBlockPolicy(const int window,
const BlockBuilder& data_block_builder,
std::shared_ptr<Statistics> statistics)
: window_(window),
num_keys_(0),
data_block_builder_(data_block_builder),
statistics_(statistics) {}
bool Update(const Slice& /*key*/, const Slice& /*value*/) override {
auto multiple_of_10 = num_keys_ / window_;
if (data_block_builder_.empty()) {
// First key in this block
return false;
}
// Check every window
if (num_keys_ % window_ == 0) {
auto set_exploration = [&](void* arg) {
bool* exploration = static_cast<bool*>(arg);
*exploration = true;
};
auto unset_exploration = [&](void* arg) {
bool* exploration = static_cast<bool*>(arg);
*exploration = false;
};
SyncPoint::GetInstance()->DisableProcessing();
SyncPoint::GetInstance()->ClearAllCallBacks();
// We force exploration to set the predicted rejection ratio and then test
// that the prediction is exploited
if (multiple_of_10 % 2 == 0) {
SyncPoint::GetInstance()->SetCallBack(
"AutoSkipCompressorWrapper::CompressBlock::exploitOrExplore",
set_exploration);
} else {
SyncPoint::GetInstance()->SetCallBack(
"AutoSkipCompressorWrapper::CompressBlock::exploitOrExplore",
unset_exploration);
}
SyncPoint::GetInstance()->EnableProcessing();
auto compressed_count = PopStat(NUMBER_BLOCK_COMPRESSED);
auto bypassed_count = PopStat(NUMBER_BLOCK_COMPRESSION_BYPASSED);
auto rejected_count = PopStat(NUMBER_BLOCK_COMPRESSION_REJECTED);
auto total = compressed_count + rejected_count + bypassed_count;
int rejection_percentage, bypassed_percentage, compressed_percentage;
if (total != 0) {
rejection_percentage = static_cast<int>(rejected_count * 100 / total);
bypassed_percentage = static_cast<int>(bypassed_count * 100 / total);
compressed_percentage =
static_cast<int>(compressed_count * 100 / total);
}
// use mulitple of 10 to get correct assertion
switch (multiple_of_10) {
case 1:
// This is exploration stage in which we set the rejection ratio to
// 0.6
EXPECT_EQ(rejection_percentage, 60);
EXPECT_EQ(bypassed_percentage, 0);
EXPECT_EQ(compressed_percentage, 40);
break;
case 2:
// With the rejection ratio set to 0.6 all the blocks should be
// bypassed in next window
EXPECT_EQ(rejection_percentage, 0);
EXPECT_EQ(bypassed_percentage, 100);
EXPECT_EQ(compressed_percentage, 0);
break;
case 3:
// This is exploration stage in which we set the rejection ratio to
// 0.4
EXPECT_EQ(rejection_percentage, 40);
EXPECT_EQ(bypassed_percentage, 0);
EXPECT_EQ(compressed_percentage, 60);
break;
case 4:
// With the rejection ratio set to 0.4 all the blocks should be
// attempted to be compressed
EXPECT_EQ(rejection_percentage, 60);
EXPECT_EQ(bypassed_percentage, 0);
EXPECT_EQ(compressed_percentage, 40);
}
}
num_keys_++;
return true;
}
uint64_t PopStat(Tickers t) { return statistics_->getAndResetTickerCount(t); }
private:
int window_;
int num_keys_;
const BlockBuilder& data_block_builder_;
std::shared_ptr<Statistics> statistics_;
};
class AutoSkipTestFlushBlockPolicyFactory : public FlushBlockPolicyFactory {
public:
explicit AutoSkipTestFlushBlockPolicyFactory(
const int window, std::shared_ptr<Statistics> statistics)
: window_(window), statistics_(statistics) {}
virtual const char* Name() const override {
return "AutoSkipTestFlushBlockPolicyFactory";
}
virtual FlushBlockPolicy* NewFlushBlockPolicy(
const BlockBasedTableOptions& /*table_options*/,
const BlockBuilder& data_block_builder) const override {
(void)data_block_builder;
return new AutoSkipTestFlushBlockPolicy(window_, data_block_builder,
statistics_);
}
private:
int window_;
std::shared_ptr<Statistics> statistics_;
};
class DBAutoSkip : public DBTestBase {
public:
Options options;
Random rnd_;
int key_index_;
DBAutoSkip()
: DBTestBase("db_auto_skip", /*env_do_fsync=*/true),
options(CurrentOptions()),
rnd_(231),
key_index_(0) {
options.compression_manager =
CreateAutoSkipCompressionManager(GetDefaultBuiltinCompressionManager());
auto statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
options.statistics = statistics;
options.statistics->set_stats_level(StatsLevel::kExceptTimeForMutex);
BlockBasedTableOptions bbto;
bbto.enable_index_compression = false;
bbto.flush_block_policy_factory.reset(
new AutoSkipTestFlushBlockPolicyFactory(10, statistics));
options.table_factory.reset(NewBlockBasedTableFactory(bbto));
DestroyAndReopen(options);
}
bool CompressionFriendlyPut(const int no_of_kvs, const int size_of_value) {
auto value = std::string(size_of_value, 'A');
for (int i = 0; i < no_of_kvs; ++i) {
auto status = Put(Key(key_index_), value);
EXPECT_EQ(status.ok(), true);
key_index_++;
}
return true;
}
bool CompressionUnfriendlyPut(const int no_of_kvs, const int size_of_value) {
auto value = rnd_.RandomBinaryString(size_of_value);
for (int i = 0; i < no_of_kvs; ++i) {
auto status = Put(Key(key_index_), value);
EXPECT_EQ(status.ok(), true);
key_index_++;
}
return true;
}
};
TEST_F(DBAutoSkip, AutoSkipCompressionManager) {
if (GetSupportedCompressions().size() > 1) {
const int kValueSize = 20000;
// This will set the rejection ratio to 60%
CompressionUnfriendlyPut(6, kValueSize);
CompressionFriendlyPut(4, kValueSize);
// This will verify all the data block compressions are bypassed based on
// previous prediction
CompressionUnfriendlyPut(6, kValueSize);
CompressionFriendlyPut(4, kValueSize);
// This will set the rejection ratio to 40%
CompressionUnfriendlyPut(4, kValueSize);
CompressionFriendlyPut(6, kValueSize);
// This will verify all the data block compression are attempted based on
// previous prediction
// Compression will be rejected for 6 compression unfriendly blocks
// Compression will be accepted for 4 compression friendly blocks
CompressionUnfriendlyPut(6, kValueSize);
CompressionFriendlyPut(4, kValueSize);
// Extra block write to ensure that the all above cases are checked
CompressionFriendlyPut(6, kValueSize);
CompressionFriendlyPut(4, kValueSize);
ASSERT_OK(Flush());
}
}
} // namespace ROCKSDB_NAMESPACE
int main(int argc, char** argv) {
ROCKSDB_NAMESPACE::port::InstallStackTraceHandler();
::testing::InitGoogleTest(&argc, argv);
RegisterCustomObjects(argc, argv);
return RUN_ALL_TESTS();
}
-2
View File
@@ -13,6 +13,4 @@ int CountTrailingZeroBitsForSmallEnumSet(uint64_t v) {
return CountTrailingZeroBits(v);
}
int BitsSetToOneForSmallEnumSet(uint64_t v) { return BitsSetToOne(v); }
} // namespace ROCKSDB_NAMESPACE::detail
-108
View File
@@ -1,108 +0,0 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
//
// Creates mixed compressor wrapper which uses multiple compression algorithm
// within same SST file.
#include "simple_mixed_compressor.h"
#include <options/options_helper.h>
#include "random.h"
#include "rocksdb/advanced_compression.h"
namespace ROCKSDB_NAMESPACE {
// MultiCompressorWrapper implementation
MultiCompressorWrapper::MultiCompressorWrapper(const CompressionOptions& opts,
CompressionType type,
CompressionDict&& dict) {
assert(type != kNoCompression);
assert(type == kZSTD);
auto builtInManager = GetDefaultBuiltinCompressionManager();
const auto& compressions = GetSupportedCompressions();
for (auto type_ : compressions) {
if (type_ == kNoCompression) {
continue;
}
compressors_.push_back(builtInManager->GetCompressor(opts, type_));
}
(void)dict;
(void)type;
}
size_t MultiCompressorWrapper::GetMaxSampleSizeIfWantDict(
CacheEntryRole block_type) const {
return compressors_.back()->GetMaxSampleSizeIfWantDict(block_type);
}
Slice MultiCompressorWrapper::GetSerializedDict() const {
return compressors_.back()->GetSerializedDict();
}
CompressionType MultiCompressorWrapper::GetPreferredCompressionType() const {
return kZSTD;
}
Compressor::ManagedWorkingArea MultiCompressorWrapper::ObtainWorkingArea() {
return compressors_.back()->ObtainWorkingArea();
}
std::unique_ptr<Compressor> MultiCompressorWrapper::MaybeCloneSpecialized(
CacheEntryRole block_type, DictSampleArgs&& dict_samples) {
return compressors_.back()->MaybeCloneSpecialized(block_type,
std::move(dict_samples));
}
Status RandomMixedCompressor::CompressBlock(
Slice uncompressed_data, std::string* compressed_output,
CompressionType* out_compression_type, ManagedWorkingArea* wa) {
auto selected =
Random::GetTLSInstance()->Uniform(static_cast<int>(compressors_.size()));
auto& compressor = compressors_[selected];
return compressor->CompressBlock(uncompressed_data, compressed_output,
out_compression_type, wa);
}
const char* RandomMixedCompressionManager::Name() const {
return wrapped_->Name();
// return "RandomMixedCompressionManager";
}
std::unique_ptr<Compressor> RandomMixedCompressionManager::GetCompressorForSST(
const FilterBuildingContext& context, const CompressionOptions& opts,
CompressionType preferred) {
assert(preferred == kZSTD);
(void)context;
return std::make_unique<RandomMixedCompressor>(opts, preferred);
}
// RoundRobinCompressor implementation
Status RoundRobinCompressor::CompressBlock(
Slice uncompressed_data, std::string* compressed_output,
CompressionType* out_compression_type, ManagedWorkingArea* wa) {
auto counter = block_counter.FetchAddRelaxed(1);
auto sel_idx = counter % (compressors_.size());
auto& compressor = compressors_[sel_idx];
return compressor->CompressBlock(uncompressed_data, compressed_output,
out_compression_type, wa);
}
RelaxedAtomic<uint64_t> RoundRobinCompressor::block_counter{0};
// RoundRobinManager implementation
const char* RoundRobinManager::Name() const {
// return "RoundRobinManager";
return wrapped_->Name();
}
std::unique_ptr<Compressor> RoundRobinManager::GetCompressorForSST(
const FilterBuildingContext& context, const CompressionOptions& opts,
CompressionType preferred) {
assert(preferred == kZSTD);
(void)context;
return std::make_unique<RoundRobinCompressor>(opts, preferred);
}
} // namespace ROCKSDB_NAMESPACE
-67
View File
@@ -1,67 +0,0 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
//
// Creates mixed compressor wrapper which uses multiple compression algorithm
// within same SST file.
#pragma once
#include <memory>
#include <mutex>
#include <vector>
#include "compression.h"
#include "rocksdb/advanced_compression.h"
namespace ROCKSDB_NAMESPACE {
class MultiCompressorWrapper : public Compressor {
public:
explicit MultiCompressorWrapper(const CompressionOptions& opts,
CompressionType type,
CompressionDict&& dict = {});
size_t GetMaxSampleSizeIfWantDict(CacheEntryRole block_type) const override;
Slice GetSerializedDict() const override;
CompressionType GetPreferredCompressionType() const override;
ManagedWorkingArea ObtainWorkingArea() override;
std::unique_ptr<Compressor> MaybeCloneSpecialized(
CacheEntryRole block_type, DictSampleArgs&& dict_samples) override;
protected:
std::vector<std::unique_ptr<Compressor>> compressors_;
};
struct RandomMixedCompressor : public MultiCompressorWrapper {
using MultiCompressorWrapper::MultiCompressorWrapper;
Status CompressBlock(Slice uncompressed_data, std::string* compressed_output,
CompressionType* out_compression_type,
ManagedWorkingArea* wa) override;
};
class RandomMixedCompressionManager : public CompressionManagerWrapper {
using CompressionManagerWrapper::CompressionManagerWrapper;
const char* Name() const override;
std::unique_ptr<Compressor> GetCompressorForSST(
const FilterBuildingContext& context, const CompressionOptions& opts,
CompressionType preferred) override;
};
struct RoundRobinCompressor : public MultiCompressorWrapper {
using MultiCompressorWrapper::MultiCompressorWrapper;
Status CompressBlock(Slice uncompressed_data, std::string* compressed_output,
CompressionType* out_compression_type,
ManagedWorkingArea* wa) override;
static RelaxedAtomic<uint64_t> block_counter;
};
class RoundRobinManager : public CompressionManagerWrapper {
using CompressionManagerWrapper::CompressionManagerWrapper;
const char* Name() const override;
std::unique_ptr<Compressor> GetCompressorForSST(
const FilterBuildingContext& context, const CompressionOptions& opts,
CompressionType preferred) override;
};
} // namespace ROCKSDB_NAMESPACE
-71
View File
@@ -177,23 +177,18 @@ class SmallEnumSetTest : public testing::Test {
TEST_F(SmallEnumSetTest, SmallEnumSetTest1) {
FileTypeSet fs; // based on a legacy enum type
ASSERT_TRUE(fs.empty());
ASSERT_EQ(fs.count(), 0U);
ASSERT_TRUE(fs.Add(FileType::kIdentityFile));
ASSERT_FALSE(fs.empty());
ASSERT_EQ(fs.count(), 1U);
ASSERT_FALSE(fs.Add(FileType::kIdentityFile));
ASSERT_TRUE(fs.Add(FileType::kInfoLogFile));
ASSERT_TRUE(fs.Contains(FileType::kIdentityFile));
ASSERT_FALSE(fs.Contains(FileType::kDBLockFile));
ASSERT_FALSE(fs.empty());
ASSERT_EQ(fs.count(), 2U);
ASSERT_FALSE(fs.Remove(FileType::kDBLockFile));
ASSERT_TRUE(fs.Remove(FileType::kIdentityFile));
ASSERT_FALSE(fs.empty());
ASSERT_EQ(fs.count(), 1U);
ASSERT_TRUE(fs.Remove(FileType::kInfoLogFile));
ASSERT_TRUE(fs.empty());
ASSERT_EQ(fs.count(), 0U);
}
namespace {
@@ -229,16 +224,12 @@ TEST_F(SmallEnumSetTest, SmallEnumSetTest2) {
ASSERT_NE(cs, MyEnumClassSet{MyEnumClass::B});
ASSERT_NE(cs, MyEnumClassSet::All());
ASSERT_EQ(MyEnumClassSet{}.count(), 0U);
ASSERT_EQ(MyEnumClassSet::All().count(), 3U);
int count = 0;
for (MyEnumClass e : cs) {
ASSERT_EQ(e, MyEnumClass::A);
++count;
}
ASSERT_EQ(count, 1);
ASSERT_EQ(cs.count(), 1U);
count = 0;
for (MyEnumClass e : MyEnumClassSet::All().Without(MyEnumClass::B)) {
@@ -253,68 +244,6 @@ TEST_F(SmallEnumSetTest, SmallEnumSetTest2) {
}
}
template <typename ENUM_TYPE, ENUM_TYPE MAX_ENUMERATOR>
void TestBiggerEnumSet() {
using MySet = SmallEnumSet<ENUM_TYPE, MAX_ENUMERATOR>;
constexpr int kMaxValue = static_cast<int>(MAX_ENUMERATOR);
SCOPED_TRACE("kMaxValue = " + std::to_string(kMaxValue));
ASSERT_EQ(sizeof(MySet), (kMaxValue + 1 + 63) / 64 * 8);
MySet s;
ASSERT_TRUE(s.empty());
ASSERT_EQ(s.count(), 0U);
ASSERT_TRUE(s.Add(ENUM_TYPE(0)));
ASSERT_FALSE(s.empty());
ASSERT_EQ(s.count(), 1U);
ASSERT_TRUE(s.Add(ENUM_TYPE(kMaxValue - 1)));
ASSERT_FALSE(s.empty());
ASSERT_EQ(s.count(), 2U);
ASSERT_TRUE(s.Add(ENUM_TYPE(kMaxValue)));
ASSERT_FALSE(s.empty());
ASSERT_EQ(s.count(), 3U);
int count = 0;
for (ENUM_TYPE e : s) {
ASSERT_TRUE(e == ENUM_TYPE(0) || e == ENUM_TYPE(kMaxValue - 1) ||
e == ENUM_TYPE(kMaxValue));
++count;
}
ASSERT_EQ(count, 3);
ASSERT_TRUE(s.Remove(ENUM_TYPE(0)));
ASSERT_TRUE(s.Remove(ENUM_TYPE(kMaxValue)));
ASSERT_FALSE(s.empty());
ASSERT_EQ(s.count(), 1U);
count = 0;
for (ENUM_TYPE e : s) {
ASSERT_EQ(e, ENUM_TYPE(kMaxValue - 1));
++count;
}
ASSERT_EQ(count, 1);
}
TEST_F(SmallEnumSetTest, BiggerEnumClasses) {
enum class BiggerEnumClass63 { A, B, C = 63 };
enum class BiggerEnumClass64 { A, B, C = 64 };
enum class BiggerEnumClass65 { A, B, C = 65 };
enum class BiggerEnumClass127 { A, B, C = 127 };
enum class BiggerEnumClass128 { A, B, C = 128 };
enum class BiggerEnumClass129 { A, B, C = 129 };
enum class BiggerEnumClass150 { A, B, C = 150 };
enum class BiggerEnumClass255 { A, B, C = 255 };
TestBiggerEnumSet<BiggerEnumClass63, BiggerEnumClass63::C>();
TestBiggerEnumSet<BiggerEnumClass64, BiggerEnumClass64::C>();
TestBiggerEnumSet<BiggerEnumClass65, BiggerEnumClass65::C>();
TestBiggerEnumSet<BiggerEnumClass127, BiggerEnumClass127::C>();
TestBiggerEnumSet<BiggerEnumClass128, BiggerEnumClass128::C>();
TestBiggerEnumSet<BiggerEnumClass129, BiggerEnumClass129::C>();
TestBiggerEnumSet<BiggerEnumClass150, BiggerEnumClass150::C>();
TestBiggerEnumSet<BiggerEnumClass255, BiggerEnumClass255::C>();
}
// ***************************************************************** //
// Unit test for Status
TEST(StatusTest, Update) {
-1
View File
@@ -340,7 +340,6 @@ Status CheckpointImpl::ExportColumnFamily(
s = db_->GetEnv()->CreateDir(tmp_export_dir);
if (s.ok()) {
// FIXME: should respect atomic_flush and flush all CFs if needed.
s = db_->Flush(ROCKSDB_NAMESPACE::FlushOptions(), handle);
}