Compare commits

..
1 Commits
Author SHA1 Message Date
anand1976 b2da0a0ad9 Update HISTORY.md for 11.6.0 release 2026-07-02 13:38:28 -07:00
370 changed files with 8311 additions and 28035 deletions

No files matched your search

+5 -11
View File
@@ -20,15 +20,9 @@ runs:
echo "GTEST_COLOR=1" >> "$GITHUB_ENV"
echo "CTEST_OUTPUT_ON_FAILURE=1" >> "$GITHUB_ENV"
echo "CTEST_TEST_TIMEOUT=300" >> "$GITHUB_ENV"
# These third-party sources are mirrored on the "third-party-deps" GitHub
# release. To add one, upload the asset here (intentionally hidden):
# https://github.com/facebook/rocksdb/releases/edit/third-party-deps
# Note how file names are generated below (vs. from the original source)
# before uploading. Removing or modifying files will break builds for
# older releases/revisions (not found or checksum mismatch).
echo "ZLIB_DOWNLOAD_PREFIX=https://github.com/facebook/rocksdb/releases/download/third-party-deps/zlib-" >> "$GITHUB_ENV"
echo "BZIP2_DOWNLOAD_PREFIX=https://github.com/facebook/rocksdb/releases/download/third-party-deps/bzip2-" >> "$GITHUB_ENV"
echo "SNAPPY_DOWNLOAD_PREFIX=https://github.com/facebook/rocksdb/releases/download/third-party-deps/snappy-" >> "$GITHUB_ENV"
echo "LZ4_DOWNLOAD_PREFIX=https://github.com/facebook/rocksdb/releases/download/third-party-deps/lz4-" >> "$GITHUB_ENV"
echo "ZSTD_DOWNLOAD_PREFIX=https://github.com/facebook/rocksdb/releases/download/third-party-deps/zstd-" >> "$GITHUB_ENV"
echo "ZLIB_DOWNLOAD_BASE=https://rocksdb-deps.s3.us-west-2.amazonaws.com/pkgs/zlib" >> "$GITHUB_ENV"
echo "BZIP2_DOWNLOAD_BASE=https://rocksdb-deps.s3.us-west-2.amazonaws.com/pkgs/bzip2" >> "$GITHUB_ENV"
echo "SNAPPY_DOWNLOAD_BASE=https://rocksdb-deps.s3.us-west-2.amazonaws.com/pkgs/snappy" >> "$GITHUB_ENV"
echo "LZ4_DOWNLOAD_BASE=https://rocksdb-deps.s3.us-west-2.amazonaws.com/pkgs/lz4" >> "$GITHUB_ENV"
echo "ZSTD_DOWNLOAD_BASE=https://rocksdb-deps.s3.us-west-2.amazonaws.com/pkgs/zstd" >> "$GITHUB_ENV"
shell: bash
+16 -33
View File
@@ -5,40 +5,23 @@
// return build({ icon, headerTitle, triggerLine, responseBody, footerLines
// });
// GitHub rejects issue comments longer than this many characters. The model
// response (responseBody) is the only unbounded input, so we trim it to fit
// while keeping the fixed scaffolding (header, trigger, footer) intact.
const MAX_COMMENT_LENGTH = 65536;
const TRUNCATION_NOTE =
'\n\n*[Truncated — full output in execution log artifact]*';
module.exports = function buildAiReviewComment(
{icon, headerTitle, triggerLine, responseBody, footerLines}) {
const assemble = (body) => [`## ${icon} ${headerTitle}`,
'',
triggerLine,
'',
'---',
'',
body,
'',
'---',
'',
'<details>',
'<summary>ℹ️ About this response</summary>',
'',
...footerLines,
'</details>',
return [
`## ${icon} ${headerTitle}`,
'',
triggerLine,
'',
'---',
'',
responseBody,
'',
'---',
'',
'<details>',
'<summary>ℹ️ About this response</summary>',
'',
...footerLines,
'</details>',
].join('\n');
const body = responseBody || '';
const comment = assemble(body);
if (comment.length <= MAX_COMMENT_LENGTH) {
return comment;
}
// Drop only as much of the body as needed to fit, then re-assemble so the
// footer/<details> block is preserved rather than cut off mid-comment.
const overflow = comment.length - MAX_COMMENT_LENGTH;
const keep = Math.max(0, body.length - overflow - TRUNCATION_NOTE.length);
return assemble(body.substring(0, keep) + TRUNCATION_NOTE);
};
+1 -1
View File
@@ -103,7 +103,7 @@ module.exports = function parseClaude({executionFile, conclusion, meta}) {
responseBody,
footerLines: [
'Generated by [Claude Code](https://github.com/anthropics/claude-code-action).',
'Review methodology: `claude_md/ci_review_prompt.md`',
'Review methodology: `claude_md/code_review.md`',
'',
'**Limitations:**',
'- Claude may miss context from files not in the diff',
+1 -1
View File
@@ -83,7 +83,7 @@ module.exports = function parseCodex(
responseBody,
footerLines: [
'Generated by Codex CLI.',
'Review methodology: `claude_md/ci_review_prompt.md`',
'Review methodology: `claude_md/code_review.md`',
'',
'**Limitations:**',
'- Codex may miss context from files not in the diff',
+10 -2
View File
@@ -714,6 +714,8 @@ jobs:
CODEX_HOME: /tmp/codex-home
CODEX_MODEL: ${{ inputs.default_model }}
CODEX_REASONING_EFFORT: ${{ steps.budget_codex.outputs.effort }}
BASE_SHA: ${{ steps.pr_info.outputs.base_sha }}
PR_TITLE: ${{ steps.pr_info.outputs.pr_title }}
run: |
if [ -z "${OPENAI_API_KEY}" ]; then
echo "OPENAI_API_KEY not configured, skipping Codex review"
@@ -721,7 +723,9 @@ jobs:
fi
mkdir -p "${CODEX_HOME}"
set +e
codex exec \
codex exec review \
--base "${BASE_SHA}" \
--title "${PR_TITLE}" \
-m "${CODEX_MODEL}" \
-c model_reasoning_effort="${CODEX_REASONING_EFFORT}" \
--dangerously-bypass-approvals-and-sandbox \
@@ -1336,6 +1340,8 @@ jobs:
CODEX_HOME: /tmp/codex-home
CODEX_MODEL: ${{ inputs.selected_model != '' && inputs.selected_model || inputs.default_model }}
CODEX_REASONING_EFFORT: ${{ steps.manual_budget_codex.outputs.effort }}
BASE_SHA: ${{ steps.pr_info.outputs.base_sha }}
PR_TITLE: ${{ steps.pr_info.outputs.pr_title }}
COMMAND_TYPE: ${{ steps.request.outputs.type }}
run: |
mkdir -p "${CODEX_HOME}"
@@ -1348,7 +1354,9 @@ jobs:
--output-last-message codex-review-output.md \
- < /tmp/prompt.txt > codex-review-execution.log 2>&1
else
codex exec \
codex exec review \
--base "${BASE_SHA}" \
--title "${PR_TITLE}" \
-m "${CODEX_MODEL}" \
-c model_reasoning_effort="${CODEX_REASONING_EFFORT}" \
--dangerously-bypass-approvals-and-sandbox \
+14 -32
View File
@@ -40,7 +40,6 @@ jobs:
name: ${{ inputs.result_artifact_name }}
run-id: ${{ github.event.workflow_run.id }}
github-token: ${{ secrets.GITHUB_TOKEN }}
path: _artifact
continue-on-error: true
- name: Post or update PR comment
@@ -53,18 +52,8 @@ jobs:
with:
script: |
const fs = require('fs');
const path = require('path');
const artifactDir = '_artifact';
const commentFile = path.join(
artifactDir,
process.env.COMMENT_FILE
);
const prNumberFile = path.join(artifactDir, 'pr_number.txt');
const triggerTypeFile = path.join(artifactDir, 'trigger_type.txt');
const headShaFile = path.join(artifactDir, 'head_sha.txt');
if (!fs.existsSync(commentFile) ||
!fs.existsSync(prNumberFile)) {
if (!fs.existsSync(process.env.COMMENT_FILE) ||
!fs.existsSync('pr_number.txt')) {
core.info('No review results found; skipping.');
return;
}
@@ -72,16 +61,16 @@ jobs:
const post = require('./.github/scripts/post-pr-comment.js');
const provider = process.env.PROVIDER;
const providerTitle = provider === 'codex' ? 'Codex' : 'Claude';
const body = fs.readFileSync(commentFile, 'utf8');
const body = fs.readFileSync(process.env.COMMENT_FILE, 'utf8');
const prNumber = parseInt(
fs.readFileSync(prNumberFile, 'utf8').trim(),
fs.readFileSync('pr_number.txt', 'utf8').trim(),
10
);
const trigger = fs.existsSync(triggerTypeFile) ?
fs.readFileSync(triggerTypeFile, 'utf8').trim() :
const trigger = fs.existsSync('trigger_type.txt') ?
fs.readFileSync('trigger_type.txt', 'utf8').trim() :
'auto';
const headSha = fs.existsSync(headShaFile) ?
fs.readFileSync(headShaFile, 'utf8').trim() :
const headSha = fs.existsSync('head_sha.txt') ?
fs.readFileSync('head_sha.txt', 'utf8').trim() :
'';
const shortSha = headSha ? headSha.substring(0, 7) : '';
const runId = process.env.RUN_ID;
@@ -130,16 +119,12 @@ jobs:
with:
script: |
const fs = require('fs');
const path = require('path');
const artifactDir = '_artifact';
const triggerTypeFile = path.join(artifactDir, 'trigger_type.txt');
const commentIdFile = path.join(artifactDir, 'comment_id.txt');
if (!fs.existsSync(triggerTypeFile)) return;
const trigger = fs.readFileSync(triggerTypeFile, 'utf8').trim();
if (!fs.existsSync('trigger_type.txt')) return;
const trigger = fs.readFileSync('trigger_type.txt', 'utf8').trim();
if (trigger !== 'manual') return;
if (!fs.existsSync(commentIdFile)) return;
if (!fs.existsSync('comment_id.txt')) return;
const commentId = parseInt(
fs.readFileSync(commentIdFile, 'utf8').trim(),
fs.readFileSync('comment_id.txt', 'utf8').trim(),
10
);
if (!commentId) return;
@@ -162,7 +147,6 @@ jobs:
name: ${{ inputs.result_artifact_name }}
run-id: ${{ github.event.workflow_run.id }}
github-token: ${{ secrets.GITHUB_TOKEN }}
path: _artifact
continue-on-error: true
- name: React with failure
@@ -171,11 +155,9 @@ jobs:
with:
script: |
const fs = require('fs');
const path = require('path');
const commentIdFile = path.join('_artifact', 'comment_id.txt');
if (!fs.existsSync(commentIdFile)) return;
if (!fs.existsSync('comment_id.txt')) return;
const commentId = parseInt(
fs.readFileSync(commentIdFile, 'utf8').trim(),
fs.readFileSync('comment_id.txt', 'utf8').trim(),
10
);
if (!commentId) return;
+3 -11
View File
@@ -25,7 +25,6 @@ jobs:
name: clang-tidy-result
run-id: ${{ github.event.workflow_run.id }}
github-token: ${{ secrets.GITHUB_TOKEN }}
path: _artifact
continue-on-error: true
- name: Post or update PR comment
@@ -34,19 +33,12 @@ jobs:
with:
script: |
const fs = require('fs');
if (!fs.existsSync('_artifact/clang-tidy-comment.md') ||
!fs.existsSync('_artifact/pr_number.txt')) {
if (!fs.existsSync('clang-tidy-comment.md') || !fs.existsSync('pr_number.txt')) {
core.info('No clang-tidy results found; skipping.');
return;
}
const body = fs.readFileSync(
'_artifact/clang-tidy-comment.md',
'utf8'
);
const prNumber = parseInt(
fs.readFileSync('_artifact/pr_number.txt', 'utf8').trim(),
10
);
const body = fs.readFileSync('clang-tidy-comment.md', 'utf8');
const prNumber = parseInt(fs.readFileSync('pr_number.txt', 'utf8').trim());
const post = require('./.github/scripts/post-pr-comment.js');
await post({
@@ -22,3 +22,4 @@ jobs:
provider: claude
result_artifact_name: claude-review-result
comment_file: claude-review-comment.md
secrets: inherit
@@ -22,3 +22,4 @@ jobs:
provider: codex
result_artifact_name: codex-review-result
comment_file: codex-review-comment.md
secrets: inherit
+8 -3
View File
@@ -7,9 +7,14 @@
name: Codex Code Review
on:
# Automatic PR reviews are temporarily disabled while Codex authentication is
# repaired. Manual review requests remain available through issue comments
# and workflow_dispatch.
workflow_run:
workflows: ["facebook/rocksdb/pr-jobs"]
types: [completed]
# The early pull_request_target path is limited to same-repo PRs by the job
# condition below. Fork PRs skip this path and rely on workflow_run instead.
pull_request_target:
types: [opened, reopened, synchronize]
issue_comment:
types: [created]
+1 -11
View File
@@ -140,17 +140,7 @@ jobs:
- uses: "./.github/actions/pre-steps"
- run: sudo apt-get update && sudo apt-get install -y build-essential libgflags-dev libsnappy-dev zlib1g-dev libbz2-dev liblz4-dev libzstd-dev
- run: sudo mount -o remount,size=16G /dev/shm
- name: Ensure swap space
run: |-
if sudo swapon --show=NAME --noheadings --raw | grep -Fxq /swapfile; then
echo "/swapfile is already active"
else
sudo dd bs=1048576 count=4096 if=/dev/zero of=/swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
fi
sudo swapon --show
- run: sudo dd bs=1048576 count=4096 if=/dev/zero of=/swapfile && sudo chmod 600 /swapfile && sudo mkswap /swapfile && sudo swapon /swapfile
- run: ulimit -S -n `ulimit -H -n` && make V=1 -j8 CRASH_TEST_EXT_ARGS='--duration=1800 --max_key=2500000' blackbox_crash_test_with_atomic_flush
- run: rm -rf /dev/shm/rocksdb.*
- run: ulimit -S -n `ulimit -H -n` && make V=1 -j8 CRASH_TEST_EXT_ARGS='--duration=1800 --max_key=2500000' blackbox_crash_test_with_multiops_wc_txn
+4 -43
View File
@@ -65,9 +65,7 @@ jobs:
pip install https://files.pythonhosted.org/packages/fb/ac/3c04772acc0257f5730e83adb542b2603c1a62d1315010ab593a980af404/clang_format-21.1.2-py2.py3-none-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
clang-format --version
- name: Download clang-format-diff.py
# Mirrored on the "third-party-deps" GitHub release; add/update via
# https://github.com/facebook/rocksdb/releases/edit/third-party-deps
run: wget --tries=3 --retry-on-host-error https://github.com/facebook/rocksdb/releases/download/third-party-deps/clang-format-diff.py
run: wget https://rocksdb-deps.s3.us-west-2.amazonaws.com/llvm/llvm-project/release/12.x/clang/tools/clang-format/clang-format-diff.py
- name: Check format
run: VERBOSE_CHECK=1 make check-format
- name: Compare buckify output
@@ -322,46 +320,16 @@ jobs:
# Run the make target in STRICT mode so this core CI job HARD-FAILS rather
# than silently skipping if a prerequisite (clang++, clang-format, or the
# compat baseline ref) is ever missing. See `make check-c-api-gen`.
env:
PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
PUSH_BEFORE_SHA: ${{ github.event.before }}
run: |
# The container checkout is owned by a different user, so git refuses to
# operate on it ("dubious ownership") -- mark it safe for the `git fetch`
# and the `git show` the compat checker runs.
git config --global --add safe.directory "$GITHUB_WORKSPACE"
git config --global --add safe.directory '*'
# A PR must preserve the API of its merge target, while a push must
# preserve the API of the branch before the push. Comparing every event
# with main produces false removals when a release branch predates APIs
# added to main.
case "$GITHUB_EVENT_NAME" in
pull_request) api_compat_ref="$PR_BASE_SHA" ;;
push) api_compat_ref="$PUSH_BEFORE_SHA" ;;
*)
echo "ERROR: unsupported event for C API compatibility: $GITHUB_EVENT_NAME" >&2
exit 1
;;
esac
if [ -z "$api_compat_ref" ]; then
echo "ERROR: C API compatibility baseline is empty" >&2
exit 1
fi
zero_sha=0000000000000000000000000000000000000000
if [ "$api_compat_ref" = "$zero_sha" ]; then
# A newly created branch or tag has no prior ref state to preserve.
api_compat_ref=HEAD
else
git fetch --no-tags --depth=1 origin "$api_compat_ref"
api_compat_ref=FETCH_HEAD
fi
git fetch --no-tags --depth=1 origin main
CXX=clang++-21 make check-c-api-gen \
CHECK_C_API_GEN_STRICT=1 \
API_COMPAT_REF="$api_compat_ref" \
API_COMPAT_REF=FETCH_HEAD \
CLANG_FORMAT_BINARY=clang-format-21
- uses: "./.github/actions/teardown-ccache"
if: always()
@@ -426,20 +394,13 @@ jobs:
steps:
- uses: actions/checkout@v4.1.0
- uses: "./.github/actions/pre-steps"
- uses: "./.github/actions/cache-getdeps-downloads"
- uses: "./.github/actions/setup-folly"
- uses: "./.github/actions/setup-ccache"
with:
cache-key-prefix: mini-crashtest
- uses: "./.github/actions/cache-folly"
id: cache-folly
- uses: "./.github/actions/build-folly"
with:
cache-hit: ${{ steps.cache-folly.outputs.cache-hit }}
- run: |
ulimit -S -n $(ulimit -Hn) # Raise open files soft limit to hard limit
echo "Updated ulimit -Hn: $(ulimit -Hn) -Sn: $(ulimit -Sn)"
USE_COROUTINES=1 USE_FOLLY=1 LIB_MODE=static make V=1 -j8 CRASH_TEST_EXT_ARGS='--duration=${{ matrix.crash_duration }} --max_key=2500000' ${{ matrix.crash_test_target }}
make V=1 -j8 CRASH_TEST_EXT_ARGS='--duration=${{ matrix.crash_duration }} --max_key=2500000' ${{ matrix.crash_test_target }}
- uses: "./.github/actions/teardown-ccache"
if: always()
- uses: "./.github/actions/post-steps"
+1 -27
View File
@@ -59,7 +59,6 @@ cpp_library_wrapper(name="rocksdb_lib", srcs=[
"db/compaction/sst_partitioner.cc",
"db/compaction/subcompaction_state.cc",
"db/convenience.cc",
"db/coro_db.cc",
"db/db_filesnapshot.cc",
"db/db_impl/compacted_db_impl.cc",
"db/db_impl/db_impl.cc",
@@ -104,6 +103,7 @@ cpp_library_wrapper(name="rocksdb_lib", srcs=[
"db/snapshot_impl.cc",
"db/table_cache.cc",
"db/table_properties_collector.cc",
"db/transaction_log_impl.cc",
"db/trim_history_scheduler.cc",
"db/version_builder.cc",
"db/version_edit.cc",
@@ -111,9 +111,7 @@ cpp_library_wrapper(name="rocksdb_lib", srcs=[
"db/version_set.cc",
"db/version_util.cc",
"db/wal_edit.cc",
"db/wal_iterator_impl.cc",
"db/wal_manager.cc",
"db/wide/lazy_wide_columns.cc",
"db/wide/read_path_blob_resolver.cc",
"db/wide/wide_column_serialization.cc",
"db/wide/wide_columns.cc",
@@ -270,7 +268,6 @@ cpp_library_wrapper(name="rocksdb_lib", srcs=[
"util/compression.cc",
"util/compression_context_cache.cc",
"util/concurrent_task_limiter_impl.cc",
"util/coro_stats_util.cc",
"util/crc32c.cc",
"util/crc32c_arm64.cc",
"util/data_structure.cc",
@@ -309,7 +306,6 @@ cpp_library_wrapper(name="rocksdb_lib", srcs=[
"utilities/compaction_filters.cc",
"utilities/compaction_filters/remove_emptyvalue_compactionfilter.cc",
"utilities/convenience/info_log_finder.cc",
"utilities/copy_engine/copy_engine.cc",
"utilities/counted_fs.cc",
"utilities/debug.cc",
"utilities/env_mirror.cc",
@@ -383,21 +379,11 @@ cpp_library_wrapper(name="rocksdb_lib", srcs=[
"utilities/write_batch_with_index/write_batch_with_index_internal.cc",
], deps=[
"//folly/container:f14_hash",
"//folly/coro:baton",
"//folly/coro:blocking_wait",
"//folly/coro:collect",
"//folly/coro:coroutine",
"//folly/coro:nothrow",
"//folly/coro:task",
"//folly/executors/thread_factory:named_thread_factory",
"//folly/executors:io_executor",
"//folly/executors:io_thread_pool_executor",
"//folly/io/async:async_base",
"//folly/io/async:event_base_manager",
"//folly/io/async:io_uring_backend",
"//folly/io/async:request_context",
"//folly/synchronization:distributed_mutex",
"//folly:executor",
], headers=glob(["**/*.h"]), link_whole=False, extra_test_libs=False)
cpp_library_wrapper(name="rocksdb_whole_archive_lib", srcs=[], deps=[":rocksdb_lib"], headers=[], link_whole=True, extra_test_libs=False)
@@ -4757,12 +4743,6 @@ cpp_unittest_wrapper(name="configurable_test",
extra_compiler_flags=[])
cpp_unittest_wrapper(name="copy_engine_test",
srcs=["utilities/copy_engine/copy_engine_test.cc"],
deps=[":rocksdb_test_lib"],
extra_compiler_flags=[])
cpp_unittest_wrapper(name="corruption_test",
srcs=["db/corruption_test.cc"],
deps=[":rocksdb_test_lib"],
@@ -4949,12 +4929,6 @@ cpp_unittest_wrapper(name="db_kv_checksum_test",
extra_compiler_flags=[])
cpp_unittest_wrapper(name="db_lazy_entity_test",
srcs=["db/wide/db_lazy_entity_test.cc"],
deps=[":rocksdb_test_lib"],
extra_compiler_flags=[])
cpp_unittest_wrapper(name="db_log_iter_test",
srcs=["db/db_log_iter_test.cc"],
deps=[":rocksdb_test_lib"],
+2 -28
View File
@@ -8,7 +8,7 @@ This document provides guidance for generating and reviewing code in the RocksDB
### Code Quality and Maintainability
**Clarity and Readability:** Write clear, self-documenting code. Use meaningful variable names, add comments for complex logic, and structure code to minimize cognitive load. Avoid clever tricks that sacrifice readability for marginal performance gains unless absolutely necessary. Avoid static_cast, reinterpret_cast, and C-style casts; static_cast_with_check, up_cast, and lossless_cast from cast_util.h are preferred.
**Clarity and Readability:** Write clear, self-documenting code. Use meaningful variable names, add comments for complex logic, and structure code to minimize cognitive load. Avoid clever tricks that sacrifice readability for marginal performance gains unless absolutely necessary.
**Consistent Style:** Follow existing code style conventions. RocksDB uses `.clang-format` for formatting, specific naming conventions, and structural patterns. Deviations from these patterns are frequently flagged in reviews.
@@ -55,7 +55,7 @@ This document provides guidance for generating and reviewing code in the RocksDB
**API Consistency:** New APIs should be consistent with existing patterns. Use similar naming conventions, parameter ordering, and return types. Reviewers will suggest changes to improve consistency with the broader codebase.
**Documentation:** Public APIs must be thoroughly documented, without unnecessary embelishment nor dwelling on implementation details nor project planning. When non-obvious, include usage examples, parameter descriptions, known bugs or limitations, notes on thread safety, performance characteristics, and compatibility considerations. Re-read comments for ambiguous terminology and phrasing, such as ambiguously re-purposed programming jargon.
**Documentation:** Public APIs must be thoroughly documented. Include usage examples, parameter descriptions, and notes on thread safety, performance characteristics, and compatibility considerations.
---
@@ -243,11 +243,6 @@ from an implementation detail instead of an explicit option.
* Don't manually edit BUCK file, after updating src.mk, run
/usr/local/bin/python3 buckifier/buckify_rocksdb.py to update it
* For -j in make command, use the number of CPU cores to decide it.
* When searching for references to something (a symbol, library, etc.), do not
restrict or truncate your search based on presumed relevance or scope. It is
important and time-saving to keep the repo reasonably consistent across
different build systems, programming languages, and even between
documentation and implementation.
### Avoiding mixed build modes with Make (use `AUTO_CLEAN=1`)
@@ -259,10 +254,6 @@ will automatically clean object files if the build parameters/flavor have
changed. The `build_tools/rockstest.sh` / `rocksptest.sh` helpers described
below set `AUTO_CLEAN=1` for you.
`AUTO_CLEAN=1` does not fix Make failures associated with stale .d files
referring to removed files. Resolve that manually or with `make clean`
without complaining to the user.
### Source checks
* Run `make check-sources` before committing. This catches non-ASCII
characters in source files and other source-level issues that CI will
@@ -302,7 +293,6 @@ build (and where noted, run tests) across:
| Axis | Must support |
|------|--------------|
| OS | Linux (x86_64 + ARM), macOS, Windows |
| Architecture | Little-endian and big-endian targets, including Linux on s390x |
| Compiler | GCC, Clang (libstdc++ **and** libc++), AppleClang, **MSVC (VS2022)**, MinGW (Linux cross-compile, build-only, no gflags) |
| Build system | Make, CMake, and BUCK (internal) -- keep all in sync (see "Build system" above) |
| Config | release (`-fno-rtti`), `ASSERT_STATUS_CHECKED`, ASAN/UBSAN/TSAN, folly, unity build, JNI/Java |
@@ -317,12 +307,6 @@ abstractions; otherwise guard with `#ifdef OS_WIN` (POSIX `<unistd.h>` ->
Windows `<process.h>`). Because libc++ is also tested, include what you use
rather than relying on libstdc++ transitive includes.
Do not use `static_assert` to reject a supported architecture for an optional
feature. Check an existing `port::` capability such as `port::kLittleEndian`
and disable only the unsupported feature so the rest of RocksDB still builds.
Use a portable representation when the feature itself must work across
architectures.
### Unit Test
* After all of the unit tests are added, review them and try to extract common
reusable utility functions to reduce code duplication due to copy past between
@@ -350,9 +334,6 @@ architectures.
* For CI-style flaky tests that do not reproduce with `gtest_parallel.py`,
`--gtest_repeat`, or normal coerce-mode runs, inspect
`tools/gtest_parallel_repro.py --help`.
* Each unit test file has overheads, so avoid creating new unit test files
for random minor features. Consider adding to slice_test, db_etc3_test, or
others.
### Unit test dedup guidelines
* Extract helper functions for repeated patterns such as object
@@ -400,13 +381,6 @@ architectures.
### Adding release note
* Release note should be kept short at high level for external user consumption.
Release notes identify what users might care about most in a release. They
are not exhaustive and are not a guide. PLEASE learn from past agents who
ried to build elaborate release notes with implementation details and
elsewhere-documented nuance. That wastes time. Fight the bias that
"my change" is important so must be worthy of release note mention.
* If more than single markdown line, consider how their formatting will be
integrated into HISTORY.md.
### Blog posts (docs/_posts)
* Blog post authors must be defined in `docs/_data/authors.yml` to be displayed
+4 -33
View File
@@ -698,19 +698,10 @@ if(USE_FOLLY)
include(${FOLLY_INST_PATH}/lib/cmake/folly/folly-config.cmake)
# Fix gflags library name for debug builds. The getdeps gflags shared
# library is versioned (e.g. libgflags_debug.so.2.3), so resolve the
# actual file by glob rather than hard-coding a version.
# Fix gflags library name for debug builds
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
file(GLOB GFLAGS_DEBUG_SHARED_LIBS
"${GFLAGS_INST_PATH}/lib/libgflags_debug.so.*")
if(NOT GFLAGS_DEBUG_SHARED_LIBS)
message(FATAL_ERROR
"Could not find getdeps libgflags_debug.so under ${GFLAGS_INST_PATH}/lib")
endif()
list(GET GFLAGS_DEBUG_SHARED_LIBS 0 GFLAGS_DEBUG_SHARED_LIB)
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-rpath=${GFLAGS_INST_PATH}/lib")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${GFLAGS_DEBUG_SHARED_LIB}")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${GFLAGS_INST_PATH}/lib/libgflags_debug.so.2.2")
endif()
endif()
@@ -801,7 +792,6 @@ set(SOURCES
db/compaction/sst_partitioner.cc
db/compaction/subcompaction_state.cc
db/convenience.cc
db/coro_db.cc
db/db_filesnapshot.cc
db/db_impl/compacted_db_impl.cc
db/db_impl/db_impl.cc
@@ -846,6 +836,7 @@ set(SOURCES
db/snapshot_impl.cc
db/table_cache.cc
db/table_properties_collector.cc
db/transaction_log_impl.cc
db/trim_history_scheduler.cc
db/version_builder.cc
db/version_edit.cc
@@ -853,9 +844,7 @@ set(SOURCES
db/version_set.cc
db/version_util.cc
db/wal_edit.cc
db/wal_iterator_impl.cc
db/wal_manager.cc
db/wide/lazy_wide_columns.cc
db/wide/read_path_blob_resolver.cc
db/wide/wide_column_serialization.cc
db/wide/wide_columns.cc
@@ -1004,7 +993,6 @@ set(SOURCES
util/simple_mixed_compressor.cc
util/compression_context_cache.cc
util/concurrent_task_limiter_impl.cc
util/coro_stats_util.cc
util/crc32c.cc
util/data_structure.cc
util/dynamic_bloom.cc
@@ -1026,7 +1014,6 @@ set(SOURCES
util/xxhash.cc
utilities/agg_merge/agg_merge.cc
utilities/backup/backup_engine.cc
utilities/copy_engine/copy_engine.cc
utilities/blob_db/blob_compaction_filter.cc
utilities/blob_db/blob_db.cc
utilities/blob_db/blob_db_impl.cc
@@ -1562,7 +1549,6 @@ if(WITH_TESTS)
db/version_set_test.cc
db/wal_manager_test.cc
db/wal_edit_test.cc
db/wide/db_lazy_entity_test.cc
db/wide/db_wide_basic_test.cc
db/wide/db_wide_blob_direct_write_test.cc
db/wide/wide_column_serialization_test.cc
@@ -1645,7 +1631,6 @@ if(WITH_TESTS)
utilities/cassandra/cassandra_row_merge_test.cc
utilities/cassandra/cassandra_serialize_test.cc
utilities/checkpoint/checkpoint_test.cc
utilities/copy_engine/copy_engine_test.cc
utilities/sorted_run_builder/sorted_run_builder_test.cc
utilities/env_timed_test.cc
utilities/fault_injection_fs_test.cc
@@ -1713,21 +1698,7 @@ if(WITH_TESTS)
)
target_link_libraries(${exename}${ARTIFACT_SUFFIX} testutillib${ARTIFACT_SUFFIX} testharness gtest ${THIRDPARTY_LIBS} ${ROCKSDB_LIB})
if(NOT "${exename}" MATCHES "db_sanity_test")
if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.18)
# Discover tests at ctest time instead of during the parallel build.
# POST_BUILD discovery (the default) runs each freshly-built test
# binary while the -j build is still compiling; on resource-constrained
# CI (notably the arm64 macOS runners) that discovery run can yield
# empty output, and CMake's JSON parser then aborts the whole build
# with "Syntax error: value, object or array expected". PRE_TEST moves
# discovery out of the build phase so a slow/empty enumeration no
# longer fails the build.
gtest_discover_tests(${exename}
DISCOVERY_TIMEOUT 120
DISCOVERY_MODE PRE_TEST)
else()
gtest_discover_tests(${exename} DISCOVERY_TIMEOUT 120)
endif()
gtest_discover_tests(${exename} DISCOVERY_TIMEOUT 120)
add_dependencies(rocksdb_check ${exename}${ARTIFACT_SUFFIX})
endif()
endforeach(sourcefile ${TESTS})
-53
View File
@@ -1,59 +1,6 @@
# Rocksdb Change Log
> NOTE: Entries for next release do not go here. Follow instructions in `unreleased_history/README.txt`
## 11.9.1 (08/18/2026)
### Public API Changes
* Added an immutable `external_table_config` option that is persisted in OPTIONS files and passed to external table factories during bootstrap.
## 11.9.0 (08/14/2026)
### New Features
* Added an integrated and improved compression auto-skip feature (new CompressionOptions, still experimental) that saves CPU by skipping compression when and where the overall ratio is inadequate. This improves on the previous auto-skip compression manager by (a) taking achieved compression ratios into account, (b) using a continuously evolving payoff estimate, and (c) combining natively with parallel compression.
* Added the `blob_file_writable_file_max_buffer_size` mutable column family option. When set to a non-zero value, blob-file writers use it as their `WritableFileWriter` max buffer size instead of inheriting `DBOptions::writable_file_max_buffer_size`.
* Added an experimental lazy wide-column read API, `DB::GetEntityLazy()` / `DB::MultiGetEntityLazy()` (see `include/rocksdb/lazy_wide_columns.h`). The returned `LazyWideColumns` leaves blob-backed columns as unresolved references and, like an iterator, stays valid after the call returns, so the caller resolves only the columns -- and only the byte ranges -- it needs; a byte-range read of an uncompressed blob (separate-file or embedded) reads just those bytes from storage. Adds `Env::IOActivity::kLazyResolve` and `rocksdb.blobdb.lazy.*` statistics. Requires `max_open_files == -1`.
* Added DB property `rocksdb.num-running-remote-compactions`, reporting the number of compaction service jobs currently waiting in `CompactionService::Wait()`.
* Added DB property `rocksdb.num-unscheduled-compactions`, reporting compactions waiting in the DB's internal compaction queue but not yet assigned to a background job.
* Added `DB::AbortCompactions()` and `DB::ResumeCompactions()` for per-column-family compaction abort and resume, with the same active-abort semantics as the DB-wide `AbortAllCompactions()`/`ResumeAllCompactions()` but scoped to a single column family. Calls are reference-counted independently per column family and compose with the DB-wide abort.
### Public API Changes
* Add IndexFactory compatibility names for the existing user-defined index API.
* Added the experimental `CoroDB` capability, exposed by `DB::GetCoroDB()`, with lazy native coroutine variants of `Get` and `MultiGet`. The existing `DB::GetAsync()` and `DB::MultiGetAsync()` APIs dispatch through it.
* Added `rocksdb_batched_multi_get_pinned_cf()` to return batch-owned pinned MultiGet values and per-key errors without allocating one wrapper per found value.
* Add `DBOptions::read_io_executor_threads` to increase the maximum thread count of the shared filesystem read I/O executor used for asynchronous reads when opening a DB. Opening a DB never reduces the shared executor thread count. Change the experimental `FSRandomAccessFile::SubmitReadAsync()` API to return whether the asynchronous path was used, and add the `FILE_SUBMIT_ASYNC_READ_FALLBACK` ticker to count calls that fall back to synchronous reads.
* `ReadOptions::table_filter` is now a *pointer* to a caller-owned `std::function` instead of a `std::function` value, to improve efficiency in copying and destroying `ReadOptions` objects (which RocksDB does internally). This is a breaking change for users of this relatively obscure option, who will now need to declare a `std::function` that outlives the read. As a side effect of `ReadOptions` being trivially copyable, new but legitimate compiler warnings may surface.
* Removed the experimental `CreateAutoSkipCompressionManager()`. Auto-skip compression is now a first-class feature of the block-based table builder, controlled by the new experimental `CompressionOptions::auto_skip`.
* Added `CoroStackableDB` for implementing wrappers over native coroutine reads and used it to add coroutine `Get` and `MultiGet` support to `DBWithTTL` and WritePrepared `TransactionDB`. A stackable wrapper advertises coroutine support only when its wrapped DB supports it; TTL value decoding and transaction visibility semantics are preserved.
* Added a `kSstFileWriter` value to `TableFileCreationReason`, which `SstFileWriter` now reports instead of the catch-all `kMisc`. This, along with new `db_name` and `is_remote_compaction` fields in `FilterBuildingContext`, improves the contextual information available to custom filter and compression strategies.
* Renamed `TransactionLogIterator` to `WalIterator` (and `include/rocksdb/transaction_log.h` to `include/rocksdb/wal_iterator.h`), because it iterates the write-ahead log and is unrelated to `TransactionDB`. The old names still work. `DB::GetUpdatesSince()` is unchanged. In Java, `WalIterator` is the new name and `TransactionLogIterator` remains as a subclass. Also documented existing behavior that was previously unstated: only writes that reached the WAL are visible (so `WriteOptions::disableWAL` and `IngestExternalFile()` leave holes that end iteration), what each iterator state means, and that `GetUpdatesSince()` silently starts later when the requested sequence number is unavailable.
### Bug Fixes
* Fixed a bug where `BlobFileBuilder` passed an SST path to `OnBlobFileCompleted()` instead of the completed blob path during BlobDB garbage-collection compactions, causing incorrect `SstFileManager` accounting and compaction failures on filesystems where the SST was not yet pathname-visible.
### Performance Improvements
* When `DBOptions::avoid_unnecessary_blocking_io` is true, obsolete `OPTIONS-*` files found during DB open are deleted by background purge instead of synchronously on the opening thread.
## 11.8.0 (07/28/2026)
### Public API Changes
* Add callback-based asynchronous read APIs, `DB::GetAsync()` and `DB::MultiGetAsync()`. The idea is that when IO is required, RocksDB can suspend its internal coroutine read path, allowing the read executor thread to do other work. When the IO is complete, RocksDB invokes the user callback. This requires filesystem support for full performance benefits. A new filesystem API `FSRandomAccessFile::SubmitReadAsync()` is introduced for this. Unlike `ReadAsync`, the filesystem is responsible for eventually calling the callback. `FileSystem::GetReadExecutor()` returns the IO executor whose EventBases run coroutine read processing. In the Posix filesystem, an IO-uring based event loop is used to complete the IO.
* Added `FlushOptions::listener_wait` (default `false`). When set together with `FlushOptions::wait == true`, `DB::Flush()` will not return until the registered `EventListener::OnFlushCompleted` callbacks for the flushed memtables have finished running. By default (`false`), `Flush(wait=true)` may return as soon as the flush result is committed, which can be before (or while) the `OnFlushCompleted` callbacks execute on the background flush thread. Also added the corresponding C API `rocksdb_flushoptions_set_listener_wait()` / `rocksdb_flushoptions_get_listener_wait()`.
* Deprecated `PinnableWideColumns::serialized_size()` in favor of the new `PinnableWideColumns::payload_size()`, which returns the total size of the columns' names and values (for a plain value this equals the value size). Relatedly, wide-column read accounting changed subtly: read statistics for entities (`BYTES_READ`, `BYTES_PER_READ`, and the per-key byte counts for `GetEntity`/`MultiGetEntity`) and the `ReadOptions::value_size_soft_limit` threshold now measure entities by this payload size instead of the serialized entity size. This drops serialization framing bytes from those measurements (so reported/limited sizes for entity reads are slightly smaller than before) and makes plain-value and wide-column accounting consistent.
### Behavior Changes
* `ReadOptions::value_size_soft_limit` now also bounds the blob values resolved from pre-flush blob direct write references during `MultiGet`/`MultiGetEntity` (previously these were resolved after the limit check and read without bound). Enforcement is "always make progress": at least one key is read even if its value alone exceeds the limit, and only once the returned size exceeds the limit do subsequent keys get `Status::Aborted` -- so a caller retrying the aborted keys cannot loop forever on a single value that by itself exceeds the limit.
### Performance Improvements
* Reduced copying when reading wide-column entities that have blob-referenced columns, whether stored in separate blob files or embedded (same-file) as blob records in the same SST. On the point-lookup (`GetEntity`/`MultiGetEntity`) and blob-backed memtable/direct-write read paths, resolving these columns no longer re-serializes the whole entity into a fresh buffer: inline columns are referenced in place in the pinned entity and each resolved blob value is referenced in place from its fetched buffer. This is enabled by an internal change to `PinnableWideColumns` that lets its columns reference multiple backing buffers.
## 11.7.0 (07/16/2026)
### Public API Changes
* Added `RangeLockManagerHandle::SetIsKilledCallback()`, a `std::function<bool()>` predicate polled during range-lock waits. When it returns true, a blocked `GetRangeLock()` wait returns promptly with `Status::Aborted()` instead of waiting for the lock timeout. Range-lock users that install no callback keep the original wait-until-grant-or-timeout behavior.
* Added `MultiScanArgs::reverse` to support reverse MultiScan reads over bounded scan ranges.
### Behavior Changes
* When using `LockWAL()`, live-file capture APIs such as checkpoint and backup now flush WAL-disabled unpersisted data; they can block until `UnlockWAL()` or return `Aborted` when called from the same thread that holds `LockWAL()` to avoid deadlock. `UnlockWAL()` must now also be called from the same thread that called `LockWAL()`.
### Performance Improvements
* Fixed slow DB open with `best_efforts_recovery`, and slow catch-up of secondary and follower (read-only) instances, in which time and memory grew quadratically with the number of files in the DB (so the slowdown was worst for large DBs with long history).
## 11.6.0 (07/02/2026)
### New Features
* Added EXPERIMENTAL embedded blob SST support through `SstFileWriter::OpenWithEmbeddedBlobs()`, storing eligible large values as same-file blob records in block-based SST files and resolving them transparently for reads. This niche feature currently supports uncompressed embedded blobs only; compression options are placeholders and compression support is deferred to follow-up work.
+48 -135
View File
@@ -86,20 +86,11 @@ else
LIB_MODE?=shared
endif
# Set by the gen_check_scripts wrappers to mark a recursive make reusing the
# parent's make_config.mk: silence the parse-time banners and skip
# build_detect_platform (below).
$(if $(ROCKSDB_RECURSIVE_MAKE_SAME_CONFIG),,$(info $$DEBUG_LEVEL is $(DEBUG_LEVEL), $$LIB_MODE is $(LIB_MODE)))
$(info $$DEBUG_LEVEL is $(DEBUG_LEVEL), $$LIB_MODE is $(LIB_MODE))
# Detect what platform we're building on.
# Export some common variables that might have been passed as Make variables
# instead of environment variables.
#
# Skipped by the gen_check_scripts wrappers (which run concurrently under
# gnu_parallel): each would otherwise rewrite the shared make_config.mk
# non-atomically and a concurrent reader could catch it mid-write ("missing
# separator"). Requires an existing make_config.mk, so a normal build still detects.
ifeq ($(and $(ROCKSDB_RECURSIVE_MAKE_SAME_CONFIG),$(wildcard make_config.mk)),)
dummy := $(shell (export ROCKSDB_ROOT="$(CURDIR)"; \
export CXXFLAGS="$(EXTRA_CXXFLAGS)"; \
export LDFLAGS="$(EXTRA_LDFLAGS)"; \
@@ -113,9 +104,8 @@ dummy := $(shell (export ROCKSDB_ROOT="$(CURDIR)"; \
export ROCKSDB_CXX_STANDARD="$(ROCKSDB_CXX_STANDARD)"; \
export USE_FOLLY="$(USE_FOLLY)"; \
export USE_FOLLY_LITE="$(USE_FOLLY_LITE)"; \
"$(CURDIR)/build_tools/build_detect_platform" "$(CURDIR)/make_config.mk" $(if $(ROCKSDB_RECURSIVE_MAKE_SAME_CONFIG),2>/dev/null)))
endif
# this file (generated above, or reused when skipped) sets build flags and sources
"$(CURDIR)/build_tools/build_detect_platform" "$(CURDIR)/make_config.mk"))
# this file is generated by the previous line to set build flags and sources
include make_config.mk
# Figure out optimize level.
@@ -191,7 +181,7 @@ ifeq ($(filter -DROCKSDB_ASSERT_STATUS_CHECKED,$(OPT)),)
endif
endif
$(if $(ROCKSDB_RECURSIVE_MAKE_SAME_CONFIG),,$(warning Warning: Compiling in debug mode. Don't use the resulting binary in production))
$(warning Warning: Compiling in debug mode. Don't use the resulting binary in production)
endif
# `USE_LTO=1` enables link-time optimizations. Among other things, this enables
@@ -589,12 +579,9 @@ TESTS += $(PLUGIN_TESTS)
ifneq ($(filter check-headers, $(MAKECMDGOALS)),)
# TODO: add/support JNI headers
DEV_HEADER_DIRS := $(sort include/ $(dir $(ALL_SOURCES)))
FOLLY_DEPENDENT_HEADERS := \
include/rocksdb/coro_db.h \
include/rocksdb/utilities/coro_stackable_db.h
# Some headers like in port/ are platform-specific
DEV_HEADERS_TO_CHECK := $(filter-out $(FOLLY_DEPENDENT_HEADERS), $(shell $(FIND) $(DEV_HEADER_DIRS) -type f -name '*.h' | grep -E -v 'port/|plugin/|range_tree/|secondary_index/'))
PUBLIC_HEADERS_TO_CHECK := $(filter-out $(FOLLY_DEPENDENT_HEADERS), $(shell $(FIND) include/ -type f -name '*.h'))
DEV_HEADERS_TO_CHECK := $(shell $(FIND) $(DEV_HEADER_DIRS) -type f -name '*.h' | grep -E -v 'port/|plugin/|range_tree/|secondary_index/')
PUBLIC_HEADERS_TO_CHECK := $(shell $(FIND) include/ -type f -name '*.h')
else
DEV_HEADERS_TO_CHECK :=
PUBLIC_HEADERS_TO_CHECK :=
@@ -962,57 +949,6 @@ gen_parallel_tests:
$(AM_V_at)$(FIND) t -type f -name 'run-*' -exec rm -f {} \;
$(MAKE) $(parallel_tests)
# Auxiliary (non-unit-test) checks that are part of `make check`. Kept as a
# single list so the same set can run as parallel jobs alongside the C++ unit
# tests (see gen_check_scripts + check_0) and serially in the J=1 fallback.
CHECK_EXTRA_TARGETS =
ifneq ($(PLATFORM), OS_AIX)
CHECK_EXTRA_TARGETS += check-all-python
ifndef ASSERT_STATUS_CHECKED # not yet working with these tests
CHECK_EXTRA_TARGETS += ldb_tests db_crashtest_tests rocksdb_dump_test
endif
endif
ifndef SKIP_FORMAT_BUCK_CHECKS
CHECK_EXTRA_TARGETS += check-format check-buck-targets check-sources check-workflow-yaml check-c-api-gen
endif
# Generate a t/run-<target> wrapper per enabled auxiliary check; check_0's
# `$(FIND) t -name 'run-*'` then runs them as gnu_parallel jobs alongside the
# unit tests, each framed with a gtest-style pass/fail line. Under CI sharding,
# round-robin across shards so each check runs on exactly one shard. Kept
# separate from gen_parallel_tests (which cleans t/run-* first) so the valgrind_*
# targets, which also glob t/run-*, don't pick these up.
.PHONY: gen_check_scripts
gen_check_scripts:
$(AM_V_at)mkdir -p t; \
idx=0; \
for tgt in $(CHECK_EXTRA_TARGETS); do \
if [ -z "$(CI_TOTAL_SHARDS)" ] || [ $$(( idx % $(CI_TOTAL_SHARDS) )) -eq $(CI_SHARD_INDEX) ]; then \
s=t/run-$$tgt; \
printf '%s\n' \
'#!/bin/sh' \
'# Generated by `make gen_check_scripts`.' \
"t=$$tgt" \
'# Drop the parent jobserver from MAKEFLAGS (its fds are lost through' \
'# gnu_parallel, causing a spurious warning); keep overrides after "--".' \
'MAKEFLAGS=$$(printf "%s" "$$MAKEFLAGS" | sed -e "s/ --jobserver-auth=[^ ]*//g" -e "s/ --jobserver-fds=[^ ]*//g" -e "s/ -j[0-9]*//g")' \
'export MAKEFLAGS' \
'echo; echo "[----------]"; echo "[ RUN ] >>> make $$t <<<"' \
'$(MAKE) --no-print-directory ROCKSDB_RECURSIVE_MAKE_SAME_CONFIG=1 "$$t"' \
'rc=$$?' \
'if [ "$$rc" = 0 ]; then' \
' echo "[ OK ] >>> make $$t <<<"' \
'else' \
' echo "[ FAILED ] >>> make $$t <<<"' \
'fi' \
'echo "[----------]"' \
'exit $$rc' \
> $$s; \
chmod a=rx $$s; \
fi; \
idx=$$((idx + 1)); \
done
# Reorder input lines (one per test or per shard) so the longest-running
# tests/shards start first under "make check" parallel scheduling. The trick
# is to prefix matched names with a fake duration (100), sort numerically
@@ -1040,8 +976,7 @@ gen_check_scripts:
slow_test_regexp = \
^.*point_lock_manager_stress_test.*$$|^.*db_test.*$$|^.*external_sst_file_test.*$$|^.*compaction_service_test.*$$|^.*corruption_test.*$$|^.*comparator_db_test.*$$|^.*external_sst_file_basic_test.*$$|^.*rate_limiter_test.*$$|^.*db_compaction_test.*$$|^.*write_prepared_transaction_test.*$$|^.*db_merge_operator_test.*$$|\
^.*db_dynamic_level_test.*$$|^.*db_bloom_filter_test.*$$|^.*error_handler_fs_test.*$$|^.*merge_helper_test.*$$|^.*transaction_test.*$$|^.*db_kv_checksum_test.*$$|^.*inlineskiplist_test.*$$|\
^.*db_with_timestamp_basic_test.*$$|^.*table_test.*$$|^.*db_wal_test.*$$|^.*block_based_table_reader_test.*$$|^.*block_test.*$$|\
^.*run-check-c-api-gen.*$$|^.*run-check-format.*$$
^.*db_with_timestamp_basic_test.*$$|^.*table_test.*$$|^.*db_wal_test.*$$|^.*block_based_table_reader_test.*$$|^.*block_test.*$$
prioritize_long_running_tests = \
perl -pe 's,($(slow_test_regexp)),100 $$1,' \
| sort -k1,1gr \
@@ -1173,17 +1108,27 @@ check: all
&& (build_tools/gnu_parallel --gnu --help 2>/dev/null) | \
grep -q 'GNU Parallel'; \
then \
$(MAKE) gen_check_scripts; \
$(MAKE) T="$$t" check_0; \
else \
for t in $(TESTS); do \
echo "===== Running $$t (`date`)"; ./$$t || exit 1; done; \
for t in $(CHECK_EXTRA_TARGETS); do \
echo "===== Running $$t (`date`)"; $(MAKE) $$t || exit 1; done; \
fi
rm -rf $(TEST_TMPDIR)
# NOTE: ^^^^^^^^ don't add new auxiliary checks here, but instead to
# CHECK_EXTRA_TARGETS
ifneq ($(PLATFORM), OS_AIX)
$(PYTHON) tools/check_all_python.py
ifndef ASSERT_STATUS_CHECKED # not yet working with these tests
$(PYTHON) tools/ldb_test.py
$(PYTHON) tools/db_crashtest_test.py
sh tools/rocksdb_dump_test.sh
endif
endif
ifndef SKIP_FORMAT_BUCK_CHECKS
$(MAKE) check-format
$(MAKE) check-buck-targets
$(MAKE) check-sources
$(MAKE) check-workflow-yaml
$(MAKE) check-c-api-gen
endif
# Check that the auto-generated C API files are up to date. It regenerates the
# fragments and the inlined c.h/c.cc and compares them against a snapshot of the
@@ -1204,8 +1149,8 @@ check: all
# Any non-empty value other than 0/no/false enables strict mode.
CLANG_FORMAT_BINARY ?=
# Backward-compatibility baseline for the C API (signature-level) check. CI
# overrides this with the PR's merge target or the branch's pre-push tip;
# locally it falls back to main or origin/main and is skipped if neither resolves.
# overrides this with the PR's merge target; locally it falls back to main /
# origin/main and is skipped if neither resolves.
API_COMPAT_REF ?= main
CHECK_C_API_GEN_STRICT ?=
check-c-api-gen:
@@ -1229,43 +1174,30 @@ check-c-api-gen:
echo "Skipping C API backward-compatibility check ($(API_COMPAT_REF) not found; set API_COMPAT_REF)"; \
fi
# Staleness: regenerate and confirm the checked-in output is current. Needs a
# clang++ (the generator parses C++ ASTs). Use CLANG_CXX, which
# build_tools/build_detect_platform resolves once (the fbcode clang++ in
# fbcode builds, else a versioned clang++ on PATH) and passes explicitly, so
# the check and the generator agree on the same binary without heuristics.
# clang++ (the generator parses C++ ASTs); detect one the way the generator
# does (a clang in $(CXX) -- which may be ccache-prefixed/versioned -- else a
# bare/versioned clang++ on PATH) rather than testing $(CXX) verbatim.
@strict=""; case "$(CHECK_C_API_GEN_STRICT)" in ""|0|no|NO|false|FALSE) ;; *) strict=1 ;; esac; \
cf_arg=""; \
if [ -n "$(CLANG_FORMAT_BINARY)" ]; then cf_arg="--clang-format $(CLANG_FORMAT_BINARY)"; fi; \
if [ -n "$(CLANG_CXX)" ] && command -v "$(CLANG_CXX)" >/dev/null 2>&1; then \
$(PYTHON) tools/c_api_gen/verify_generated_up_to_date.py --clang "$(CLANG_CXX)" $$cf_arg; \
have_clang=""; \
for c in $$(printf '%s\n' $(CXX) | grep -i clang) clang++ clang++-21 clang++-20 clang++-19 clang++-18 clang++-17 clang++-16 clang++-15 clang++-14 clang++-13; do \
if command -v "$$c" >/dev/null 2>&1; then have_clang=1; break; fi; \
done; \
if [ -n "$$have_clang" ]; then \
$(PYTHON) tools/c_api_gen/verify_generated_up_to_date.py $$cf_arg; \
elif [ -n "$$strict" ]; then \
echo "ERROR: no clang++ found (CLANG_CXX unset) and CHECK_C_API_GEN_STRICT is set; cannot run the C API staleness check" >&2; exit 1; \
echo "ERROR: no clang++ found and CHECK_C_API_GEN_STRICT is set; cannot run the C API staleness check" >&2; exit 1; \
else \
echo "Skipping C API codegen staleness check (no clang++ found; CLANG_CXX unset, install clang++ to enable)"; \
echo "Skipping C API codegen staleness check (no clang++ found; install clang++ or set CXX to a clang to enable)"; \
fi
# Regenerate the checked-in C API generated files (fragments under c_api_gen/,
# the inlined include/rocksdb/c.h and db/c.cc, and the round-trip tests). Uses
# CLANG_CXX (resolved by build_tools/build_detect_platform) so it works in a gcc
# build too. Aborts up front if no usable clang++ is available, so a bad
# toolchain never leaves the tree in a partially regenerated state. Pin the
# formatter to match CI with CLANG_FORMAT_BINARY, e.g.:
# make regen-c-api CLANG_FORMAT_BINARY=clang-format-21
.PHONY: regen-c-api
regen-c-api:
@if [ -z "$(CLANG_CXX)" ] || ! command -v "$(CLANG_CXX)" >/dev/null 2>&1; then \
echo "ERROR: no clang++ found (CLANG_CXX unset); build on a host with clang++ or the fbcode toolchain to regenerate the C API" >&2; exit 1; \
fi
@cf_arg=""; \
if [ -n "$(CLANG_FORMAT_BINARY)" ]; then cf_arg="--clang-format $(CLANG_FORMAT_BINARY)"; fi; \
$(PYTHON) tools/c_api_gen/regen_all.py --clang "$(CLANG_CXX)" $$cf_arg
# Quick local validation for C API generation plus the focused C API test.
# This verifies the checked-in generated fragments as well as the inlined
# include/rocksdb/c.h and db/c.cc outputs, then runs c_test in an isolated
# TEST_TMPDIR to avoid stale-state failures.
check-c-api-c_test:
$(PYTHON) tools/c_api_gen/verify_generated_up_to_date.py --clang "$(CLANG_CXX)"
$(PYTHON) tools/c_api_gen/verify_generated_up_to_date.py
$(MAKE) c_test
@tmpdir=$$(mktemp -d); \
trap 'rm -rf "$$tmpdir"' EXIT; \
@@ -1290,14 +1222,6 @@ ldb_tests: ldb
db_crashtest_tests:
$(PYTHON) tools/db_crashtest_test.py
.PHONY: check-all-python
check-all-python:
$(PYTHON) tools/check_all_python.py
.PHONY: rocksdb_dump_test
rocksdb_dump_test: rocksdb_dump rocksdb_undump
sh tools/rocksdb_dump_test.sh
include crash_test.mk
asan_check: clean
@@ -1733,9 +1657,6 @@ db_readonly_with_timestamp_test: $(OBJ_DIR)/db/db_readonly_with_timestamp_test.o
db_wide_basic_test: $(OBJ_DIR)/db/wide/db_wide_basic_test.o $(TEST_LIBRARY) $(LIBRARY)
$(AM_LINK)
db_lazy_entity_test: $(OBJ_DIR)/db/wide/db_lazy_entity_test.o $(TEST_LIBRARY) $(LIBRARY)
$(AM_LINK)
db_wide_blob_direct_write_test: $(OBJ_DIR)/db/wide/db_wide_blob_direct_write_test.o $(TEST_LIBRARY) $(LIBRARY)
$(AM_LINK)
@@ -1895,9 +1816,6 @@ backup_engine_test: $(OBJ_DIR)/utilities/backup/backup_engine_test.o $(TEST_LIBR
checkpoint_test: $(OBJ_DIR)/utilities/checkpoint/checkpoint_test.o $(TEST_LIBRARY) $(LIBRARY)
$(AM_LINK)
copy_engine_test: $(OBJ_DIR)/utilities/copy_engine/copy_engine_test.o $(TEST_LIBRARY) $(LIBRARY)
$(AM_LINK)
sorted_run_builder_test: $(OBJ_DIR)/utilities/sorted_run_builder/sorted_run_builder_test.o $(TEST_LIBRARY) $(LIBRARY)
$(AM_LINK)
@@ -2440,27 +2358,22 @@ ROCKSDB_JAVADOCS_JAR = rocksdbjni-$(ROCKSDB_JAVA_VERSION)-javadoc.jar
ROCKSDB_SOURCES_JAR = rocksdbjni-$(ROCKSDB_JAVA_VERSION)-sources.jar
SHA256_CMD = sha256sum
# The *_DOWNLOAD_PREFIX defaults below point at the upstream projects; CI
# overrides them to a mirror on the "third-party-deps" GitHub release (see
# .github/actions/pre-steps/action.yml). When bumping a version, see
# instructions in CI config comments for how to update that release.
ZLIB_VER ?= 1.3.1
ZLIB_SHA256 ?= 9a93b2b7dfdac77ceba5a558a580e74667dd6fede4585b91eefb60f03b72df23
ZLIB_DOWNLOAD_PREFIX ?= http://zlib.net/zlib-
ZLIB_DOWNLOAD_BASE ?= http://zlib.net
BZIP2_VER ?= 1.0.8
BZIP2_SHA256 ?= ab5a03176ee106d3f0fa90e381da478ddae405918153cca248e682cd0c4a2269
BZIP2_DOWNLOAD_PREFIX ?= http://sourceware.org/pub/bzip2/bzip2-
BZIP2_DOWNLOAD_BASE ?= http://sourceware.org/pub/bzip2
SNAPPY_VER ?= 1.2.2
SNAPPY_SHA256 ?= 90f74bc1fbf78a6c56b3c4a082a05103b3a56bb17bca1a27e052ea11723292dc
SNAPPY_DOWNLOAD_PREFIX ?= https://github.com/google/snappy/archive/
SNAPPY_DOWNLOAD_BASE ?= https://github.com/google/snappy/archive
LZ4_VER ?= 1.10.0
LZ4_SHA256 ?= 537512904744b35e232912055ccf8ec66d768639ff3abe5788d90d792ec5f48b
LZ4_DOWNLOAD_PREFIX ?= https://github.com/lz4/lz4/archive/v
LZ4_DOWNLOAD_BASE ?= https://github.com/lz4/lz4/archive
ZSTD_VER ?= 1.5.7
ZSTD_SHA256 ?= 37d7284556b20954e56e1ca85b80226768902e2edabd3b649e9e72c0c9012ee3
ZSTD_DOWNLOAD_PREFIX ?= https://github.com/facebook/zstd/archive/v
# curl with the common options used to fetch the pinned third-party sources above
CURL_DOWNLOAD = curl --fail --location --retry 3 --retry-all-errors
ZSTD_DOWNLOAD_BASE ?= https://github.com/facebook/zstd/archive
CURL_SSL_OPTS ?= --tlsv1
ifeq ($(PLATFORM), OS_MACOSX)
ifeq (,$(findstring librocksdbjni-osx,$(ROCKSDBJNILIB)))
@@ -2539,7 +2452,7 @@ BUILD_SIG_NONBUILD_GOALS := \
check-sources check-workflow-yaml check-progress clang-tidy \
tags tags0 package jclean checkout_folly build_folly \
watch-log dump-log suggest-slow-tests list_all_tests gen-pc \
gen_parallel_tests gen_check_scripts check-c-api-gen check-all-python \
gen_parallel_tests check-c-api-gen \
setup-hooks install-hooks uninstall-hooks uninstall db_crashtest_tests
# Goals that clean before building (depend on or invoke `clean`): they manage
# their own freshness, so the check must not block them (it would error before
@@ -2601,7 +2514,7 @@ endif
endif
zlib-$(ZLIB_VER).tar.gz:
$(CURL_DOWNLOAD) --output zlib-$(ZLIB_VER).tar.gz ${ZLIB_DOWNLOAD_PREFIX}$(ZLIB_VER).tar.gz
curl --fail --output zlib-$(ZLIB_VER).tar.gz --location ${ZLIB_DOWNLOAD_BASE}/zlib-$(ZLIB_VER).tar.gz
ZLIB_SHA256_ACTUAL=`$(SHA256_CMD) zlib-$(ZLIB_VER).tar.gz | cut -d ' ' -f 1`; \
if [ "$(ZLIB_SHA256)" != "$$ZLIB_SHA256_ACTUAL" ]; then \
echo zlib-$(ZLIB_VER).tar.gz checksum mismatch, expected=\"$(ZLIB_SHA256)\" actual=\"$$ZLIB_SHA256_ACTUAL\"; \
@@ -2619,7 +2532,7 @@ libz.a: zlib-$(ZLIB_VER).tar.gz
cp zlib-$(ZLIB_VER)/libz.a .
bzip2-$(BZIP2_VER).tar.gz:
$(CURL_DOWNLOAD) --output bzip2-$(BZIP2_VER).tar.gz ${BZIP2_DOWNLOAD_PREFIX}$(BZIP2_VER).tar.gz
curl --fail --output bzip2-$(BZIP2_VER).tar.gz --location ${CURL_SSL_OPTS} ${BZIP2_DOWNLOAD_BASE}/bzip2-$(BZIP2_VER).tar.gz
BZIP2_SHA256_ACTUAL=`$(SHA256_CMD) bzip2-$(BZIP2_VER).tar.gz | cut -d ' ' -f 1`; \
if [ "$(BZIP2_SHA256)" != "$$BZIP2_SHA256_ACTUAL" ]; then \
echo bzip2-$(BZIP2_VER).tar.gz checksum mismatch, expected=\"$(BZIP2_SHA256)\" actual=\"$$BZIP2_SHA256_ACTUAL\"; \
@@ -2633,7 +2546,7 @@ libbz2.a: bzip2-$(BZIP2_VER).tar.gz
cp bzip2-$(BZIP2_VER)/libbz2.a .
snappy-$(SNAPPY_VER).tar.gz:
$(CURL_DOWNLOAD) --output snappy-$(SNAPPY_VER).tar.gz ${SNAPPY_DOWNLOAD_PREFIX}$(SNAPPY_VER).tar.gz
curl --fail --output snappy-$(SNAPPY_VER).tar.gz --location ${CURL_SSL_OPTS} ${SNAPPY_DOWNLOAD_BASE}/$(SNAPPY_VER).tar.gz
SNAPPY_SHA256_ACTUAL=`$(SHA256_CMD) snappy-$(SNAPPY_VER).tar.gz | cut -d ' ' -f 1`; \
if [ "$(SNAPPY_SHA256)" != "$$SNAPPY_SHA256_ACTUAL" ]; then \
echo snappy-$(SNAPPY_VER).tar.gz checksum mismatch, expected=\"$(SNAPPY_SHA256)\" actual=\"$$SNAPPY_SHA256_ACTUAL\"; \
@@ -2648,7 +2561,7 @@ libsnappy.a: snappy-$(SNAPPY_VER).tar.gz
cp snappy-$(SNAPPY_VER)/build/libsnappy.a .
lz4-$(LZ4_VER).tar.gz:
$(CURL_DOWNLOAD) --output lz4-$(LZ4_VER).tar.gz ${LZ4_DOWNLOAD_PREFIX}$(LZ4_VER).tar.gz
curl --fail --output lz4-$(LZ4_VER).tar.gz --location ${CURL_SSL_OPTS} ${LZ4_DOWNLOAD_BASE}/v$(LZ4_VER).tar.gz
LZ4_SHA256_ACTUAL=`$(SHA256_CMD) lz4-$(LZ4_VER).tar.gz | cut -d ' ' -f 1`; \
if [ "$(LZ4_SHA256)" != "$$LZ4_SHA256_ACTUAL" ]; then \
echo lz4-$(LZ4_VER).tar.gz checksum mismatch, expected=\"$(LZ4_SHA256)\" actual=\"$$LZ4_SHA256_ACTUAL\"; \
@@ -2662,7 +2575,7 @@ liblz4.a: lz4-$(LZ4_VER).tar.gz
cp lz4-$(LZ4_VER)/lib/liblz4.a .
zstd-$(ZSTD_VER).tar.gz:
$(CURL_DOWNLOAD) --output zstd-$(ZSTD_VER).tar.gz ${ZSTD_DOWNLOAD_PREFIX}$(ZSTD_VER).tar.gz
curl --fail --output zstd-$(ZSTD_VER).tar.gz --location ${CURL_SSL_OPTS} ${ZSTD_DOWNLOAD_BASE}/v$(ZSTD_VER).tar.gz
ZSTD_SHA256_ACTUAL=`$(SHA256_CMD) zstd-$(ZSTD_VER).tar.gz | cut -d ' ' -f 1`; \
if [ "$(ZSTD_SHA256)" != "$$ZSTD_SHA256_ACTUAL" ]; then \
echo zstd-$(ZSTD_VER).tar.gz checksum mismatch, expected=\"$(ZSTD_SHA256)\" actual=\"$$ZSTD_SHA256_ACTUAL\"; \
-10
View File
@@ -145,21 +145,11 @@ def generate_buck(repo_path, deps_map):
# always add range_tree, it's only excluded on ppc64, which we don't use internally
src_mk["RANGE_TREE_SOURCES"] + src_mk["TOOL_LIB_SOURCES"],
deps=[
"//folly:executor",
"//folly/container:f14_hash",
"//folly/coro:baton",
"//folly/coro:blocking_wait",
"//folly/coro:collect",
"//folly/coro:coroutine",
"//folly/coro:nothrow",
"//folly/coro:task",
"//folly/executors:io_executor",
"//folly/executors:io_thread_pool_executor",
"//folly/executors/thread_factory:named_thread_factory",
"//folly/io/async:async_base",
"//folly/io/async:event_base_manager",
"//folly/io/async:io_uring_backend",
"//folly/io/async:request_context",
"//folly/synchronization:distributed_mutex",
],
headers=LiteralValue("glob([\"**/*.h\"])")
+5 -43
View File
@@ -89,36 +89,13 @@ if test -z "$CC"; then
fi
fi
# CLANG_CXX is the single clang++ detection point for the whole script: it is
# used for CXX when building with clang, for CLANG_ANALYZER (scan-build), and by
# tooling that needs clang even in a gcc build (e.g. the C API codegen, which
# parses C++ ASTs). The fbcode config above already sets CLANG_CXX; otherwise
# resolve it here.
if test -z "$CLANG_CXX"; then
if [ -n "$CXX" ] && echo | $CXX -dM -E -x c++ - 2>/dev/null | grep -q '\b__clang__\b'; then
# Honor an already-configured clang compiler (e.g. CI sets
# CXX=clang++-21) so codegen parses headers with the same clang the
# build uses, not an unrelated clang++ that merely happens to come first
# on PATH (an image may ship both a bare clang++ and clang++-NN).
CLANG_CXX="$CXX"
else
# Otherwise take the first clang++ on PATH. Candidates cover a bare
# clang++, versioned names, and clang++.par (a Meta-internal wrapper
# often present on dev machines).
CLANG_CXX=$(command -v clang++ || command -v clang++-21 || command -v clang++-20 \
|| command -v clang++-19 || command -v clang++-18 || command -v clang++-17 \
|| command -v clang++-16 || command -v clang++-15 || command -v clang++-14 \
|| command -v clang++-13 || command -v clang++.par || true)
fi
fi
if test -z "$CXX"; then
if [ "$USE_CLANG" ] && [ -n "$CLANG_CXX" ]; then
CXX="$CLANG_CXX"
if [ "$USE_CLANG" -a -x "$(command -v clang++)" ]; then
CXX=clang++
elif [ -x "$(command -v g++)" ]; then
CXX=g++
elif [ -n "$CLANG_CXX" ]; then
CXX="$CLANG_CXX"
elif [ -x "$(command -v clang++)" ]; then
CXX=clang++
else
CXX=g++
fi
@@ -136,17 +113,6 @@ if test -z "$AR"; then
fi
fi
# If the selected C++ compiler is actually clang (e.g. clang was the only
# compiler available), reflect that as USE_CLANG so clang-specific logic in the
# Makefile applies consistently. Detect it via the compiler's own __clang__
# predefined macro rather than matching the binary path, which can false-positive
# (e.g. a home directory containing "clang").
if test -z "$USE_CLANG"; then
if echo | $CXX -dM -E -x c++ - 2>/dev/null | grep -q '\b__clang__\b'; then
USE_CLANG=1
fi
fi
# Detect OS
if test -z "$TARGET_OS"; then
TARGET_OS=`uname -s`
@@ -161,7 +127,7 @@ if test -z "$CLANG_SCAN_BUILD"; then
fi
if test -z "$CLANG_ANALYZER"; then
CLANG_ANALYZER="$CLANG_CXX"
CLANG_ANALYZER=$(command -v clang++ 2> /dev/null)
fi
if test -z "$FIND"; then
@@ -852,10 +818,6 @@ echo "ROCKSDB_MINOR=$ROCKSDB_MINOR" >> "$OUTPUT"
echo "ROCKSDB_PATCH=$ROCKSDB_PATCH" >> "$OUTPUT"
echo "CLANG_SCAN_BUILD=$CLANG_SCAN_BUILD" >> "$OUTPUT"
echo "CLANG_ANALYZER=$CLANG_ANALYZER" >> "$OUTPUT"
echo "CLANG_CXX=$CLANG_CXX" >> "$OUTPUT"
if test -n "$USE_CLANG"; then
echo "USE_CLANG=$USE_CLANG" >> "$OUTPUT"
fi
echo "PROFILING_FLAGS=$PROFILING_FLAGS" >> "$OUTPUT"
echo "FIND=$FIND" >> "$OUTPUT"
echo "WATCH=$WATCH" >> "$OUTPUT"
+1 -5
View File
@@ -104,10 +104,6 @@ CLANG_BIN="$CLANG_BASE/bin"
CLANG_LIB="$CLANG_BASE/lib"
CLANG_SRC="$CLANG_BASE/../../src"
# A clang++ is always available in the fbcode toolchain regardless of whether
# the build itself uses gcc or clang. CLANG_CXX exposes it for tooling (e.g. the
# C API codegen, which parses C++ ASTs) that needs clang even in a gcc build.
CLANG_CXX="$CLANG_BIN/clang++"
CLANG_ANALYZER="$CLANG_BIN/clang++"
CLANG_SCAN_BUILD="$CLANG_BIN/scan-build"
@@ -171,4 +167,4 @@ EXEC_LDFLAGS_SHARED="$SNAPPY_LIBS $ZLIB_LIBS $BZIP_LIBS $LZ4_LIBS $ZSTD_LIBS $GF
VALGRIND_VER="$VALGRIND_BASE/bin/"
export CC CXX AR AS CFLAGS CXXFLAGS EXEC_LDFLAGS EXEC_LDFLAGS_SHARED VALGRIND_VER JEMALLOC_LIB JEMALLOC_INCLUDE CLANG_CXX CLANG_ANALYZER CLANG_SCAN_BUILD
export CC CXX AR AS CFLAGS CXXFLAGS EXEC_LDFLAGS EXEC_LDFLAGS_SHARED VALGRIND_VER JEMALLOC_LIB JEMALLOC_INCLUDE CLANG_ANALYZER CLANG_SCAN_BUILD
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/generate_c_api.py.
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/generate_c_api.py.
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/generate_c_api.py.
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/generate_c_api.py.
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/generate_c_api.py.
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/generate_c_api.py.
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/auto_simple_bindings.py.
-4
View File
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/auto_simple_bindings.py.
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/generate_c_api.py.
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/generate_c_api.py.
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/auto_simple_bindings.py.
@@ -482,17 +478,6 @@ uint64_t rocksdb_compaction_file_info_oldest_blob_file_number(
/* BlobFileAdditionInfo */
const char* rocksdb_blob_file_addition_info_blob_file_path(
const rocksdb_blob_file_addition_info_t* info, size_t* size) {
*size = info->rep.blob_file_path.size();
return info->rep.blob_file_path.data();
}
uint64_t rocksdb_blob_file_addition_info_blob_file_number(
const rocksdb_blob_file_addition_info_t* info) {
return info->rep.blob_file_number;
}
uint64_t rocksdb_blob_file_addition_info_total_blob_count(
const rocksdb_blob_file_addition_info_t* info) {
return info->rep.total_blob_count;
@@ -505,17 +490,6 @@ uint64_t rocksdb_blob_file_addition_info_total_blob_bytes(
/* BlobFileGarbageInfo */
const char* rocksdb_blob_file_garbage_info_blob_file_path(
const rocksdb_blob_file_garbage_info_t* info, size_t* size) {
*size = info->rep.blob_file_path.size();
return info->rep.blob_file_path.data();
}
uint64_t rocksdb_blob_file_garbage_info_blob_file_number(
const rocksdb_blob_file_garbage_info_t* info) {
return info->rep.blob_file_number;
}
uint64_t rocksdb_blob_file_garbage_info_garbage_blob_count(
const rocksdb_blob_file_garbage_info_t* info) {
return info->rep.garbage_blob_count;
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/auto_simple_bindings.py.
@@ -346,14 +342,6 @@ rocksdb_compaction_file_info_oldest_blob_file_number(
/* BlobFileAdditionInfo */
extern ROCKSDB_LIBRARY_API const char*
rocksdb_blob_file_addition_info_blob_file_path(
const rocksdb_blob_file_addition_info_t* info, size_t* size);
extern ROCKSDB_LIBRARY_API uint64_t
rocksdb_blob_file_addition_info_blob_file_number(
const rocksdb_blob_file_addition_info_t* info);
extern ROCKSDB_LIBRARY_API uint64_t
rocksdb_blob_file_addition_info_total_blob_count(
const rocksdb_blob_file_addition_info_t* info);
@@ -364,14 +352,6 @@ rocksdb_blob_file_addition_info_total_blob_bytes(
/* BlobFileGarbageInfo */
extern ROCKSDB_LIBRARY_API const char*
rocksdb_blob_file_garbage_info_blob_file_path(
const rocksdb_blob_file_garbage_info_t* info, size_t* size);
extern ROCKSDB_LIBRARY_API uint64_t
rocksdb_blob_file_garbage_info_blob_file_number(
const rocksdb_blob_file_garbage_info_t* info);
extern ROCKSDB_LIBRARY_API uint64_t
rocksdb_blob_file_garbage_info_garbage_blob_count(
const rocksdb_blob_file_garbage_info_t* info);
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/auto_simple_bindings.py.
@@ -141,15 +137,6 @@ int rocksdb_options_get_max_file_opening_threads(rocksdb_options_t* opt) {
return opt->rep.max_file_opening_threads;
}
void rocksdb_options_set_read_io_executor_threads(rocksdb_options_t* opt,
int v) {
opt->rep.read_io_executor_threads = v;
}
int rocksdb_options_get_read_io_executor_threads(rocksdb_options_t* opt) {
return opt->rep.read_io_executor_threads;
}
void rocksdb_options_set_open_files_async(rocksdb_options_t* opt,
unsigned char v) {
opt->rep.open_files_async = v;
@@ -1305,16 +1292,6 @@ uint64_t rocksdb_options_get_blob_file_size(rocksdb_options_t* opt) {
return opt->rep.blob_file_size;
}
void rocksdb_options_set_blob_file_writable_file_max_buffer_size(
rocksdb_options_t* opt, uint64_t v) {
opt->rep.blob_file_writable_file_max_buffer_size = v;
}
uint64_t rocksdb_options_get_blob_file_writable_file_max_buffer_size(
rocksdb_options_t* opt) {
return opt->rep.blob_file_writable_file_max_buffer_size;
}
void rocksdb_options_set_blob_compression_type(rocksdb_options_t* opt, int v) {
opt->rep.blob_compression_type =
static_cast<decltype(opt->rep.blob_compression_type)>(v);
@@ -1697,16 +1674,6 @@ unsigned char rocksdb_flushoptions_get_force_atomic_flush(
return opt->rep.force_atomic_flush;
}
void rocksdb_flushoptions_set_listener_wait(rocksdb_flushoptions_t* opt,
unsigned char v) {
opt->rep.listener_wait = v;
}
unsigned char rocksdb_flushoptions_get_listener_wait(
rocksdb_flushoptions_t* opt) {
return opt->rep.listener_wait;
}
/* FlushWALOptions */
void rocksdb_flushwaloptions_set_sync(rocksdb_flushwaloptions_t* opt,
@@ -2736,36 +2703,6 @@ uint64_t rocksdb_fifo_compaction_options_get_trivial_copy_buffer_size(
/* BackupEngineOptions */
void rocksdb_backup_engine_options_set_io_buffer_size(
rocksdb_backup_engine_options_t* opt, uint64_t v) {
opt->rep.io_buffer_size = v;
}
uint64_t rocksdb_backup_engine_options_get_io_buffer_size(
rocksdb_backup_engine_options_t* opt) {
return opt->rep.io_buffer_size;
}
void rocksdb_backup_engine_options_set_backup_rate_limit(
rocksdb_backup_engine_options_t* opt, uint64_t v) {
opt->rep.backup_rate_limit = v;
}
uint64_t rocksdb_backup_engine_options_get_backup_rate_limit(
rocksdb_backup_engine_options_t* opt) {
return opt->rep.backup_rate_limit;
}
void rocksdb_backup_engine_options_set_max_background_operations(
rocksdb_backup_engine_options_t* opt, int v) {
opt->rep.max_background_operations = v;
}
int rocksdb_backup_engine_options_get_max_background_operations(
rocksdb_backup_engine_options_t* opt) {
return opt->rep.max_background_operations;
}
void rocksdb_backup_engine_options_set_backup_dir(
rocksdb_backup_engine_options_t* opt, const char* v) {
opt->rep.backup_dir = v;
@@ -2817,6 +2754,26 @@ unsigned char rocksdb_backup_engine_options_get_backup_log_files(
return opt->rep.backup_log_files;
}
void rocksdb_backup_engine_options_set_io_buffer_size(
rocksdb_backup_engine_options_t* opt, uint64_t v) {
opt->rep.io_buffer_size = v;
}
uint64_t rocksdb_backup_engine_options_get_io_buffer_size(
rocksdb_backup_engine_options_t* opt) {
return opt->rep.io_buffer_size;
}
void rocksdb_backup_engine_options_set_backup_rate_limit(
rocksdb_backup_engine_options_t* opt, uint64_t v) {
opt->rep.backup_rate_limit = v;
}
uint64_t rocksdb_backup_engine_options_get_backup_rate_limit(
rocksdb_backup_engine_options_t* opt) {
return opt->rep.backup_rate_limit;
}
void rocksdb_backup_engine_options_set_restore_rate_limit(
rocksdb_backup_engine_options_t* opt, uint64_t v) {
opt->rep.restore_rate_limit = v;
@@ -2837,6 +2794,16 @@ unsigned char rocksdb_backup_engine_options_get_share_files_with_checksum(
return opt->rep.share_files_with_checksum;
}
void rocksdb_backup_engine_options_set_max_background_operations(
rocksdb_backup_engine_options_t* opt, int v) {
opt->rep.max_background_operations = v;
}
int rocksdb_backup_engine_options_get_max_background_operations(
rocksdb_backup_engine_options_t* opt) {
return opt->rep.max_background_operations;
}
void rocksdb_backup_engine_options_set_callback_trigger_interval_size(
rocksdb_backup_engine_options_t* opt, uint64_t v) {
opt->rep.callback_trigger_interval_size = v;
@@ -2891,6 +2858,16 @@ rocksdb_backup_engine_options_get_current_temperatures_override_manifest(
/* CreateBackupOptions */
void rocksdb_create_backup_options_set_flush_before_backup(
rocksdb_create_backup_options_t* opt, unsigned char v) {
opt->rep.flush_before_backup = v;
}
unsigned char rocksdb_create_backup_options_get_flush_before_backup(
rocksdb_create_backup_options_t* opt) {
return opt->rep.flush_before_backup;
}
void rocksdb_create_backup_options_set_decrease_background_thread_cpu_priority(
rocksdb_create_backup_options_t* opt, unsigned char v) {
opt->rep.decrease_background_thread_cpu_priority = v;
@@ -2913,16 +2890,6 @@ int rocksdb_create_backup_options_get_background_thread_cpu_priority(
return static_cast<int>(opt->rep.background_thread_cpu_priority);
}
void rocksdb_create_backup_options_set_flush_before_backup(
rocksdb_create_backup_options_t* opt, unsigned char v) {
opt->rep.flush_before_backup = v;
}
unsigned char rocksdb_create_backup_options_get_flush_before_backup(
rocksdb_create_backup_options_t* opt) {
return opt->rep.flush_before_backup;
}
void rocksdb_create_backup_options_set_atomic_flush(
rocksdb_create_backup_options_t* opt, unsigned char v) {
opt->rep.atomic_flush = v;
+32 -56
View File
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/auto_simple_bindings.py.
@@ -55,12 +51,6 @@ rocksdb_options_set_verify_sst_unique_id_in_manifest(rocksdb_options_t* opt,
extern ROCKSDB_LIBRARY_API unsigned char
rocksdb_options_get_verify_sst_unique_id_in_manifest(rocksdb_options_t* opt);
extern ROCKSDB_LIBRARY_API void rocksdb_options_set_read_io_executor_threads(
rocksdb_options_t* opt, int v);
extern ROCKSDB_LIBRARY_API int rocksdb_options_get_read_io_executor_threads(
rocksdb_options_t* opt);
extern ROCKSDB_LIBRARY_API const char* rocksdb_options_get_db_log_dir(
rocksdb_options_t* opt, size_t* size);
@@ -387,14 +377,6 @@ rocksdb_options_set_preserve_internal_time_seconds(rocksdb_options_t* opt,
extern ROCKSDB_LIBRARY_API uint64_t
rocksdb_options_get_preserve_internal_time_seconds(rocksdb_options_t* opt);
extern ROCKSDB_LIBRARY_API void
rocksdb_options_set_blob_file_writable_file_max_buffer_size(
rocksdb_options_t* opt, uint64_t v);
extern ROCKSDB_LIBRARY_API uint64_t
rocksdb_options_get_blob_file_writable_file_max_buffer_size(
rocksdb_options_t* opt);
extern ROCKSDB_LIBRARY_API void rocksdb_options_set_enable_blob_direct_write(
rocksdb_options_t* opt, unsigned char v);
@@ -559,12 +541,6 @@ extern ROCKSDB_LIBRARY_API void rocksdb_flushoptions_set_force_atomic_flush(
extern ROCKSDB_LIBRARY_API unsigned char
rocksdb_flushoptions_get_force_atomic_flush(rocksdb_flushoptions_t* opt);
extern ROCKSDB_LIBRARY_API void rocksdb_flushoptions_set_listener_wait(
rocksdb_flushoptions_t* opt, unsigned char v);
extern ROCKSDB_LIBRARY_API unsigned char rocksdb_flushoptions_get_listener_wait(
rocksdb_flushoptions_t* opt);
/* FlushWALOptions */
extern ROCKSDB_LIBRARY_API void rocksdb_flushwaloptions_set_sync(
@@ -1337,30 +1313,6 @@ rocksdb_fifo_compaction_options_get_trivial_copy_buffer_size(
/* BackupEngineOptions */
extern ROCKSDB_LIBRARY_API void
rocksdb_backup_engine_options_set_io_buffer_size(
rocksdb_backup_engine_options_t* opt, uint64_t v);
extern ROCKSDB_LIBRARY_API uint64_t
rocksdb_backup_engine_options_get_io_buffer_size(
rocksdb_backup_engine_options_t* opt);
extern ROCKSDB_LIBRARY_API void
rocksdb_backup_engine_options_set_backup_rate_limit(
rocksdb_backup_engine_options_t* opt, uint64_t v);
extern ROCKSDB_LIBRARY_API uint64_t
rocksdb_backup_engine_options_get_backup_rate_limit(
rocksdb_backup_engine_options_t* opt);
extern ROCKSDB_LIBRARY_API void
rocksdb_backup_engine_options_set_max_background_operations(
rocksdb_backup_engine_options_t* opt, int v);
extern ROCKSDB_LIBRARY_API int
rocksdb_backup_engine_options_get_max_background_operations(
rocksdb_backup_engine_options_t* opt);
extern ROCKSDB_LIBRARY_API void rocksdb_backup_engine_options_set_backup_dir(
rocksdb_backup_engine_options_t* opt, const char* v);
@@ -1398,6 +1350,22 @@ extern ROCKSDB_LIBRARY_API unsigned char
rocksdb_backup_engine_options_get_backup_log_files(
rocksdb_backup_engine_options_t* opt);
extern ROCKSDB_LIBRARY_API void
rocksdb_backup_engine_options_set_io_buffer_size(
rocksdb_backup_engine_options_t* opt, uint64_t v);
extern ROCKSDB_LIBRARY_API uint64_t
rocksdb_backup_engine_options_get_io_buffer_size(
rocksdb_backup_engine_options_t* opt);
extern ROCKSDB_LIBRARY_API void
rocksdb_backup_engine_options_set_backup_rate_limit(
rocksdb_backup_engine_options_t* opt, uint64_t v);
extern ROCKSDB_LIBRARY_API uint64_t
rocksdb_backup_engine_options_get_backup_rate_limit(
rocksdb_backup_engine_options_t* opt);
extern ROCKSDB_LIBRARY_API void
rocksdb_backup_engine_options_set_restore_rate_limit(
rocksdb_backup_engine_options_t* opt, uint64_t v);
@@ -1414,6 +1382,14 @@ extern ROCKSDB_LIBRARY_API unsigned char
rocksdb_backup_engine_options_get_share_files_with_checksum(
rocksdb_backup_engine_options_t* opt);
extern ROCKSDB_LIBRARY_API void
rocksdb_backup_engine_options_set_max_background_operations(
rocksdb_backup_engine_options_t* opt, int v);
extern ROCKSDB_LIBRARY_API int
rocksdb_backup_engine_options_get_max_background_operations(
rocksdb_backup_engine_options_t* opt);
extern ROCKSDB_LIBRARY_API void
rocksdb_backup_engine_options_set_callback_trigger_interval_size(
rocksdb_backup_engine_options_t* opt, uint64_t v);
@@ -1455,6 +1431,14 @@ rocksdb_backup_engine_options_get_current_temperatures_override_manifest(
/* CreateBackupOptions */
extern ROCKSDB_LIBRARY_API void
rocksdb_create_backup_options_set_flush_before_backup(
rocksdb_create_backup_options_t* opt, unsigned char v);
extern ROCKSDB_LIBRARY_API unsigned char
rocksdb_create_backup_options_get_flush_before_backup(
rocksdb_create_backup_options_t* opt);
extern ROCKSDB_LIBRARY_API void
rocksdb_create_backup_options_set_decrease_background_thread_cpu_priority(
rocksdb_create_backup_options_t* opt, unsigned char v);
@@ -1471,14 +1455,6 @@ extern ROCKSDB_LIBRARY_API int
rocksdb_create_backup_options_get_background_thread_cpu_priority(
rocksdb_create_backup_options_t* opt);
extern ROCKSDB_LIBRARY_API void
rocksdb_create_backup_options_set_flush_before_backup(
rocksdb_create_backup_options_t* opt, unsigned char v);
extern ROCKSDB_LIBRARY_API unsigned char
rocksdb_create_backup_options_get_flush_before_backup(
rocksdb_create_backup_options_t* opt);
extern ROCKSDB_LIBRARY_API void rocksdb_create_backup_options_set_atomic_flush(
rocksdb_create_backup_options_t* opt, unsigned char v);
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/generate_c_api.py.
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/generate_c_api.py.
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/auto_simple_bindings.py.
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/auto_simple_bindings.py.
+1 -19
View File
@@ -1,13 +1,9 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/gen_roundtrip_tests.py.
// DO NOT EDIT THIS FILE DIRECTLY.
// Round-trip (set -> get -> assert) coverage for generated option wrappers.
// Rerun `make regen-c-api`
// Rerun: python3 tools/c_api_gen/regen_all.py
// -----------------------------------------------------------------------------
static void rocksdb_roundtrip_test_rocksdb_block_based_options(void) {
@@ -463,10 +459,6 @@ static void rocksdb_roundtrip_test_rocksdb_flushoptions(void) {
CheckCondition(rocksdb_flushoptions_get_force_atomic_flush(obj) == 1);
rocksdb_flushoptions_set_force_atomic_flush(obj, 0);
CheckCondition(rocksdb_flushoptions_get_force_atomic_flush(obj) == 0);
rocksdb_flushoptions_set_listener_wait(obj, 1);
CheckCondition(rocksdb_flushoptions_get_listener_wait(obj) == 1);
rocksdb_flushoptions_set_listener_wait(obj, 0);
CheckCondition(rocksdb_flushoptions_get_listener_wait(obj) == 0);
rocksdb_flushoptions_set_wait(obj, 1);
CheckCondition(rocksdb_flushoptions_get_wait(obj) == 1);
rocksdb_flushoptions_set_wait(obj, 0);
@@ -647,12 +639,6 @@ static void rocksdb_roundtrip_test_rocksdb_options(void) {
CheckCondition(rocksdb_options_get_blob_direct_write_partitions(obj) == 1);
rocksdb_options_set_blob_direct_write_partitions(obj, 0);
CheckCondition(rocksdb_options_get_blob_direct_write_partitions(obj) == 0);
rocksdb_options_set_blob_file_writable_file_max_buffer_size(obj, 1);
CheckCondition(
rocksdb_options_get_blob_file_writable_file_max_buffer_size(obj) == 1);
rocksdb_options_set_blob_file_writable_file_max_buffer_size(obj, 0);
CheckCondition(
rocksdb_options_get_blob_file_writable_file_max_buffer_size(obj) == 0);
rocksdb_options_set_block_protection_bytes_per_key(obj, 1);
CheckCondition(rocksdb_options_get_block_protection_bytes_per_key(obj) == 1);
rocksdb_options_set_block_protection_bytes_per_key(obj, 0);
@@ -855,10 +841,6 @@ static void rocksdb_roundtrip_test_rocksdb_options(void) {
CheckCondition(rocksdb_options_get_preserve_internal_time_seconds(obj) == 1);
rocksdb_options_set_preserve_internal_time_seconds(obj, 0);
CheckCondition(rocksdb_options_get_preserve_internal_time_seconds(obj) == 0);
rocksdb_options_set_read_io_executor_threads(obj, 1);
CheckCondition(rocksdb_options_get_read_io_executor_threads(obj) == 1);
rocksdb_options_set_read_io_executor_threads(obj, 0);
CheckCondition(rocksdb_options_get_read_io_executor_threads(obj) == 0);
rocksdb_options_set_reuse_manifest_on_open(obj, 1);
CheckCondition(rocksdb_options_get_reuse_manifest_on_open(obj) == 1);
rocksdb_options_set_reuse_manifest_on_open(obj, 0);
-4
View File
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/generate_c_api.py.
-4
View File
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/generate_c_api.py.
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/generate_c_api.py.
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/generate_c_api.py.
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/generate_c_api.py.
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/generate_c_api.py.
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/generate_c_api.py.
@@ -1,7 +1,3 @@
// 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).
// @generated
// -----------------------------------------------------------------------------
// Auto-generated by tools/c_api_gen/generate_c_api.py.
+13 -31
View File
@@ -4,19 +4,12 @@
Thorough multi-agent code review for RocksDB commits following CLAUDE.md guidelines,
with structured codebase exploration, inter-agent debate, and verification.
IMPORTANT — Where the review goes: Your FINAL RESPONSE TEXT is the review.
The PR comment is generated verbatim from your final response, so the
complete, polished review MUST appear there in full. Do NOT end your turn with
a meta-summary such as "the review has been written to review-findings.md" —
paste the entire review as your response.
review-findings.md is a RECOVERY BACKSTOP, not the primary output: after
completing EACH major phase (Setup, Codebase Context, Initial Review, Debate,
Synthesis), append your current findings to it with the Write tool, and after
the final synthesis overwrite it with the complete review. This preserves
partial results if the turn limit interrupts the run (a recovery step reads
this file); it does NOT substitute for outputting the full review as your
final response.
IMPORTANT — Incremental output: After completing EACH major phase (Setup,
Codebase Context, Initial Review, Debate, Synthesis), append your findings
to review-findings.md using the Write tool. This ensures partial results are
saved even if the review is interrupted by the turn limit. After the final
synthesis, write the complete review to review-findings.md, replacing
previous content. Also output the final review as your response text.
## Workflow Steps
@@ -473,9 +466,7 @@ Team lead synthesizes the debate into a consensus document:
- Include detailed bug analysis (root cause, vulnerable code paths)
- Include suggested fixes
- Note which findings were debated and the outcome
- Output the complete review as your final response text (this becomes the PR
comment verbatim), and also overwrite review-findings.md with the identical
content as a recovery backstop
- Write the complete review to review-findings.md and output as response
**Final report quality rules:**
- The final report must be CLEAN and POLISHED. No stream-of-consciousness,
@@ -492,10 +483,9 @@ Team lead synthesizes the debate into a consensus document:
**REQUIRED output structure (so the PR page stays scrollable):**
Your final response — which becomes the PR comment verbatim — (and the
identical contents of `review-findings.md`) MUST follow this exact structure.
The summary appears first so reviewers can see HIGH findings at a glance;
everything else is hidden behind a `<details>` block.
The final response (and contents of `review-findings.md`) MUST follow this
exact structure. The summary appears first so reviewers can see HIGH findings
at a glance; everything else is hidden behind a `<details>` block.
```markdown
## Summary
@@ -543,9 +533,6 @@ Rules for this structure:
- Do NOT nest a `<details>` inside another `<details>`.
- Do NOT add any text after the closing `</details>` — the comment-builder
appends its own footer.
- Your final response MUST be the review itself in this structure — never a
meta-summary like "the review has been written to review-findings.md". The
PR comment is generated verbatim from your final response.
- If the review is partial (recovery path), still produce the summary block
first, and put whatever was salvaged inside the `<details>` block.
@@ -584,14 +571,9 @@ Rules for this structure:
- [ ] All callers enumerated with parameter range table
## Output Structure
Your **final response text is the primary output** — it becomes the PR comment
verbatim. The files below are working artifacts and recovery backstops only;
they are NOT a substitute for outputting the full review in your final response.
Write these artifacts to the working directory root:
- `review-findings.md` — Recovery backstop: incremental findings appended after
each phase, overwritten with the final synthesized review at the end. Used
only if the turn limit interrupts the run.
Write all review artifacts to the working directory root:
- `review-findings.md` — Incremental findings (appended after each phase),
then replaced with the final synthesized review at the end
- `context.md` — Codebase context (call chains, invariants)
- `findings-*.md` — Per-agent findings (design, correctness, cross-component,
invariant-adversary, caller-audit, performance, api, serialization, tests)
+104
View File
@@ -0,0 +1,104 @@
# Code Review Skill
This document defines the methodology for performing thorough, multi-perspective
code reviews on RocksDB changes. It is used both by CI (GitHub Actions) and
local review workflows.
## Prerequisites
Before starting a review:
- Read `CLAUDE.md` in the repository root for project-specific guidelines
- Read any files in `claude_md/` for architecture context
- Identify the commit/diff/PR to review and parse the changed files
## Review Methodology
Conduct the review from multiple perspectives, then synthesize findings into a
single report. Each perspective catches different classes of bugs.
### Perspective 1: Codebase Context & Call-Chain Analysis
Before reviewing the diff itself, build deep context:
- For each changed function/method, trace the call chain UPWARD 3-5 levels.
Who consumes the changed behavior? What invariants do callers rely on?
- Trace DOWNWARD into callees. What side effects do they have? What shared
state do they mutate (counters, sequence numbers, flags, metadata)?
- Identify the "sibling" or "reference" implementation that handles the same
scenario the standard way. Compare behaviors.
- For data written to shared structures (memtable, SST block, cache entry),
find ALL readers and verify their visibility rules match the writer.
### Perspective 2: Correctness & Edge Cases
- Thread safety and concurrency (lock ordering, data races)
- Error handling and Status propagation
- Edge cases: empty inputs, overflow, boundary conditions
- Data corruption scenarios
- Behavioral contract changes: do return value semantics match callers?
### Perspective 3: Cross-Component & Adversarial Analysis
Check the change in ALL execution contexts:
| Context | Key difference |
|---------|---------------|
| WritePreparedTxnDB | read_callback_ controls visibility |
| ReadOnly DB / SecondaryInstance | No mutable memtable |
| CompactionService / Remote compaction | Different process |
| User-defined timestamps | Extra key comparison dimension |
| MemPurge | Memtable-to-memtable path |
| BlobDB | Values in blob files, not inline |
| Old snapshots | Seqno far behind current |
| Concurrent writers | Lock-free vs locked paths |
| FIFO / Universal compaction | Different invariants |
| Prefix seek / total order seek | Different iterator behavior |
When the change claims a property ("logically redundant", "safe because X"),
systematically try to break it: list preconditions, construct counterexamples.
### Perspective 4: Performance
RocksDB is a high-performance storage engine.
- Memory allocation on hot paths
- Unnecessary copies (prefer move semantics, Slice, string_view)
- Cache efficiency and data locality
- Loop optimization, branch prediction (LIKELY/UNLIKELY)
### Perspective 5: API, Compatibility & Testing
- Public API backwards compatibility
- Serialization format correctness and versioning
- Test coverage for edge cases, failure modes, and system-level interactions
## How to Explore the Codebase
Use available tools to explore deeply — do NOT just review the diff in isolation.
The most critical bugs hide at component boundaries.
- Read the header files for changed implementations
- Search for callers of changed functions (3-5 levels up)
- Read existing tests to understand guaranteed behaviors
- Check related implementations for conventions and patterns
## Output Format
### Summary
Brief overall assessment (1-2 sentences).
### Issues Found
Categorize by severity:
- :red_circle: **Critical**: Must fix (correctness, data corruption, security)
- :yellow_circle: **Suggestion**: Should consider (performance, edge cases)
- :green_circle: **Nitpick**: Minor style issues
For each issue include:
- File and line reference
- Which review perspective found it
- Description with root cause analysis
- Suggested fix
### Cross-Component Analysis
Execution context checks and assumption stress-test results.
### Positive Observations
Good patterns, clever optimizations, or improvements.
-67
View File
@@ -1,67 +0,0 @@
# Manual (Local) Code Review — Lightweight Wrapper
## What this is
A resource-light, **single-reviewer** variant of `claude_md/ci_review_prompt.md`
for running a review by hand in a local Claude Code / Devmate session. It reuses
the full CI review *methodology* but drops the multi-agent orchestration and the
CI-only file-persistence machinery, to approximate the heavyweight result at a
fraction of the cost.
**Scope: LOCAL manual review only. This file is NOT used by CI.** CI uses
`claude_md/ci_review_prompt.md`.
## How to use
Read `claude_md/ci_review_prompt.md` for the complete methodology — the analysis
techniques (caller-chain, callee side-effects, cross-component data consumers,
alternative execution contexts, assumption stress-testing), the per-perspective
reviewer instructions, the review checklist, and the anti-patterns table.
Then apply that methodology with the OVERRIDES below. **Where this file
conflicts with `ci_review_prompt.md`, this file wins.**
## Overrides (this is what makes it lightweight)
### 1. Single reviewer — no team, no subagents
- Do NOT create a team, spawn subagents, or run parallel/background agents.
- Do NOT run the round-robin Debate phase or the Consensus phase.
- Instead, YOU personally apply each reviewer role from `ci_review_prompt.md`
(Design, Correctness, Cross-Component & Adversarial, Invariant Adversary,
Caller-Context, Performance, API/Compat, Serialization, Test Coverage) as
sequential *lenses* in one pass. Spend a few focused minutes per lens. Skip
lenses that plainly don't apply (e.g., Serialization when there is no on-disk
or wire-format change) and note the skip in one line.
### 2. No intermediate files
- Do NOT write `context.md`, `findings-*.md`, `consensus.md`, or
`review-findings.md`. Keep working notes in your reasoning, not on disk.
- Rationale: those files exist only so CI can recover partial results when an
ephemeral runner hits the turn limit — a local session has neither problem.
`ci_review_prompt.md` already outputs the review as its final response, so
skipping the file loses nothing here.
### 3. Right-size the effort
- Do the Codebase Context phase, but proportionally: trace the 2-3 most
load-bearing call chains and the highest-risk cross-component data consumers,
rather than exhaustively enumerating every caller 3-5 levels up.
- Prioritize the highest-signal lenses for RocksDB: **Correctness**,
**Cross-Component & Adversarial**, and **Assumption Stress-Testing**. These
catch the bugs that matter most; give them the most attention.
- Escalation clause: if a thread looks dangerous, go deep on that specific
thread even though the overall pass is modest. Modest is the default, not a cap.
### 4. Identify the review target locally
- Unlike CI, the diff is NOT pre-pasted into this prompt. Determine what to
review from the user's request against the local worktree — e.g. the current
commit (`git show`), uncommitted changes (`git diff` / `git diff --staged`),
a named commit range, or a PR — and read the changed files plus their
surrounding context directly from the repo. When in doubt, include all changes
not yet upstream, as in
`git diff "$(git merge-base upstream/main HEAD 2> /dev/null || git merge-base origin/main HEAD 2> /dev/null)"`
plus any untracked files (`git status`) that seem relevant.
## Reminder
The goal is a thorough *single* reviewer, not a 9-agent debate: depth where it
matters, brevity everywhere else.
+7 -73
View File
@@ -7,7 +7,6 @@
#include "db/blob/blob_file_partition_manager.h"
#include "db/blob/blob_index.h"
#include "db/blob/same_file_blob_reader.h"
#include "db/version_set.h"
namespace ROCKSDB_NAMESPACE {
@@ -26,86 +25,21 @@ Status BlobFetcher::FetchBlob(const Slice& user_key,
return status;
}
Status VersionBlobFetcherBase::FetchBlob(const Slice& user_key,
const BlobIndex& blob_index,
FilePrefetchBuffer* prefetch_buffer,
PinnableSlice* blob_value,
uint64_t* bytes_read) const {
const ReadOptions& read_options = this->read_options();
Status BlobFetcher::FetchBlob(const Slice& user_key,
const BlobIndex& blob_index,
FilePrefetchBuffer* prefetch_buffer,
PinnableSlice* blob_value,
uint64_t* bytes_read) const {
if (!allow_write_path_fallback_) {
assert(version_);
return version_->GetBlob(read_options, user_key, blob_index,
return version_->GetBlob(read_options_, user_key, blob_index,
prefetch_buffer, blob_value, bytes_read);
}
return BlobFilePartitionManager::ResolveBlobDirectWriteIndex(
read_options, user_key, blob_index, version_, blob_file_cache_,
read_options_, user_key, blob_index, version_, blob_file_cache_,
prefetch_buffer, blob_value, bytes_read);
}
Status VersionBlobFetcherBase::FetchBlobRange(const Slice& user_key,
const BlobIndex& blob_index,
uint64_t range_offset,
size_t range_length,
PinnableSlice* blob_value,
uint64_t* bytes_read) const {
// Only ever called when SupportsRangeRead() holds (a Version to read through,
// no direct-write fallback); the direct-write path resolves whole records and
// has no range variant.
assert(SupportsRangeRead());
assert(version_);
return version_->GetBlobRange(read_options(), user_key, blob_index,
range_offset, range_length, blob_value,
bytes_read);
}
Status VersionBlobFetcherBase::FetchBlobForceVerify(
const Slice& user_key, const BlobIndex& blob_index,
FilePrefetchBuffer* prefetch_buffer, PinnableSlice* blob_value,
uint64_t* bytes_read) const {
if (read_options().verify_checksums) {
// Verification already happens on the normal path.
return FetchBlob(user_key, blob_index, prefetch_buffer, blob_value,
bytes_read);
}
// Force verification via a transient fetcher over a verify-enabled copy of
// the read options. `verify_read_options` outlives `verifying_fetcher` (both
// are local to this call), so the borrowed-options VersionBlobFetcher is
// safe.
ReadOptions verify_read_options = read_options();
verify_read_options.verify_checksums = true;
VersionBlobFetcher verifying_fetcher(version_, verify_read_options,
blob_file_cache_,
allow_write_path_fallback_);
return verifying_fetcher.FetchBlob(user_key, blob_index, prefetch_buffer,
blob_value, bytes_read);
}
Status EmbeddedAwareBlobFetcher::FetchBlob(const Slice& user_key,
const BlobIndex& blob_index,
FilePrefetchBuffer* prefetch_buffer,
PinnableSlice* blob_value,
uint64_t* bytes_read) const {
// Only an enabled decorator is ever routed to (see EffectiveFetcher()).
assert(same_file_reader_ != nullptr);
if (blob_index.IsSameFile()) {
// Same-file ("embedded") blob records live in the current SST and are read
// by the SameFileBlobReader (the BlockBasedTable). A separate blob-file
// prefetch buffer and bytes_read counter do not apply here (embedded reads
// account their own BLOB_DB_* stats via BlobSource).
return same_file_reader_->GetSameFileBlob(read_options(), blob_index,
blob_value);
}
if (base_ == nullptr) {
return Status::Corruption(
"Cannot resolve non-same-file blob reference without a base blob "
"fetcher");
}
return base_->FetchBlob(user_key, blob_index, prefetch_buffer, blob_value,
bytes_read);
}
} // namespace ROCKSDB_NAMESPACE
+13 -195
View File
@@ -5,8 +5,6 @@
#pragma once
#include <utility>
#include "rocksdb/options.h"
#include "rocksdb/status.h"
@@ -18,212 +16,32 @@ class Slice;
class FilePrefetchBuffer;
class PinnableSlice;
class BlobIndex;
class SameFileBlobReader;
// Abstract interface for blob retrieval on the read path. An implementation
// resolves a BlobIndex to its value, pinning it into a PinnableSlice. Callers
// hold a plain const BlobFetcher* so resolution can be intercepted by a
// decorator (e.g. EmbeddedAwareBlobFetcher) without their knowledge.
// A thin wrapper around blob retrieval. By default it reads through Version,
// and it can optionally fall back to direct-write blob files that are not yet
// manifest-visible.
class BlobFetcher {
public:
virtual ~BlobFetcher() = default;
BlobFetcher(const Version* version, const ReadOptions& read_options,
BlobFileCache* blob_file_cache = nullptr,
bool allow_write_path_fallback = false)
: version_(version),
read_options_(read_options),
blob_file_cache_(blob_file_cache),
allow_write_path_fallback_(allow_write_path_fallback) {}
// Convenience overload: decodes `blob_index_slice` into a BlobIndex and
// dispatches to the virtual overload below. Non-virtual; shared by all
// implementations.
Status FetchBlob(const Slice& user_key, const Slice& blob_index_slice,
FilePrefetchBuffer* prefetch_buffer,
PinnableSlice* blob_value, uint64_t* bytes_read) const;
virtual Status FetchBlob(const Slice& user_key, const BlobIndex& blob_index,
FilePrefetchBuffer* prefetch_buffer,
PinnableSlice* blob_value,
uint64_t* bytes_read) const = 0;
// The read options this fetcher operates under. Used (via an
// EmbeddedAwareBlobFetcher decorator) to resolve same-file blob references,
// which need the current read_tier.
virtual const ReadOptions& read_options() const = 0;
};
// Shared implementation of the two Version-backed BlobFetchers below. Reads
// through a Version, optionally falling back to direct-write blob files that
// are not yet manifest-visible. Everything except the ReadOptions is stored
// here; the concrete subclass decides whether it references a caller-owned
// ReadOptions (VersionBlobFetcher) or owns its own copy
// (OwningVersionBlobFetcher). FetchBlob reads the options via the virtual
// read_options() so both storage strategies share one implementation.
class VersionBlobFetcherBase : public BlobFetcher {
public:
// Un-hide the base's Slice-based convenience overload.
using BlobFetcher::FetchBlob;
Status FetchBlob(const Slice& user_key, const BlobIndex& blob_index,
FilePrefetchBuffer* prefetch_buffer,
PinnableSlice* blob_value,
uint64_t* bytes_read) const override;
// Fetches a byte sub-range [range_offset, range_offset + range_length) of an
// *uncompressed*, separate-file blob's value into *blob_value, reading only
// those bytes on a cache miss (see Version::GetBlobRange /
// BlobSource::GetBlobRange). Only valid when SupportsRangeRead() is true (a
// Version to read through and no direct-write fallback); callers check that
// first and take the whole-value FetchBlob path otherwise. Not routed through
// the same-file (embedded) decorator -- same-file range reads are a later
// phase.
Status FetchBlobRange(const Slice& user_key, const BlobIndex& blob_index,
uint64_t range_offset, size_t range_length,
PinnableSlice* blob_value, uint64_t* bytes_read) const;
// Fetches the whole blob with checksum verification forced on, regardless of
// this fetcher's ReadOptions::verify_checksums. Used to honor a lazy read's
// force_verify when verify_checksums is off: the caller wants the record's
// checksum checked even though the global option would skip it. When
// verify_checksums is already on this is just FetchBlob.
//
// TODO(lazy-blob-resolution-cleanup): fold FetchBlobRange /
// FetchBlobForceVerify (and the whole-vs-range GetBlob twins throughout the
// blob stack) into one parameterized primitive taking a BlobReadRequest -- a
// range descriptor ({offset, len}; whole == [0, npos)) plus a 3-valued verify
// policy (must-verify-if-present / verify-if-no-amplification / ignore). That
// retires this method and the range/whole method pairs. See the lazy blob
// resolution plan (deferred for feature velocity).
Status FetchBlobForceVerify(const Slice& user_key,
const BlobIndex& blob_index,
FilePrefetchBuffer* prefetch_buffer,
PinnableSlice* blob_value,
uint64_t* bytes_read) const;
// True if this fetcher has enough context to resolve a (non-inlined,
// non-same-file) blob reference: either a Version to read through, or the
// direct-write fallback (a blob file cache) enabled. Callers that may hold a
// null Version (e.g. DBIter) can check this to surface a clean Corruption on
// an unexpected blob index instead of dereferencing null in FetchBlob.
bool CanResolve() const {
return version_ != nullptr ||
(allow_write_path_fallback_ && blob_file_cache_ != nullptr);
}
// True if this fetcher can serve an I/O-saving byte-range read: it reads
// through a Version (FetchBlobRange goes to Version::GetBlobRange) and is not
// in direct-write fallback mode (whose reads resolve whole records instead).
bool SupportsRangeRead() const {
return version_ != nullptr && !allow_write_path_fallback_;
}
protected:
VersionBlobFetcherBase(const Version* version, BlobFileCache* blob_file_cache,
bool allow_write_path_fallback)
: version_(version),
blob_file_cache_(blob_file_cache),
allow_write_path_fallback_(allow_write_path_fallback) {}
PinnableSlice* blob_value, uint64_t* bytes_read) const;
private:
const Version* version_;
ReadOptions read_options_;
BlobFileCache* blob_file_cache_;
bool allow_write_path_fallback_;
};
// The default BlobFetcher for transient/stack use: holds a reference to a
// caller-owned ReadOptions rather than a copy, avoiding a per-fetcher copy of
// the (growing) ReadOptions on the hot path. The referenced ReadOptions must
// outlive the fetcher, so this is only appropriate for fetchers whose lifetime
// is bounded by the caller's (e.g. a stack local per Get / per resolution).
// Use OwningVersionBlobFetcher for lifetime-independent fetchers.
class VersionBlobFetcher : public VersionBlobFetcherBase {
public:
VersionBlobFetcher(const Version* version, const ReadOptions& read_options,
BlobFileCache* blob_file_cache = nullptr,
bool allow_write_path_fallback = false)
: VersionBlobFetcherBase(version, blob_file_cache,
allow_write_path_fallback),
read_options_(read_options) {}
// Reject binding to a temporary ReadOptions, which would leave a dangling
// reference. Callers that cannot guarantee the ReadOptions outlives the
// fetcher must use OwningVersionBlobFetcher instead.
VersionBlobFetcher(const Version* version, ReadOptions&& read_options,
BlobFileCache* blob_file_cache = nullptr,
bool allow_write_path_fallback = false) = delete;
const ReadOptions& read_options() const override { return read_options_; }
private:
const ReadOptions& read_options_;
};
// A BlobFetcher that owns its ReadOptions, for fetchers whose lifetime is
// independent of the caller that created them (the lazy read-path resolver and
// compaction). Takes ownership of the ReadOptions by rvalue so ownership
// transfer is explicit and no hidden copy is made on the way in; later reads
// never touch caller state. Callers holding a borrowed ReadOptions they cannot
// move must make the copy explicit (e.g. ReadOptions(read_options)).
class OwningVersionBlobFetcher : public VersionBlobFetcherBase {
public:
OwningVersionBlobFetcher(const Version* version, ReadOptions&& read_options,
BlobFileCache* blob_file_cache = nullptr,
bool allow_write_path_fallback = false)
: VersionBlobFetcherBase(version, blob_file_cache,
allow_write_path_fallback),
read_options_(std::move(read_options)) {}
const ReadOptions& read_options() const override { return read_options_; }
private:
ReadOptions read_options_;
};
// A BlobFetcher decorator that resolves same-file ("embedded") blob references
// against a SameFileBlobReader (the current SST) and delegates all other
// references to a base BlobFetcher. It is cheap to construct as a stack local
// per resolution: the same-file target is per-SST while the base fetcher is one
// per-Get object shared across SSTs, so an immutable per-SST decorator avoids
// shared-mutable-state hazards under async MultiGet.
//
// A decorator is "enabled" when it has a same-file reader and "disabled"
// (unusable) when constructed with a null `same_file_reader` (e.g. via the
// default constructor). A disabled decorator must not be routed through
// directly; callers construct one unconditionally and use EffectiveFetcher(),
// which returns this decorator when enabled or the undecorated base fetcher
// otherwise. This avoids std::optional / branching at call sites while adding
// no indirection on the common (non-embedded) path.
//
// The base fetcher may be null for an entity whose blob columns are all
// same-file (no separate-file blob support wired, e.g. SstFileReader); a
// non-same-file reference then surfaces as a Corruption rather than silently.
class EmbeddedAwareBlobFetcher : public BlobFetcher {
public:
explicit EmbeddedAwareBlobFetcher(
const BlobFetcher* base = nullptr,
const SameFileBlobReader* same_file_reader = nullptr)
: base_(base), same_file_reader_(same_file_reader) {}
// The fetcher to route resolution through: this decorator when it has a
// same-file reader, otherwise the (undecorated) base fetcher. Only an enabled
// decorator's FetchBlob is ever invoked.
const BlobFetcher* EffectiveFetcher() const {
return same_file_reader_ != nullptr ? this : base_;
}
// Un-hide the base's Slice-based convenience overload.
using BlobFetcher::FetchBlob;
Status FetchBlob(const Slice& user_key, const BlobIndex& blob_index,
FilePrefetchBuffer* prefetch_buffer,
PinnableSlice* blob_value,
uint64_t* bytes_read) const override;
const ReadOptions& read_options() const override {
// Same-file resolution uses the base fetcher's read options; when there is
// no base (e.g. SstFileReader) a default (kReadAllTier) suffices.
static const ReadOptions kDefaultReadOptions;
return base_ != nullptr ? base_->read_options() : kDefaultReadOptions;
}
private:
const BlobFetcher* base_;
// Null iff this decorator is disabled (see class comment); otherwise the
// same-file blob reader for the current SST.
const SameFileBlobReader* same_file_reader_;
};
} // namespace ROCKSDB_NAMESPACE
+19 -30
View File
@@ -41,14 +41,14 @@ BlobFileBuilder::BlobFileBuilder(
const std::shared_ptr<IOTracer>& io_tracer,
BlobFileCompletionCallback* blob_callback,
BlobFileCreationReason creation_reason,
std::vector<std::string>* output_file_paths,
std::vector<std::string>* blob_file_paths,
std::vector<BlobFileAddition>* blob_file_additions)
: BlobFileBuilder([versions]() { return versions->NewFileNumber(); }, fs,
immutable_options, mutable_cf_options, file_options,
write_options, db_id, db_session_id, job_id,
column_family_id, column_family_name, write_hint,
io_tracer, blob_callback, creation_reason,
output_file_paths, blob_file_additions) {}
blob_file_paths, blob_file_additions) {}
BlobFileBuilder::BlobFileBuilder(
std::function<uint64_t()> file_number_generator, FileSystem* fs,
@@ -60,15 +60,13 @@ BlobFileBuilder::BlobFileBuilder(
const std::shared_ptr<IOTracer>& io_tracer,
BlobFileCompletionCallback* blob_callback,
BlobFileCreationReason creation_reason,
std::vector<std::string>* output_file_paths,
std::vector<std::string>* blob_file_paths,
std::vector<BlobFileAddition>* blob_file_additions)
: file_number_generator_(std::move(file_number_generator)),
fs_(fs),
immutable_options_(immutable_options),
min_blob_size_(mutable_cf_options->min_blob_size),
blob_file_size_(mutable_cf_options->blob_file_size),
blob_file_writable_file_max_buffer_size_(
mutable_cf_options->blob_file_writable_file_max_buffer_size),
blob_compression_type_(mutable_cf_options->blob_compression_type),
// TODO with schema change: support custom compression manager and options
// such as max_compressed_bytes_per_kb
@@ -90,7 +88,7 @@ BlobFileBuilder::BlobFileBuilder(
io_tracer_(io_tracer),
blob_callback_(blob_callback),
creation_reason_(creation_reason),
output_file_paths_(output_file_paths),
blob_file_paths_(blob_file_paths),
blob_file_additions_(blob_file_additions),
blob_count_(0),
blob_bytes_(0) {
@@ -99,21 +97,14 @@ BlobFileBuilder::BlobFileBuilder(
assert(immutable_options_);
assert(file_options_);
assert(write_options_);
assert(output_file_paths_);
assert(output_file_paths_->empty());
assert(blob_file_paths_);
assert(blob_file_paths_->empty());
assert(blob_file_additions_);
assert(blob_file_additions_->empty());
}
BlobFileBuilder::~BlobFileBuilder() = default;
std::string BlobFileBuilder::GetBlobFilePath(uint64_t blob_file_number) const {
assert(immutable_options_);
assert(!immutable_options_->cf_paths.empty());
return BlobFileName(immutable_options_->cf_paths.front().path,
blob_file_number);
}
Status BlobFileBuilder::Add(const Slice& key, const Slice& value,
std::string* blob_index) {
assert(blob_index);
@@ -195,7 +186,10 @@ Status BlobFileBuilder::OpenBlobFileIfNeeded() {
assert(file_number_generator_);
const uint64_t blob_file_number = file_number_generator_();
std::string blob_file_path = GetBlobFilePath(blob_file_number);
assert(immutable_options_);
assert(!immutable_options_->cf_paths.empty());
std::string blob_file_path =
BlobFileName(immutable_options_->cf_paths.front().path, blob_file_number);
if (blob_callback_) {
blob_callback_->OnBlobFileCreationStarted(
@@ -210,10 +204,6 @@ Status BlobFileBuilder::OpenBlobFileIfNeeded() {
fo_copy.open_contract = FileOpenContract::kNoReopenForWrite |
FileOpenContract::kNoReadersWhileOpenForWrite;
fo_copy.write_hint = write_hint_;
if (blob_file_writable_file_max_buffer_size_ > 0) {
fo_copy.writable_file_max_buffer_size =
blob_file_writable_file_max_buffer_size_;
}
Status s = NewWritableFile(fs_, blob_file_path, &file, fo_copy);
TEST_SYNC_POINT_CALLBACK(
@@ -224,11 +214,11 @@ Status BlobFileBuilder::OpenBlobFileIfNeeded() {
}
}
// Note: blob files get added to output_file_paths_ right after the open, so
// they can be cleaned up upon failure. Contrast this with
// blob_file_additions_, which only contains successfully written files.
assert(output_file_paths_);
output_file_paths_->emplace_back(std::move(blob_file_path));
// Note: files get added to blob_file_paths_ right after the open, so they
// can be cleaned up upon failure. Contrast this with blob_file_additions_,
// which only contains successfully written files.
assert(blob_file_paths_);
blob_file_paths_->emplace_back(std::move(blob_file_path));
assert(file);
file->SetIOPriority(write_options_->rate_limiter_priority);
@@ -238,7 +228,7 @@ Status BlobFileBuilder::OpenBlobFileIfNeeded() {
FileTypeSet tmp_set = immutable_options_->checksum_handoff_file_types;
Statistics* const statistics = immutable_options_->stats;
std::unique_ptr<WritableFileWriter> file_writer(new WritableFileWriter(
std::move(file), output_file_paths_->back(), fo_copy,
std::move(file), blob_file_paths_->back(), *file_options_,
immutable_options_->clock, io_tracer_, statistics,
Histograms::BLOB_DB_BLOB_FILE_WRITE_MICROS, immutable_options_->listeners,
immutable_options_->file_checksum_gen_factory.get(),
@@ -351,7 +341,7 @@ Status BlobFileBuilder::CloseBlobFile() {
if (blob_callback_) {
s = blob_callback_->OnBlobFileCompleted(
GetBlobFilePath(blob_file_number), column_family_name_, job_id_,
blob_file_paths_->back(), column_family_name_, job_id_,
blob_file_number, creation_reason_, s, checksum_value, checksum_method,
blob_count_, blob_bytes_);
}
@@ -395,10 +385,9 @@ void BlobFileBuilder::Abandon(const Status& s) {
if (blob_callback_) {
// BlobFileBuilder::Abandon() is called because of error while writing to
// Blob files. So we can ignore the below error.
const uint64_t blob_file_number = writer_->get_log_number();
blob_callback_
->OnBlobFileCompleted(GetBlobFilePath(blob_file_number),
column_family_name_, job_id_, blob_file_number,
->OnBlobFileCompleted(blob_file_paths_->back(), column_family_name_,
job_id_, writer_->get_log_number(),
creation_reason_, s, "", "", blob_count_,
blob_bytes_)
.PermitUncheckedError();
+3 -5
View File
@@ -48,7 +48,7 @@ class BlobFileBuilder {
const std::shared_ptr<IOTracer>& io_tracer,
BlobFileCompletionCallback* blob_callback,
BlobFileCreationReason creation_reason,
std::vector<std::string>* output_file_paths,
std::vector<std::string>* blob_file_paths,
std::vector<BlobFileAddition>* blob_file_additions);
BlobFileBuilder(std::function<uint64_t()> file_number_generator,
@@ -63,7 +63,7 @@ class BlobFileBuilder {
const std::shared_ptr<IOTracer>& io_tracer,
BlobFileCompletionCallback* blob_callback,
BlobFileCreationReason creation_reason,
std::vector<std::string>* output_file_paths,
std::vector<std::string>* blob_file_paths,
std::vector<BlobFileAddition>* blob_file_additions);
BlobFileBuilder(const BlobFileBuilder&) = delete;
@@ -76,7 +76,6 @@ class BlobFileBuilder {
void Abandon(const Status& s);
private:
std::string GetBlobFilePath(uint64_t blob_file_number) const;
bool IsBlobFileOpen() const;
Status OpenBlobFileIfNeeded();
Status CompressBlobIfNeeded(Slice* blob,
@@ -94,7 +93,6 @@ class BlobFileBuilder {
const ImmutableOptions* immutable_options_;
uint64_t min_blob_size_;
uint64_t blob_file_size_;
uint64_t blob_file_writable_file_max_buffer_size_;
CompressionType blob_compression_type_;
std::unique_ptr<Compressor> blob_compressor_;
mutable Compressor::ManagedWorkingArea blob_compressor_wa_;
@@ -110,7 +108,7 @@ class BlobFileBuilder {
std::shared_ptr<IOTracer> io_tracer_;
BlobFileCompletionCallback* blob_callback_;
BlobFileCreationReason creation_reason_;
std::vector<std::string>* output_file_paths_;
std::vector<std::string>* blob_file_paths_;
std::vector<BlobFileAddition>* blob_file_additions_;
std::unique_ptr<BlobLogWriter> writer_;
uint64_t blob_count_;
+1 -8
View File
@@ -100,8 +100,7 @@ BlobFilePartitionManager::BlobFilePartitionManager(
FileNumberAllocator file_number_allocator, FileSystem* fs,
SystemClock* clock, Statistics* statistics, const FileOptions& file_options,
std::string db_path, std::string column_family_name,
uint64_t blob_file_size, bool use_fsync,
uint64_t blob_writer_max_buffer_size, BlobFileCache* blob_file_cache,
uint64_t blob_file_size, bool use_fsync, BlobFileCache* blob_file_cache,
BlobFileCompletionCallback* blob_callback,
const std::vector<std::shared_ptr<EventListener>>& listeners,
FileChecksumGenFactory* file_checksum_gen_factory,
@@ -121,7 +120,6 @@ BlobFilePartitionManager::BlobFilePartitionManager(
column_family_name_(std::move(column_family_name)),
blob_file_size_(blob_file_size),
use_fsync_(use_fsync),
blob_writer_max_buffer_size_(blob_writer_max_buffer_size),
blob_file_cache_(blob_file_cache),
blob_callback_(blob_callback),
listeners_(listeners),
@@ -204,11 +202,6 @@ Status BlobFilePartitionManager::OpenNewBlobFile(Partition* partition,
std::unique_ptr<FSWritableFile> file;
FileOptions writer_file_options = file_options_;
writer_file_options.open_contract = FileOpenContract::kNoReopenForWrite;
const uint64_t max_buffer_size =
blob_writer_max_buffer_size_.load(std::memory_order_relaxed);
if (max_buffer_size > 0) {
writer_file_options.writable_file_max_buffer_size = max_buffer_size;
}
Status s = NewWritableFile(fs_, blob_file_path, &file, writer_file_options);
if (!s.ok()) {
RemoveFilePartitionMapping(blob_file_number);
+1 -9
View File
@@ -4,7 +4,6 @@
// (found in the LICENSE.Apache file in the root directory).
#pragma once
#include <atomic>
#include <cstdint>
#include <deque>
#include <functional>
@@ -62,8 +61,7 @@ class BlobFilePartitionManager {
SystemClock* clock, Statistics* statistics,
const FileOptions& file_options, std::string db_path,
std::string column_family_name, uint64_t blob_file_size, bool use_fsync,
uint64_t blob_writer_max_buffer_size, BlobFileCache* blob_file_cache,
BlobFileCompletionCallback* blob_callback,
BlobFileCache* blob_file_cache, BlobFileCompletionCallback* blob_callback,
const std::vector<std::shared_ptr<EventListener>>& listeners,
FileChecksumGenFactory* file_checksum_gen_factory,
const FileTypeSet& checksum_handoff_file_types,
@@ -131,11 +129,6 @@ class BlobFilePartitionManager {
// protected by a live memtable / old SuperVersion.
bool IsTrackedBlobFileNumber(uint64_t file_number) const;
void SetBlobWriterMaxBufferSize(uint64_t blob_writer_max_buffer_size) {
blob_writer_max_buffer_size_.store(blob_writer_max_buffer_size,
std::memory_order_relaxed);
}
// Increments / decrements memtable-held protection on sealed blob files.
void ProtectSealedBlobFileNumbers(const std::vector<uint64_t>& file_numbers);
void UnprotectSealedBlobFileNumbers(
@@ -267,7 +260,6 @@ class BlobFilePartitionManager {
// File creation policy and shared blob-file infrastructure.
uint64_t blob_file_size_;
bool use_fsync_;
std::atomic<uint64_t> blob_writer_max_buffer_size_;
BlobFileCache* blob_file_cache_;
BlobFileCompletionCallback* blob_callback_;
std::vector<std::shared_ptr<EventListener>> listeners_;
-71
View File
@@ -416,77 +416,6 @@ Status BlobFileReader::GetBlob(
return Status::OK();
}
Status BlobFileReader::GetBlobRange(const ReadOptions& read_options,
const Slice& user_key, uint64_t offset,
uint64_t value_size, uint64_t range_offset,
size_t range_length,
MemoryAllocator* allocator,
std::unique_ptr<BlobContents>* result,
uint64_t* bytes_read) const {
assert(result);
// Partial reads are only meaningful for uncompressed blobs: a strict
// sub-range of a compressed record cannot be decompressed in isolation.
// Callers (BlobSource::GetBlobRange) must ensure this; enforce it here too.
if (compression_type_ != kNoCompression) {
return Status::Corruption("Cannot range-read a compressed blob");
}
const uint64_t key_size = user_key.size();
// Validate that the full value region is within the file (same check GetBlob
// performs); this guards the sub-range read below.
if (!IsValidBlobOffset(offset, key_size, value_size, file_size_,
has_footer_)) {
return Status::Corruption("Invalid blob offset");
}
// The requested sub-range must lie within the value.
if (range_offset > value_size || range_length > value_size - range_offset) {
return Status::InvalidArgument("Blob range out of bounds");
}
// Read only the requested bytes, at the value's file position plus the range
// offset. Unlike GetBlob there is no record-header adjustment (we do not read
// the key/header) and no whole-record checksum verification (a strict
// sub-range cannot cover it -- callers that require verification take the
// full-read path instead).
const uint64_t read_offset = offset + range_offset;
const size_t read_size = range_length;
Slice range_slice;
Buffer buf;
AlignedBuffer direct_io_buffer;
TEST_SYNC_POINT("BlobFileReader::GetBlobRange:ReadFromFile");
PERF_COUNTER_ADD(blob_read_count, 1);
PERF_COUNTER_ADD(blob_read_byte, read_size);
PERF_TIMER_GUARD(blob_read_time);
{
const Status s =
ReadFromFile(file_reader_.get(), read_options, read_offset, read_size,
statistics_, &range_slice, &buf, &direct_io_buffer);
if (!s.ok()) {
return s;
}
}
TEST_SYNC_POINT_CALLBACK("BlobFileReader::GetBlobRange:TamperWithResult",
&range_slice);
// The blob is uncompressed, so the bytes read are the requested value bytes;
// copy them into an owned BlobContents (no decompression).
BlobContentsCreator::Create(result, /*out_charge=*/nullptr, range_slice,
kNoCompression, allocator);
if (bytes_read) {
*bytes_read = read_size;
}
return Status::OK();
}
void BlobFileReader::MultiGetBlob(
const ReadOptions& read_options, MemoryAllocator* allocator,
autovector<std::pair<BlobReadRequest*, std::unique_ptr<BlobContents>>>&
-17
View File
@@ -64,23 +64,6 @@ class BlobFileReader {
std::unique_ptr<BlobContents>* result,
uint64_t* bytes_read) const;
// Reads a byte sub-range [range_offset, range_offset + range_length) of an
// *uncompressed* blob's value directly from the file, reading only those
// bytes. Unlike GetBlob it does not read the record header/key, does not
// verify the whole-record checksum (a strict sub-range cannot cover it), and
// never decompresses -- so it is only valid when this reader's blob file is
// uncompressed (checked). `offset` and `value_size` are the blob value's file
// offset and full size (from the BlobIndex); the caller must ensure
// range_offset + range_length <= value_size. On success `*result` owns a copy
// of the requested bytes and `*bytes_read` (when non-null) is the number of
// bytes read from the file.
Status GetBlobRange(const ReadOptions& read_options, const Slice& user_key,
uint64_t offset, uint64_t value_size,
uint64_t range_offset, size_t range_length,
MemoryAllocator* allocator,
std::unique_ptr<BlobContents>* result,
uint64_t* bytes_read) const;
// offsets must be sorted in ascending order by caller.
void MultiGetBlob(
const ReadOptions& read_options, MemoryAllocator* allocator,
-48
View File
@@ -76,54 +76,6 @@ Status ReadAndVerifySimpleGen2BlobRecord(
return Status::OK();
}
Status ReadSimpleGen2BlobRange(const ReadOptions& read_options,
RandomAccessFileReader* file,
uint64_t record_offset, size_t payload_size,
uint64_t range_offset, size_t range_length,
CompressionType expected_compression,
char* buf) {
assert(file != nullptr);
assert(buf != nullptr);
// A strict sub-range of a compressed payload cannot be decompressed in
// isolation; callers resolve such payloads whole and slice instead.
if (expected_compression != kNoCompression) {
return Status::Corruption("Cannot range-read a compressed blob");
}
// The requested sub-range must lie within the payload (the trailer that
// follows the payload is never part of a range read).
if (range_offset > payload_size ||
range_length > payload_size - range_offset) {
return Status::InvalidArgument("Blob range out of bounds");
}
Slice result;
IOOptions opts;
IODebugContext dbg;
Status s = file->PrepareIOOptions(read_options, opts, &dbg);
if (s.ok()) {
s = file->Read(opts, record_offset + range_offset, range_length, &result,
buf, nullptr, &dbg);
}
if (!s.ok()) {
return s;
}
if (result.size() != range_length) {
return Status::Corruption("Could not read complete blob range");
}
// With mmap reads the data lands outside `buf`; copy it in so the caller can
// rely on `buf` owning the bytes (the only copy on the mmap path).
if (result.data() != buf) {
memcpy(buf, result.data(), range_length);
}
// No trailer read and no checksum verification: a strict sub-range cannot
// cover the record's checksum (callers that require it read the whole
// record).
return Status::OK();
}
IOStatus WriteSimpleGen2BlobRecord(WritableFileWriter* file,
const WriteOptions& write_options,
ChecksumType checksum_type,
-18
View File
@@ -73,24 +73,6 @@ Status ReadAndVerifySimpleGen2BlobRecord(
ChecksumType checksum_type, uint32_t base_context_checksum,
CompressionType expected_compression, char* buf);
// Reads a byte sub-range [range_offset, range_offset + range_length) of an
// *uncompressed* SimpleGen2Blob payload directly into `buf` (capacity >=
// range_length), reading only those bytes. Unlike
// ReadAndVerifySimpleGen2BlobRecord it does not read the trailer and does not
// verify the record's checksum (a strict sub-range cannot cover it); callers
// that require verification read the whole record instead. `payload_size` is
// the full payload size (from the blob index); the caller must ensure
// range_offset + range_length <= payload_size. `expected_compression` must be
// kNoCompression (a strict sub-range of a compressed payload cannot be
// decompressed in isolation).
//
// On success, buf[0, range_length) holds the requested payload bytes.
Status ReadSimpleGen2BlobRange(const ReadOptions& read_options,
RandomAccessFileReader* file,
uint64_t record_offset, size_t payload_size,
uint64_t range_offset, size_t range_length,
CompressionType expected_compression, char* buf);
// Writes a SimpleGen2Blob record for `payload` at the current end of `file`,
// which the caller asserts is byte offset `record_offset`. Appends the payload
// bytes followed by the 5-byte trailer (compression marker + context-modified
+48 -283
View File
@@ -36,102 +36,6 @@ Status AppendBlobRefreshRetryFailure(const Status& stale_status,
stale_status, "; refresh retry failed: ", retry_status.ToString());
}
// Runs read(reader) against the blob-file reader for `file_number`. On a
// Corruption -- which a stale cached reader (e.g. the physical file was
// replaced) can surface -- evicts the cached reader, reopens it uncached,
// retries read() once, and refreshes the cache on success. Shared by the
// single-blob read paths (GetBlob / GetBlobRange) so the stale-file recovery
// lives in one place.
//
// `read` is invoked with a BlobFileReader* and returns a Status; because it may
// run twice, it must re-initialize any output it populates on each call (and is
// taken by const reference rather than forwarded, since it is not moved-from).
template <typename ReadFn>
Status ReadBlobWithReaderRetry(BlobFileCache* blob_file_cache,
const ReadOptions& read_options,
uint64_t file_number, const ReadFn& read) {
CacheHandleGuard<BlobFileReader> blob_file_reader;
Status s = blob_file_cache->GetBlobFileReader(read_options, file_number,
&blob_file_reader);
if (!s.ok()) {
return s;
}
assert(blob_file_reader.GetValue());
s = read(blob_file_reader.GetValue());
if (!s.IsCorruption()) {
return s;
}
const Status stale_status = s;
blob_file_reader.Reset();
blob_file_cache->Evict(file_number);
std::unique_ptr<BlobFileReader> fresh_reader;
s = blob_file_cache->OpenBlobFileReaderUncached(
read_options, file_number, &fresh_reader,
/*allow_footer_skip_retry=*/false);
if (!s.ok()) {
return AppendBlobRefreshRetryFailure(stale_status, s);
}
s = read(fresh_reader.get());
if (!s.ok()) {
return AppendBlobRefreshRetryFailure(stale_status, s);
}
CacheHandleGuard<BlobFileReader> ignored_reader;
blob_file_cache
->RefreshBlobFileReader(file_number, &fresh_reader, &ignored_reader)
.PermitUncheckedError();
return s;
}
// Records lazy wide-column read metrics for one actual storage read issued
// while resolving a lazy result (attributed via Env::IOActivity::kLazyResolve):
// `bytes_read` bytes were read from storage. Covers both whole-column and
// partial reads; not called for cache hits (no storage read).
void RecordLazyRead(Statistics* statistics, uint64_t bytes_read) {
RecordTick(statistics, BLOB_DB_LAZY_READ_COUNT);
RecordTick(statistics, BLOB_DB_LAZY_READ_BYTES, bytes_read);
}
// Additionally records the partial-read metrics for one actual partial
// (byte-range) read: `bytes_read` bytes were fetched instead of the column's
// full `value_size`. Call alongside RecordLazyRead (a partial read is also a
// lazy read).
void RecordLazyPartialRead(Statistics* statistics, uint64_t bytes_read,
uint64_t value_size) {
RecordTick(statistics, BLOB_DB_LAZY_PARTIAL_READ_COUNT);
if (value_size > bytes_read) {
RecordTick(statistics, BLOB_DB_LAZY_PARTIAL_BYTES_SAVED,
value_size - bytes_read);
}
}
// Pins the sub-range [range_offset, range_offset + range_length) of a cache-hit
// whole blob value into *value (clamped: an offset at/past the end yields
// empty, length is clamped to the remainder), keeping the cached bytes alive by
// transferring the cache handle into *value. Shared by the range-read cache-hit
// paths (GetBlobRange / GetSimpleGen2BlobRange).
void PinCacheHitSubRange(CacheHandleGuard<BlobContents>* blob_handle,
uint64_t range_offset, size_t range_length,
PinnableSlice* value) {
const Slice full = blob_handle->GetValue()->data();
Slice sub;
if (range_offset < full.size()) {
const size_t off = static_cast<size_t>(range_offset);
const size_t avail = full.size() - off;
const size_t len = range_length > avail ? avail : range_length;
sub = Slice(full.data() + off, len);
} // else: offset at/past end -> empty (not an error)
value->Reset();
constexpr Cleanable* cleanable = nullptr;
value->PinSlice(sub, cleanable);
blob_handle->TransferTo(value);
}
} // namespace
BlobSource::BlobSource(const ImmutableOptions& immutable_options,
@@ -324,37 +228,66 @@ Status BlobSource::GetBlob(const ReadOptions& read_options,
std::unique_ptr<BlobContents> blob_contents;
{
CacheHandleGuard<BlobFileReader> blob_file_reader;
s = blob_file_cache_->GetBlobFileReader(read_options, file_number,
&blob_file_reader);
if (!s.ok()) {
return s;
}
assert(blob_file_reader.GetValue());
if (compression_type != blob_file_reader.GetValue()->GetCompressionType()) {
return Status::Corruption("Compression type mismatch when reading blob");
}
MemoryAllocator* const allocator =
(blob_cache_ && read_options.fill_cache)
? blob_cache_.get()->memory_allocator()
: nullptr;
uint64_t read_size = 0;
s = ReadBlobWithReaderRetry(
blob_file_cache_, read_options, file_number,
[&](BlobFileReader* reader) {
if (compression_type != reader->GetCompressionType()) {
return Status::Corruption(
"Compression type mismatch when reading blob");
}
blob_contents.reset();
read_size = 0;
return reader->GetBlob(read_options, user_key, offset, value_size,
compression_type, prefetch_buffer, allocator,
&blob_contents, &read_size);
});
s = blob_file_reader.GetValue()->GetBlob(
read_options, user_key, offset, value_size, compression_type,
prefetch_buffer, allocator, &blob_contents, &read_size);
if (s.IsCorruption()) {
const Status stale_status = s;
blob_file_reader.Reset();
blob_file_cache_->Evict(file_number);
std::unique_ptr<BlobFileReader> fresh_reader;
s = blob_file_cache_->OpenBlobFileReaderUncached(
read_options, file_number, &fresh_reader,
/*allow_footer_skip_retry=*/false);
if (!s.ok()) {
return AppendBlobRefreshRetryFailure(stale_status, s);
}
if (compression_type != fresh_reader->GetCompressionType()) {
return Status::Corruption(
"Compression type mismatch when reading blob");
}
blob_contents.reset();
read_size = 0;
s = fresh_reader->GetBlob(read_options, user_key, offset, value_size,
compression_type, prefetch_buffer, allocator,
&blob_contents, &read_size);
if (!s.ok()) {
s = AppendBlobRefreshRetryFailure(stale_status, s);
} else {
CacheHandleGuard<BlobFileReader> ignored_reader;
blob_file_cache_
->RefreshBlobFileReader(file_number, &fresh_reader, &ignored_reader)
.PermitUncheckedError();
}
}
if (!s.ok()) {
return s;
}
if (bytes_read) {
*bytes_read = read_size;
}
// Whole-column read on the lazy resolve path (partial reads go through
// GetBlobRange). Counts the storage read; partial reads are not counted
// here.
if (read_options.io_activity == Env::IOActivity::kLazyResolve) {
RecordLazyRead(statistics_, read_size);
}
}
if (blob_cache_ && read_options.fill_cache) {
@@ -375,92 +308,6 @@ Status BlobSource::GetBlob(const ReadOptions& read_options,
return s;
}
Status BlobSource::GetBlobRange(const ReadOptions& read_options,
const Slice& user_key, uint64_t file_number,
uint64_t offset, uint64_t file_size,
uint64_t value_size,
CompressionType compression_type,
uint64_t range_offset, size_t range_length,
PinnableSlice* value, uint64_t* bytes_read) {
assert(value);
// Partial reads are for uncompressed blobs only; the caller decides this (a
// compressed column takes the whole-value GetBlob path and slices).
assert(compression_type == kNoCompression);
// Range reads are (currently) only issued while resolving a lazy result, so
// the lazy read stats below are recorded unconditionally (unlike GetBlob,
// which gates on the activity). Enforce that invariant here.
assert(read_options.io_activity == Env::IOActivity::kLazyResolve);
Status s;
const CacheKey cache_key = GetCacheKey(file_number, file_size, offset);
CacheHandleGuard<BlobContents> blob_handle;
// First, probe the blob cache for the whole value. On a hit, slice the
// requested sub-range out of the cached value while pinning the cache handle
// (zero-copy, no disk read). A partial read never inserts into the cache.
if (blob_cache_) {
Slice key = cache_key.AsSlice();
s = GetBlobFromCache(key, &blob_handle);
if (s.ok()) {
PinCacheHitSubRange(&blob_handle, range_offset, range_length, value);
if (bytes_read) {
*bytes_read = 0; // served from cache; no disk read
}
return s;
}
}
assert(blob_handle.IsEmpty());
const bool no_io = read_options.read_tier == kBlockCacheTier;
if (no_io) {
return Status::Incomplete("Cannot read blob(s): no disk I/O allowed");
}
// Cache miss: read only the requested sub-range from the file. The result is
// never inserted into the blob cache (see the header comment).
std::unique_ptr<BlobContents> blob_contents;
{
// No cache-fill allocator: a partial value is never inserted into the
// cache.
constexpr MemoryAllocator* allocator = nullptr;
uint64_t read_size = 0;
// Reuses the stale-reader retry shared with GetBlob. A range read skips
// whole-record checksum verification, so the retry handles the stale-file
// case (offset/size mismatch surfacing as Corruption), not a payload
// checksum failure.
s = ReadBlobWithReaderRetry(
blob_file_cache_, read_options, file_number,
[&](BlobFileReader* reader) {
if (compression_type != reader->GetCompressionType()) {
return Status::Corruption(
"Compression type mismatch when reading blob");
}
blob_contents.reset();
read_size = 0;
return reader->GetBlobRange(read_options, user_key, offset,
value_size, range_offset, range_length,
allocator, &blob_contents, &read_size);
});
if (!s.ok()) {
return s;
}
if (bytes_read) {
*bytes_read = read_size;
}
RecordLazyRead(statistics_, read_size);
RecordLazyPartialRead(statistics_, read_size, value_size);
}
PinOwnedBlob(&blob_contents, value);
assert(s.ok());
return s;
}
Status BlobSource::GetSimpleGen2Blob(
const ReadOptions& read_options, const OffsetableCacheKey& base_cache_key,
RandomAccessFileReader* file, uint64_t record_offset, uint64_t payload_size,
@@ -532,11 +379,6 @@ Status BlobSource::GetSimpleGen2Blob(
if (bytes_read) {
*bytes_read = record_size;
}
// Whole-column read on the lazy resolve path (partial reads go through
// GetSimpleGen2BlobRange).
if (read_options.io_activity == Env::IOActivity::kLazyResolve) {
RecordLazyRead(statistics_, record_size);
}
if (blob_cache_ && read_options.fill_cache) {
// If filling cache is allowed and a cache is configured, try to put the
@@ -556,83 +398,6 @@ Status BlobSource::GetSimpleGen2Blob(
return s;
}
Status BlobSource::GetSimpleGen2BlobRange(
const ReadOptions& read_options, const OffsetableCacheKey& base_cache_key,
RandomAccessFileReader* file, uint64_t record_offset, uint64_t payload_size,
ChecksumType /*checksum_type*/, uint32_t /*base_context_checksum*/,
CompressionType expected_compression, uint64_t range_offset,
size_t range_length, PinnableSlice* value, uint64_t* bytes_read) {
assert(value);
assert(file);
// Partial reads are for uncompressed payloads only; the caller decides this
// (a compressed column takes the whole-payload GetSimpleGen2Blob path +
// slice).
assert(expected_compression == kNoCompression);
// Range reads are (currently) only issued while resolving a lazy result, so
// the lazy read stats below are recorded unconditionally (unlike
// GetSimpleGen2Blob, which gates on the activity). Enforce that invariant
// here.
assert(read_options.io_activity == Env::IOActivity::kLazyResolve);
const CacheKey cache_key =
GetSimpleGen2BlobCacheKey(base_cache_key, record_offset);
Status s;
CacheHandleGuard<BlobContents> blob_handle;
// First, probe the blob cache for the whole payload. On a hit, slice the
// requested sub-range out of the cached payload while pinning the cache
// handle (zero-copy, no disk read). A partial read never inserts into the
// cache.
if (blob_cache_) {
Slice key = cache_key.AsSlice();
s = GetBlobFromCache(key, &blob_handle);
if (s.ok()) {
PinCacheHitSubRange(&blob_handle, range_offset, range_length, value);
if (bytes_read) {
*bytes_read = 0; // served from cache; no disk read
}
return s;
}
}
assert(blob_handle.IsEmpty());
const bool no_io = read_options.read_tier == kBlockCacheTier;
if (no_io) {
return Status::Incomplete("Cannot read blob(s): no disk I/O allowed");
}
// Cache miss: read only the requested sub-range from the file. The result is
// never inserted into the blob cache (a partial payload cannot represent the
// whole-record cache entry).
CacheAllocationPtr buf = AllocateBlock(range_length, /*allocator=*/nullptr);
s = ReadSimpleGen2BlobRange(read_options, file, record_offset,
static_cast<size_t>(payload_size), range_offset,
range_length, expected_compression, buf.get());
if (!s.ok()) {
return s;
}
std::unique_ptr<BlobContents> blob_contents(
new BlobContents(std::move(buf), range_length));
RecordTick(statistics_, BLOB_DB_BLOB_FILE_BYTES_READ, range_length);
PERF_COUNTER_ADD(blob_read_count, 1);
PERF_COUNTER_ADD(blob_read_byte, range_length);
RecordLazyRead(statistics_, range_length);
RecordLazyPartialRead(statistics_, range_length, payload_size);
if (bytes_read) {
*bytes_read = range_length;
}
PinOwnedBlob(&blob_contents, value);
assert(s.ok());
return s;
}
void BlobSource::MultiGetBlob(const ReadOptions& read_options,
autovector<BlobFileReadRequests>& blob_reqs,
uint64_t* bytes_read) {
-50
View File
@@ -61,31 +61,6 @@ class BlobSource {
FilePrefetchBuffer* prefetch_buffer, PinnableSlice* value,
uint64_t* bytes_read);
// Reads a byte sub-range [range_offset, range_offset + range_length) of an
// *uncompressed* blob's value, reading only those bytes on a cache miss.
//
// First probes the blob cache for the whole value. On a hit, pins the cache
// handle into *value and points it at the requested sub-range (zero-copy, no
// disk I/O). On a miss, reads only the requested bytes from the blob file
// (via BlobFileReader::GetBlobRange -- no record-header/key read and no
// whole-record checksum verification) and pins the owned buffer into *value.
//
// Unlike GetBlob, a partial read never inserts into the blob cache: the cache
// entry is keyed per (file, offset) and holds the *whole* BlobContents, so a
// partial value would violate that invariant. `compression_type` must be
// kNoCompression (a strict sub-range of a compressed blob cannot be
// decompressed in isolation); callers that need a compressed column, a
// whole-column read, or checksum verification use GetBlob and slice instead.
//
// The caller must ensure range_offset + range_length <= value_size. On a miss
// *bytes_read (when non-null) is the number of bytes read from the file; on a
// hit it is 0.
Status GetBlobRange(const ReadOptions& read_options, const Slice& user_key,
uint64_t file_number, uint64_t offset, uint64_t file_size,
uint64_t value_size, CompressionType compression_type,
uint64_t range_offset, size_t range_length,
PinnableSlice* value, uint64_t* bytes_read);
// Reads a SimpleGen2Blob payload (see db/blob/blob_gen2_format.h) through the
// blob value cache and BLOB_DB_* statistics. This is the counterpart to
// GetBlob() for the second-generation blob record format, which is read
@@ -121,31 +96,6 @@ class BlobSource {
CompressionType expected_compression,
PinnableSlice* value, uint64_t* bytes_read);
// Reads a byte sub-range [range_offset, range_offset + range_length) of an
// *uncompressed* SimpleGen2Blob payload, reading only those bytes on a cache
// miss. This is the embedded (same-file) counterpart of GetBlobRange().
//
// First probes the blob cache for the whole payload (keyed exactly as
// GetSimpleGen2Blob). On a hit, pins the cache handle into *value and points
// it at the requested sub-range (zero-copy, no disk I/O). On a miss, reads
// only the requested bytes from the file (via ReadSimpleGen2BlobRange -- no
// trailer read and no checksum verification) and pins the owned buffer.
//
// Like GetBlobRange, a partial read never inserts into the blob cache (the
// cache entry holds the whole payload). `expected_compression` must be
// kNoCompression. The caller must ensure range_offset + range_length <=
// payload_size. On a miss *bytes_read (when non-null) is the number of bytes
// read from the file; on a hit it is 0.
Status GetSimpleGen2BlobRange(const ReadOptions& read_options,
const OffsetableCacheKey& base_cache_key,
RandomAccessFileReader* file,
uint64_t record_offset, uint64_t payload_size,
ChecksumType checksum_type,
uint32_t base_context_checksum,
CompressionType expected_compression,
uint64_t range_offset, size_t range_length,
PinnableSlice* value, uint64_t* bytes_read);
// Read multiple blobs from the underlying cache or blob file(s).
//
// If successful, returns ok and sets "result" in the elements of "blob_reqs"
+3 -2
View File
@@ -215,10 +215,11 @@ Status BlobWriteBatchTransformer::PutEntityCF(uint32_t column_family_id,
output_batch_, column_family_id, key, entity);
}
Slice entity_ref = entity;
std::vector<WideColumn> columns;
std::vector<std::pair<size_t, BlobIndex>> existing_blob_columns;
Status status = WideColumnSerialization::Deserialize(entity, columns,
&existing_blob_columns);
Status status = WideColumnSerialization::DeserializeV2(entity_ref, columns,
existing_blob_columns);
if (status.ok()) {
// Reject pre-serialized entities that already contain blob references.
// Passing them through would preserve references to blob files outside this
-71
View File
@@ -5,8 +5,6 @@
#include <algorithm>
#include <array>
#include <atomic>
#include <cstdint>
#include <set>
#include <sstream>
#include <string>
@@ -65,75 +63,6 @@ TEST_F(DBBlobBasicTest, GetBlob) {
.IsIncomplete());
}
TEST_F(DBBlobBasicTest, BlobFileWritableFileMaxBufferSize) {
constexpr uint64_t kBlobWriterBufferSize = 128 * 1024;
Options options = GetDefaultOptions();
options.enable_blob_files = true;
options.min_blob_size = 0;
options.writable_file_max_buffer_size = 1024 * 1024;
options.blob_file_writable_file_max_buffer_size = kBlobWriterBufferSize;
Reopen(options);
std::atomic<int> matching_blob_writer_count{0};
SyncPoint::GetInstance()->ClearAllCallBacks();
SyncPoint::GetInstance()->SetCallBack(
"WritableFileWriter::WritableFileWriter:0", [&](void* arg) {
const uint64_t max_buffer_size =
static_cast<uint64_t>(reinterpret_cast<uintptr_t>(arg));
if (max_buffer_size == kBlobWriterBufferSize) {
++matching_blob_writer_count;
}
});
SyncPoint::GetInstance()->EnableProcessing();
ASSERT_OK(Put("key", std::string(1024, 'v')));
ASSERT_OK(Flush());
SyncPoint::GetInstance()->DisableProcessing();
SyncPoint::GetInstance()->ClearAllCallBacks();
ASSERT_GE(matching_blob_writer_count.load(), 1);
}
TEST_F(DBBlobBasicTest,
DirectWriteBlobFileWritableFileMaxBufferSizeSetOptions) {
constexpr uint64_t kBlobWriterBufferSize = 64 * 1024;
Options options = GetDefaultOptions();
options.enable_blob_files = true;
options.enable_blob_direct_write = true;
options.allow_concurrent_memtable_write = false;
options.min_blob_size = 0;
options.blob_file_size = 200;
options.writable_file_max_buffer_size = 1024 * 1024;
Reopen(options);
std::atomic<int> matching_blob_writer_count{0};
SyncPoint::GetInstance()->ClearAllCallBacks();
SyncPoint::GetInstance()->SetCallBack(
"WritableFileWriter::WritableFileWriter:0", [&](void* arg) {
const uint64_t max_buffer_size =
static_cast<uint64_t>(reinterpret_cast<uintptr_t>(arg));
if (max_buffer_size == kBlobWriterBufferSize) {
++matching_blob_writer_count;
}
});
SyncPoint::GetInstance()->EnableProcessing();
ASSERT_OK(Put("first", std::string(300, 'a')));
ASSERT_OK(db_->SetOptions({{"blob_file_writable_file_max_buffer_size",
std::to_string(kBlobWriterBufferSize)}}));
ASSERT_OK(Put("second", std::string(300, 'b')));
SyncPoint::GetInstance()->DisableProcessing();
SyncPoint::GetInstance()->ClearAllCallBacks();
ASSERT_GE(matching_blob_writer_count.load(), 1);
}
TEST_F(DBBlobBasicTest, EmptyValueNotStoredAsBlob) {
// Regression test for crash when empty blob value is evicted to
// CompressedSecondaryCache (T261142690). Empty values should always be
+14 -311
View File
@@ -15,7 +15,6 @@
#include <vector>
#include "db/arena_wrapped_db_iter.h"
#include "db/blob/blob_fetcher.h"
#include "db/blob/blob_index.h"
#include "db/column_family.h"
#include "db/db_iter.h"
@@ -139,32 +138,19 @@ class DBBlobIndexTest : public DBTestBase {
bool resolve_direct_write_value, const Version* current,
PinnableSlice* value, PinnableWideColumns* columns, Status* s,
bool* is_blob_index, bool* value_found = nullptr) {
VersionBlobFetcher blob_fetcher(current, read_options,
cfd()->blob_file_cache(),
/*allow_write_path_fallback=*/true);
return DBImpl::MaybeResolveDirectWriteValue(
read_options, key, resolve_direct_write_value, blob_fetcher, value,
read_options, key, resolve_direct_write_value, current, cfd(), value,
columns, s, is_blob_index, value_found);
}
Status MaybeResolveMemtableBlobValueForTest(
const Slice& key, const BlobFetcher* blob_fetcher, PinnableSlice* value,
PinnableWideColumns* columns, bool* did_resolve, bool* is_blob_index,
bool* value_found = nullptr) {
return DBImpl::MaybeResolveMemtableBlobValue(key, blob_fetcher, value,
columns, did_resolve,
is_blob_index, value_found);
}
Status PostprocessMemtableValueReadForTest(
const Slice& key, bool resolve_blob_backed_memtable_value,
const BlobFetcher* blob_fetcher, PinnableSlice* value,
PinnableWideColumns* columns, Status memtable_read_status,
bool* is_blob_index, bool* value_found = nullptr) {
return DBImpl::PostprocessMemtableValueRead(
key, /*timestamp=*/nullptr, resolve_blob_backed_memtable_value,
blob_fetcher, value, columns, std::move(memtable_read_status),
is_blob_index, value_found);
bool MaybeResolveMemtableBlobValueForTest(const Slice& key,
const BlobFetcher* blob_fetcher,
PinnableSlice* value,
PinnableWideColumns* columns,
Status* s, bool* is_blob_index,
bool* value_found = nullptr) {
return DBImpl::MaybeResolveMemtableBlobValue(
key, blob_fetcher, value, columns, s, is_blob_index, value_found);
}
Options GetTestOptions() {
@@ -323,65 +309,17 @@ TEST_F(DBBlobIndexTest,
value.GetSelf()->assign(blob_index.data(), blob_index.size());
value.PinSelf();
bool did_resolve = false;
Status s = Status::OK();
bool is_blob_index = true;
Status s = MaybeResolveMemtableBlobValueForTest(
Slice("key"), /*blob_fetcher=*/nullptr, &value, /*columns=*/nullptr,
&did_resolve, &is_blob_index);
ASSERT_TRUE(MaybeResolveMemtableBlobValueForTest(
Slice("key"), /*blob_fetcher=*/nullptr, &value, /*columns=*/nullptr, &s,
&is_blob_index));
ASSERT_TRUE(did_resolve);
ASSERT_TRUE(s.IsCorruption()) << s.ToString();
ASSERT_TRUE(s.IsNotSupported()) << s.ToString();
ASSERT_TRUE(value.empty());
ASSERT_FALSE(is_blob_index);
}
TEST_F(DBBlobIndexTest, PostprocessMemtableValueReadClearsOutputsOnError) {
// Regression test for the "swallowed status" FIXME: on any error,
// PostprocessMemtableValueRead must clear the outputs and return the status,
// never leaving a half-populated result behind a non-OK status.
// Case 1: the incoming memtable read status is already non-OK. The resolve
// path is skipped; the finalization block clears outputs and returns it.
{
PinnableSlice value;
value.GetSelf()->assign("stale", 5);
value.PinSelf();
bool is_blob_index = false;
Status s = PostprocessMemtableValueReadForTest(
Slice("key"), /*resolve_blob_backed_memtable_value=*/true,
/*blob_fetcher=*/nullptr, &value, /*columns=*/nullptr,
Status::Corruption("read failed"), &is_blob_index);
ASSERT_TRUE(s.IsCorruption()) << s.ToString();
ASSERT_TRUE(value.empty());
}
// Case 2: the incoming status is OK but the blob-resolve path itself fails (a
// blob-backed value with no fetcher). This is the actual scenario the FIXME
// referred to -- previously the non-OK status from the resolve path was
// dropped. The failure must propagate and the raw blob-index bytes must be
// cleared rather than handed back as if they were the value.
{
std::string blob_index;
BlobIndex::EncodeBlob(&blob_index, /*file_number=*/123, /*offset=*/456,
/*size=*/789, kNoCompression);
PinnableSlice value;
value.GetSelf()->assign(blob_index.data(), blob_index.size());
value.PinSelf();
bool is_blob_index = true;
Status s = PostprocessMemtableValueReadForTest(
Slice("key"), /*resolve_blob_backed_memtable_value=*/true,
/*blob_fetcher=*/nullptr, &value, /*columns=*/nullptr, Status::OK(),
&is_blob_index);
ASSERT_TRUE(s.IsCorruption()) << s.ToString();
ASSERT_TRUE(value.empty());
}
}
TEST_F(DBBlobIndexTest, ReadOnlyGetImplReturnsBlobIndexWhenRequested) {
// Goal: cover the internal read-only GetImpl contract when the caller
// explicitly asks for raw blob-index bytes via `is_blob_index`. Recovery
@@ -837,241 +775,6 @@ TEST_F(DBBlobIndexTest, EmbeddedBlobSharedBlockAndBlobCache) {
ASSERT_OK(iter->status());
}
// Point GetEntity / MultiGetEntity of a wide-column entity whose non-default
// columns are embedded (same-file) blobs must return the correct columns and
// resolve them zero-copy: each resolved blob column value points straight at
// its pinned blob-cache buffer (identical across reads, and in a separate
// buffer per column), rather than being copied into one re-serialized entity.
TEST_F(DBBlobIndexTest, EmbeddedBlobWideColumnGetEntityZeroCopy) {
Options options = GetTestOptions();
options.create_if_missing = true;
options.statistics = CreateDBStatistics();
LRUCacheOptions co;
co.capacity = 8 << 20;
options.blob_cache = NewLRUCache(co);
DestroyAndReopen(options);
const std::string sst_path = dbname_ + "/embedded_wc_zerocopy.sst";
SstFileWriterEmbeddedBlobOptions embedded_blob_options;
embedded_blob_options.min_blob_size = 8;
const std::string small_default = "d"; // inline default column
const std::string big1(1024, 'a'); // same-file blob column
const std::string big2(2048, 'b'); // same-file blob column
const WideColumns columns{
{kDefaultWideColumnName, small_default}, {"big1", big1}, {"big2", big2}};
SstFileWriter writer(EnvOptions(), options);
ASSERT_OK(writer.OpenWithEmbeddedBlobs(sst_path, embedded_blob_options));
ASSERT_OK(writer.PutEntity("k", columns));
ASSERT_OK(writer.Finish());
ASSERT_OK(db_->IngestExternalFile({sst_path}, IngestExternalFileOptions()));
const char* big1_ptr = nullptr;
const char* big2_ptr = nullptr;
{
PinnableWideColumns result;
ASSERT_OK(db_->GetEntity(ReadOptions(), db_->DefaultColumnFamily(), "k",
&result));
ASSERT_EQ(result.columns(), columns);
// columns() is sorted by name -> [default(""), big1, big2].
big1_ptr = result.columns()[1].value().data();
big2_ptr = result.columns()[2].value().data();
// Multi-buffer: each blob column lives in its own backing buffer, so the
// two values are not laid out contiguously (as they would be in a single
// re-serialized V1 entity).
ASSERT_NE(big1_ptr + big1.size(), big2_ptr);
// Pointer stability across move (address-stable backing nodes).
PinnableWideColumns moved(std::move(result));
ASSERT_EQ(moved.columns(), columns);
ASSERT_EQ(moved.columns()[1].value().data(), big1_ptr);
ASSERT_EQ(moved.columns()[2].value().data(), big2_ptr);
}
// A second read serves the same pinned blob-cache buffers (zero-copy): the
// resolved column values point at the very same addresses, which a per-read
// re-serialization would not.
{
PinnableWideColumns result;
ASSERT_OK(db_->GetEntity(ReadOptions(), db_->DefaultColumnFamily(), "k",
&result));
ASSERT_EQ(result.columns(), columns);
ASSERT_EQ(result.columns()[1].value().data(), big1_ptr);
ASSERT_EQ(result.columns()[2].value().data(), big2_ptr);
}
// MultiGetEntity: same correctness and zero-copy (cache-hit) guarantee.
{
const std::array<Slice, 1> keys{Slice("k")};
std::array<PinnableWideColumns, 1> results;
std::array<Status, 1> statuses;
db_->MultiGetEntity(ReadOptions(), db_->DefaultColumnFamily(), keys.size(),
keys.data(), results.data(), statuses.data());
ASSERT_OK(statuses[0]);
ASSERT_EQ(results[0].columns(), columns);
ASSERT_EQ(results[0].columns()[1].value().data(), big1_ptr);
ASSERT_EQ(results[0].columns()[2].value().data(), big2_ptr);
}
}
// A wide-column entity whose default column is itself an embedded (same-file)
// blob must resolve correctly on the plain Get path (default-column
// extraction) as well as GetEntity, matching the values written.
TEST_F(DBBlobIndexTest, EmbeddedBlobWideColumnGetDefaultColumn) {
Options options = GetTestOptions();
options.create_if_missing = true;
DestroyAndReopen(options);
const std::string sst_path = dbname_ + "/embedded_wc_default.sst";
SstFileWriterEmbeddedBlobOptions embedded_blob_options;
embedded_blob_options.min_blob_size = 8;
const std::string big_default(1024, 'x'); // same-file blob default column
const std::string small_attr = "s"; // inline non-default column
const WideColumns columns{{kDefaultWideColumnName, big_default},
{"attr", small_attr}};
SstFileWriter writer(EnvOptions(), options);
ASSERT_OK(writer.OpenWithEmbeddedBlobs(sst_path, embedded_blob_options));
ASSERT_OK(writer.PutEntity("k", columns));
ASSERT_OK(writer.Finish());
ASSERT_OK(db_->IngestExternalFile({sst_path}, IngestExternalFileOptions()));
// Plain Get returns the (blob-backed) default column value.
PinnableSlice value;
ASSERT_OK(db_->Get(ReadOptions(), db_->DefaultColumnFamily(), "k", &value));
ASSERT_EQ(value, big_default);
// GetEntity returns all columns.
PinnableWideColumns result;
ASSERT_OK(
db_->GetEntity(ReadOptions(), db_->DefaultColumnFamily(), "k", &result));
ASSERT_EQ(result.columns(), columns);
}
// Merge over an embedded-blob wide-column base entity must resolve the base
// entity's same-file default column before merging, and GetMergeOperands must
// return the resolved default column as the base operand.
TEST_F(DBBlobIndexTest, EmbeddedBlobWideColumnMergeBase) {
Options options = GetTestOptions(); // merge_operator = StringAppend(',')
options.create_if_missing = true;
DestroyAndReopen(options);
const std::string sst_path = dbname_ + "/embedded_wc_merge.sst";
SstFileWriterEmbeddedBlobOptions embedded_blob_options;
embedded_blob_options.min_blob_size = 8;
const std::string big_default(1024, 'D'); // same-file blob default column
const WideColumns columns{{kDefaultWideColumnName, big_default},
{"attr", "s"}};
SstFileWriter writer(EnvOptions(), options);
ASSERT_OK(writer.OpenWithEmbeddedBlobs(sst_path, embedded_blob_options));
ASSERT_OK(writer.PutEntity("k", columns));
ASSERT_OK(writer.Finish());
ASSERT_OK(db_->IngestExternalFile({sst_path}, IngestExternalFileOptions()));
// Newer merge operand lives in the memtable; the embedded entity base lives
// in the ingested SST, so the merge resolves the base via the same-file path.
ASSERT_OK(db_->Merge(WriteOptions(), db_->DefaultColumnFamily(), "k", "op1"));
PinnableSlice value;
ASSERT_OK(db_->Get(ReadOptions(), db_->DefaultColumnFamily(), "k", &value));
ASSERT_EQ(value, big_default + "," + "op1");
// GetMergeOperands returns the resolved base default column plus the operand.
std::array<PinnableSlice, 8> operands;
GetMergeOperandsOptions get_merge_opts;
get_merge_opts.expected_max_number_of_operands =
static_cast<int>(operands.size());
int num_operands = 0;
ASSERT_OK(db_->GetMergeOperands(ReadOptions(), db_->DefaultColumnFamily(),
"k", operands.data(), &get_merge_opts,
&num_operands));
ASSERT_EQ(num_operands, 2);
ASSERT_EQ(operands[0], big_default);
ASSERT_EQ(operands[1], "op1");
}
// With read_tier == kBlockCacheTier, an unresolved same-file blob column of a
// wide-column entity must surface Incomplete (never a raw same-file BlobIndex).
TEST_F(DBBlobIndexTest, EmbeddedBlobWideColumnGetEntityBlockCacheTier) {
Options options = GetTestOptions();
options.create_if_missing = true;
DestroyAndReopen(options);
const std::string sst_path = dbname_ + "/embedded_wc_blockcache.sst";
SstFileWriterEmbeddedBlobOptions embedded_blob_options;
embedded_blob_options.min_blob_size = 8;
const std::string big1(1024, 'a');
const WideColumns columns{{kDefaultWideColumnName, "d"}, {"big", big1}};
SstFileWriter writer(EnvOptions(), options);
ASSERT_OK(writer.OpenWithEmbeddedBlobs(sst_path, embedded_blob_options));
ASSERT_OK(writer.PutEntity("k", columns));
ASSERT_OK(writer.Finish());
ASSERT_OK(db_->IngestExternalFile({sst_path}, IngestExternalFileOptions()));
// Warm the block cache so the data block read succeeds under kBlockCacheTier
// and the lookup actually reaches same-file blob column resolution.
{
PinnableWideColumns result;
ASSERT_OK(db_->GetEntity(ReadOptions(), db_->DefaultColumnFamily(), "k",
&result));
ASSERT_EQ(result.columns(), columns);
}
ReadOptions read_options;
read_options.read_tier = kBlockCacheTier;
PinnableWideColumns result;
Status s =
db_->GetEntity(read_options, db_->DefaultColumnFamily(), "k", &result);
ASSERT_TRUE(s.IsIncomplete()) << s.ToString();
}
// A corrupt embedded blob record backing a wide-column column must surface an
// error on GetEntity, not expose the raw same-file BlobIndex.
// A failure resolving an embedded blob record backing a wide-column column
// (e.g. a bad record or blob-region read fault) must surface on GetEntity, not
// expose the raw same-file BlobIndex. The failure is injected via a sync point
// so the test is independent of the on-disk byte layout (e.g. encrypted env).
TEST_F(DBBlobIndexTest, EmbeddedBlobWideColumnGetEntityCorruptionSurfaced) {
Options options = GetTestOptions();
options.create_if_missing = true;
DestroyAndReopen(options);
const std::string sst_path = dbname_ + "/embedded_wc_corrupt.sst";
SstFileWriterEmbeddedBlobOptions embedded_blob_options;
embedded_blob_options.min_blob_size = 8;
const std::string big_col(1024, 'Z');
const WideColumns columns{{kDefaultWideColumnName, "d"}, {"big", big_col}};
SstFileWriter writer(EnvOptions(), options);
ASSERT_OK(writer.OpenWithEmbeddedBlobs(sst_path, embedded_blob_options));
ASSERT_OK(writer.PutEntity("k", columns));
ASSERT_OK(writer.Finish());
ASSERT_OK(db_->IngestExternalFile({sst_path}, IngestExternalFileOptions()));
const Status kInjected = Status::Corruption("injected embedded blob error");
SyncPoint::GetInstance()->SetCallBack(
"BlockBasedTable::MaybeResolveEmbeddedValue:InjectError",
[&](void* arg) { *static_cast<Status*>(arg) = kInjected; });
SyncPoint::GetInstance()->EnableProcessing();
PinnableWideColumns result;
const Status s =
db_->GetEntity(ReadOptions(), db_->DefaultColumnFamily(), "k", &result);
SyncPoint::GetInstance()->DisableProcessing();
SyncPoint::GetInstance()->ClearAllCallBacks();
ASSERT_TRUE(s.IsCorruption()) << s.ToString();
}
class PlainBlobValueFilterV3 : public CompactionFilter {
public:
PlainBlobValueFilterV3(std::atomic<int>* filter_call_count,
-57
View File
@@ -1,57 +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).
#pragma once
#include <cstddef>
#include <cstdint>
#include "rocksdb/rocksdb_namespace.h"
#include "rocksdb/status.h"
namespace ROCKSDB_NAMESPACE {
class BlobIndex;
class PinnableSlice;
struct ReadOptions;
// Narrow interface for resolving a same-file ("embedded") blob reference
// against the physical file that currently holds the table entry. Implemented
// by BlockBasedTable, which owns the reader context (file, footer, blob cache)
// needed to read an embedded blob record.
//
// Kept in its own low-level header, free of any table-layer dependency, so that
// db/blob (EmbeddedAwareBlobFetcher) and table/get_context can depend on just
// this interface without pulling in BlockBasedTable. ReadPathBlobResolver (the
// lazy-resolution read path) can likewise hold a const SameFileBlobReader*.
class SameFileBlobReader {
public:
virtual ~SameFileBlobReader() = default;
// Resolves a same-file blob reference (one for which blob_index.IsSameFile()
// is true) into `value`, pinning the payload zero-copy (from the blob cache
// or an owned buffer). read_tier == kBlockCacheTier without a cached record
// yields Status::Incomplete; a bad record yields Status::Corruption.
virtual Status GetSameFileBlob(const ReadOptions& read_options,
const BlobIndex& blob_index,
PinnableSlice* value) const = 0;
// Resolves a byte sub-range [range_offset, range_offset + range_length) of an
// *uncompressed* same-file blob reference into `value`, reading only those
// bytes on a cache miss (the embedded counterpart of a separate-file blob
// range read). Pins the payload zero-copy (a sliced cached record, or an
// owned sub-range buffer). Unlike GetSameFileBlob it skips whole-record
// checksum verification (a strict sub-range cannot cover it) and never
// populates the blob cache. The caller must ensure range_offset +
// range_length <= blob_index.size(). read_tier == kBlockCacheTier without a
// cached record yields Status::Incomplete.
virtual Status GetSameFileBlobRange(const ReadOptions& read_options,
const BlobIndex& blob_index,
uint64_t range_offset,
size_t range_length,
PinnableSlice* value) const = 0;
};
} // namespace ROCKSDB_NAMESPACE
+48 -200
View File
@@ -7,14 +7,13 @@
// Auto-generated by tools/c_api_gen/regen_all.py.
// DO NOT EDIT THIS FILE DIRECTLY.
// Edit tools/c_api_gen/c_base.cc or the inputs under tools/c_api_gen/,
// then rerun `make regen-c-api`
// then rerun: python3 tools/c_api_gen/regen_all.py
// -----------------------------------------------------------------------------
#include "rocksdb/c.h"
#include <cstdlib>
#include <iterator>
#include <limits>
#include <map>
#include <memory>
#include <unordered_set>
@@ -183,6 +182,7 @@ using ROCKSDB_NAMESPACE::TraceReader;
using ROCKSDB_NAMESPACE::Transaction;
using ROCKSDB_NAMESPACE::TransactionDB;
using ROCKSDB_NAMESPACE::TransactionDBOptions;
using ROCKSDB_NAMESPACE::TransactionLogIterator;
using ROCKSDB_NAMESPACE::TransactionOptions;
using ROCKSDB_NAMESPACE::UserCollectedProperties;
using ROCKSDB_NAMESPACE::UserDefinedIndexFactory;
@@ -190,7 +190,6 @@ using ROCKSDB_NAMESPACE::VectorWalPtr;
using ROCKSDB_NAMESPACE::WaitForCompactOptions;
using ROCKSDB_NAMESPACE::WalFile;
using ROCKSDB_NAMESPACE::WalFilter;
using ROCKSDB_NAMESPACE::WalIterator;
using ROCKSDB_NAMESPACE::WALRecoveryMode;
using ROCKSDB_NAMESPACE::WritableFile;
using ROCKSDB_NAMESPACE::WriteBatch;
@@ -413,16 +412,12 @@ struct rocksdb_readoptions_t {
void* table_filter_state = nullptr;
void (*table_filter_destructor)(void*) = nullptr;
rocksdb_readoptions_table_filter_cb table_filter_callback = nullptr;
// Owns the std::function that rep.table_filter points to. rep.table_filter is
// a pointer to a caller-owned std::function, and this struct is that owner.
std::function<bool(const TableProperties&)> table_filter_func;
std::shared_ptr<UserDefinedIndexFactory> table_index_factory;
~rocksdb_readoptions_t() { ClearTableFilter(); }
void ClearTableFilter() {
rep.table_filter = nullptr;
table_filter_func = {};
rep.table_filter = {};
if (table_filter_destructor != nullptr) {
(*table_filter_destructor)(table_filter_state);
}
@@ -440,12 +435,11 @@ struct rocksdb_readoptions_t {
if (callback != nullptr) {
auto cb = table_filter_callback;
auto filter_state = table_filter_state;
table_filter_func = [cb, filter_state](const TableProperties& props) {
rep.table_filter = [cb, filter_state](const TableProperties& props) {
return cb(filter_state,
reinterpret_cast<const rocksdb_table_properties_t*>(
&props)) != 0;
};
rep.table_filter = &table_filter_func;
}
}
};
@@ -486,10 +480,10 @@ struct rocksdb_writablefile_t {
WritableFile* rep;
};
struct rocksdb_wal_iterator_t {
WalIterator* rep;
TransactionLogIterator* rep;
};
struct rocksdb_wal_readoptions_t {
WalIterator::ReadOptions rep;
TransactionLogIterator::ReadOptions rep;
};
struct rocksdb_wal_files_t {
@@ -600,63 +594,6 @@ struct rocksdb_perfcontext_t {
struct rocksdb_pinnableslice_t {
PinnableSlice rep;
};
struct rocksdb_pinnable_multi_get_t {
static constexpr size_t kNotFound = std::numeric_limits<size_t>::max();
explicit rocksdb_pinnable_multi_get_t(size_t result_count)
: result_indexes(result_count, kNotFound) {}
void ReservePayloads(const std::vector<Status>& statuses) {
size_t value_count = 0;
size_t error_count = 0;
for (const Status& status : statuses) {
value_count += status.ok();
error_count += !status.ok() && !status.IsNotFound();
}
values.reserve(value_count);
errors.reserve(error_count);
}
void StoreResults(std::vector<PinnableSlice>* multi_get_values,
const std::vector<Status>& statuses) {
ReservePayloads(statuses);
for (size_t i = 0; i < statuses.size(); ++i) {
if (statuses[i].ok()) {
result_indexes[i] = values.size();
values.emplace_back(std::move((*multi_get_values)[i]));
} else if (!statuses[i].IsNotFound()) {
result_indexes[i] = kNotFound - errors.size() - 1;
errors.emplace_back(statuses[i].ToString());
}
}
}
int GetResult(size_t index, const char** value, size_t* value_size,
const char** error, size_t* error_size) const {
if (index >= result_indexes.size()) {
return rocksdb_pinnable_multi_get_out_of_bounds;
}
const size_t result_index = result_indexes[index];
if (result_index == kNotFound) {
return rocksdb_pinnable_multi_get_not_found;
}
if (result_index < values.size()) {
*value = values[result_index].data();
*value_size = values[result_index].size();
return rocksdb_pinnable_multi_get_found;
}
const std::string& message = errors[kNotFound - result_index - 1];
*error = message.c_str();
*error_size = message.size();
return rocksdb_pinnable_multi_get_error;
}
// Found entries store a value index. Error entries count back from
// kNotFound - 1, leaving kNotFound to represent a missing key.
std::vector<size_t> result_indexes;
std::vector<PinnableSlice> values;
std::vector<std::string> errors;
};
struct rocksdb_transactiondb_options_t {
TransactionDBOptions rep;
};
@@ -2925,44 +2862,6 @@ void rocksdb_batched_multi_get_cf_slice(
delete[] statuses;
}
rocksdb_pinnable_multi_get_t* rocksdb_batched_multi_get_pinned_cf(
rocksdb_t* db, const rocksdb_readoptions_t* options,
rocksdb_column_family_handle_t* column_family, size_t num_keys,
const rocksdb_slice_t* keys, unsigned char sorted_input) {
auto results = std::make_unique<rocksdb_pinnable_multi_get_t>(num_keys);
if (num_keys == 0) {
return results.release();
}
const Slice* key_slices = reinterpret_cast<const Slice*>(keys);
std::vector<PinnableSlice> values(num_keys);
std::vector<Status> statuses(num_keys);
db->rep->MultiGet(options->rep, column_family->rep, num_keys, key_slices,
values.data(), statuses.data(), sorted_input != 0);
results->StoreResults(&values, statuses);
return results.release();
}
size_t rocksdb_pinnable_multi_get_count(
const rocksdb_pinnable_multi_get_t* multi_get) {
return multi_get->result_indexes.size();
}
int rocksdb_pinnable_multi_get_result(
const rocksdb_pinnable_multi_get_t* multi_get, size_t index,
const char** value, size_t* value_size, const char** error,
size_t* error_size) {
*value = nullptr;
*value_size = 0;
*error = nullptr;
*error_size = 0;
return multi_get->GetResult(index, value, value_size, error, error_size);
}
void rocksdb_pinnable_multi_get_destroy(
rocksdb_pinnable_multi_get_t* multi_get) {
delete multi_get;
}
unsigned char rocksdb_key_may_exist(rocksdb_t* db,
const rocksdb_readoptions_t* options,
const char* key, size_t key_len,
@@ -3022,8 +2921,8 @@ rocksdb_iterator_t* rocksdb_create_iterator(
rocksdb_wal_iterator_t* rocksdb_get_updates_since(
rocksdb_t* db, uint64_t seq_number,
const rocksdb_wal_readoptions_t* options, char** errptr) {
std::unique_ptr<WalIterator> iter;
WalIterator::ReadOptions ro;
std::unique_ptr<TransactionLogIterator> iter;
TransactionLogIterator::ReadOptions ro;
if (options != nullptr) {
ro = options->rep;
}
@@ -5390,17 +5289,6 @@ uint64_t rocksdb_compaction_file_info_oldest_blob_file_number(
/* BlobFileAdditionInfo */
const char* rocksdb_blob_file_addition_info_blob_file_path(
const rocksdb_blob_file_addition_info_t* info, size_t* size) {
*size = info->rep.blob_file_path.size();
return info->rep.blob_file_path.data();
}
uint64_t rocksdb_blob_file_addition_info_blob_file_number(
const rocksdb_blob_file_addition_info_t* info) {
return info->rep.blob_file_number;
}
uint64_t rocksdb_blob_file_addition_info_total_blob_count(
const rocksdb_blob_file_addition_info_t* info) {
return info->rep.total_blob_count;
@@ -5413,17 +5301,6 @@ uint64_t rocksdb_blob_file_addition_info_total_blob_bytes(
/* BlobFileGarbageInfo */
const char* rocksdb_blob_file_garbage_info_blob_file_path(
const rocksdb_blob_file_garbage_info_t* info, size_t* size) {
*size = info->rep.blob_file_path.size();
return info->rep.blob_file_path.data();
}
uint64_t rocksdb_blob_file_garbage_info_blob_file_number(
const rocksdb_blob_file_garbage_info_t* info) {
return info->rep.blob_file_number;
}
uint64_t rocksdb_blob_file_garbage_info_garbage_blob_count(
const rocksdb_blob_file_garbage_info_t* info) {
return info->rep.garbage_blob_count;
@@ -9208,15 +9085,6 @@ int rocksdb_options_get_max_file_opening_threads(rocksdb_options_t* opt) {
return opt->rep.max_file_opening_threads;
}
void rocksdb_options_set_read_io_executor_threads(rocksdb_options_t* opt,
int v) {
opt->rep.read_io_executor_threads = v;
}
int rocksdb_options_get_read_io_executor_threads(rocksdb_options_t* opt) {
return opt->rep.read_io_executor_threads;
}
void rocksdb_options_set_open_files_async(rocksdb_options_t* opt,
unsigned char v) {
opt->rep.open_files_async = v;
@@ -10372,16 +10240,6 @@ uint64_t rocksdb_options_get_blob_file_size(rocksdb_options_t* opt) {
return opt->rep.blob_file_size;
}
void rocksdb_options_set_blob_file_writable_file_max_buffer_size(
rocksdb_options_t* opt, uint64_t v) {
opt->rep.blob_file_writable_file_max_buffer_size = v;
}
uint64_t rocksdb_options_get_blob_file_writable_file_max_buffer_size(
rocksdb_options_t* opt) {
return opt->rep.blob_file_writable_file_max_buffer_size;
}
void rocksdb_options_set_blob_compression_type(rocksdb_options_t* opt, int v) {
opt->rep.blob_compression_type =
static_cast<decltype(opt->rep.blob_compression_type)>(v);
@@ -10764,16 +10622,6 @@ unsigned char rocksdb_flushoptions_get_force_atomic_flush(
return opt->rep.force_atomic_flush;
}
void rocksdb_flushoptions_set_listener_wait(rocksdb_flushoptions_t* opt,
unsigned char v) {
opt->rep.listener_wait = v;
}
unsigned char rocksdb_flushoptions_get_listener_wait(
rocksdb_flushoptions_t* opt) {
return opt->rep.listener_wait;
}
/* FlushWALOptions */
void rocksdb_flushwaloptions_set_sync(rocksdb_flushwaloptions_t* opt,
@@ -11803,36 +11651,6 @@ uint64_t rocksdb_fifo_compaction_options_get_trivial_copy_buffer_size(
/* BackupEngineOptions */
void rocksdb_backup_engine_options_set_io_buffer_size(
rocksdb_backup_engine_options_t* opt, uint64_t v) {
opt->rep.io_buffer_size = v;
}
uint64_t rocksdb_backup_engine_options_get_io_buffer_size(
rocksdb_backup_engine_options_t* opt) {
return opt->rep.io_buffer_size;
}
void rocksdb_backup_engine_options_set_backup_rate_limit(
rocksdb_backup_engine_options_t* opt, uint64_t v) {
opt->rep.backup_rate_limit = v;
}
uint64_t rocksdb_backup_engine_options_get_backup_rate_limit(
rocksdb_backup_engine_options_t* opt) {
return opt->rep.backup_rate_limit;
}
void rocksdb_backup_engine_options_set_max_background_operations(
rocksdb_backup_engine_options_t* opt, int v) {
opt->rep.max_background_operations = v;
}
int rocksdb_backup_engine_options_get_max_background_operations(
rocksdb_backup_engine_options_t* opt) {
return opt->rep.max_background_operations;
}
void rocksdb_backup_engine_options_set_backup_dir(
rocksdb_backup_engine_options_t* opt, const char* v) {
opt->rep.backup_dir = v;
@@ -11884,6 +11702,26 @@ unsigned char rocksdb_backup_engine_options_get_backup_log_files(
return opt->rep.backup_log_files;
}
void rocksdb_backup_engine_options_set_io_buffer_size(
rocksdb_backup_engine_options_t* opt, uint64_t v) {
opt->rep.io_buffer_size = v;
}
uint64_t rocksdb_backup_engine_options_get_io_buffer_size(
rocksdb_backup_engine_options_t* opt) {
return opt->rep.io_buffer_size;
}
void rocksdb_backup_engine_options_set_backup_rate_limit(
rocksdb_backup_engine_options_t* opt, uint64_t v) {
opt->rep.backup_rate_limit = v;
}
uint64_t rocksdb_backup_engine_options_get_backup_rate_limit(
rocksdb_backup_engine_options_t* opt) {
return opt->rep.backup_rate_limit;
}
void rocksdb_backup_engine_options_set_restore_rate_limit(
rocksdb_backup_engine_options_t* opt, uint64_t v) {
opt->rep.restore_rate_limit = v;
@@ -11904,6 +11742,16 @@ unsigned char rocksdb_backup_engine_options_get_share_files_with_checksum(
return opt->rep.share_files_with_checksum;
}
void rocksdb_backup_engine_options_set_max_background_operations(
rocksdb_backup_engine_options_t* opt, int v) {
opt->rep.max_background_operations = v;
}
int rocksdb_backup_engine_options_get_max_background_operations(
rocksdb_backup_engine_options_t* opt) {
return opt->rep.max_background_operations;
}
void rocksdb_backup_engine_options_set_callback_trigger_interval_size(
rocksdb_backup_engine_options_t* opt, uint64_t v) {
opt->rep.callback_trigger_interval_size = v;
@@ -11958,6 +11806,16 @@ rocksdb_backup_engine_options_get_current_temperatures_override_manifest(
/* CreateBackupOptions */
void rocksdb_create_backup_options_set_flush_before_backup(
rocksdb_create_backup_options_t* opt, unsigned char v) {
opt->rep.flush_before_backup = v;
}
unsigned char rocksdb_create_backup_options_get_flush_before_backup(
rocksdb_create_backup_options_t* opt) {
return opt->rep.flush_before_backup;
}
void rocksdb_create_backup_options_set_decrease_background_thread_cpu_priority(
rocksdb_create_backup_options_t* opt, unsigned char v) {
opt->rep.decrease_background_thread_cpu_priority = v;
@@ -11980,16 +11838,6 @@ int rocksdb_create_backup_options_get_background_thread_cpu_priority(
return static_cast<int>(opt->rep.background_thread_cpu_priority);
}
void rocksdb_create_backup_options_set_flush_before_backup(
rocksdb_create_backup_options_t* opt, unsigned char v) {
opt->rep.flush_before_backup = v;
}
unsigned char rocksdb_create_backup_options_get_flush_before_backup(
rocksdb_create_backup_options_t* opt) {
return opt->rep.flush_before_backup;
}
void rocksdb_create_backup_options_set_atomic_flush(
rocksdb_create_backup_options_t* opt, unsigned char v) {
opt->rep.atomic_flush = v;
-183
View File
@@ -189,57 +189,6 @@ static void CheckMultiGetValues(size_t num_keys, char** values,
}
}
static void CheckPinnableMultiGetFound(
const rocksdb_pinnable_multi_get_t* multi_get, size_t index,
const char* expected, size_t expected_size) {
const char* value;
const char* error;
size_t value_size;
size_t error_size;
int result = rocksdb_pinnable_multi_get_result(
multi_get, index, &value, &value_size, &error, &error_size);
CheckCondition(result == rocksdb_pinnable_multi_get_found);
CheckCondition(value_size == expected_size);
CheckCondition(error == NULL);
CheckCondition(error_size == 0);
if (expected_size > 0) {
CheckCondition(value != NULL);
CheckCondition(memcmp(value, expected, expected_size) == 0);
}
}
static void CheckPinnableMultiGetNotFound(
const rocksdb_pinnable_multi_get_t* multi_get, size_t index) {
const char* value;
const char* error;
size_t value_size;
size_t error_size;
int result = rocksdb_pinnable_multi_get_result(
multi_get, index, &value, &value_size, &error, &error_size);
CheckCondition(result == rocksdb_pinnable_multi_get_not_found);
CheckCondition(value == NULL);
CheckCondition(value_size == 0);
CheckCondition(error == NULL);
CheckCondition(error_size == 0);
}
static void CheckPinnableMultiGetError(
const rocksdb_pinnable_multi_get_t* multi_get, size_t index,
const char* expected) {
const char* value;
const char* error;
size_t value_size;
size_t error_size;
int result = rocksdb_pinnable_multi_get_result(
multi_get, index, &value, &value_size, &error, &error_size);
CheckCondition(result == rocksdb_pinnable_multi_get_error);
CheckCondition(value == NULL);
CheckCondition(value_size == 0);
CheckCondition(error != NULL);
CheckCondition(error_size == strlen(error));
CheckCondition(strstr(error, expected) != NULL);
}
static void CheckIter(rocksdb_iterator_t* iter, const char* key,
const char* val) {
size_t len;
@@ -885,39 +834,6 @@ static char* MergeOperatorPartialMerge(void* arg, const char* key,
return result;
}
static char* FailingMergeOperatorFullMerge(
void* arg, const char* key, size_t key_length, const char* existing_value,
size_t existing_value_length, const char* const* operands_list,
const size_t* operands_list_length, int num_operands,
unsigned char* success, size_t* new_value_length) {
(void)arg;
(void)key;
(void)key_length;
(void)existing_value;
(void)existing_value_length;
(void)operands_list;
(void)operands_list_length;
(void)num_operands;
*success = 0;
*new_value_length = 0;
return NULL;
}
static char* FailingMergeOperatorPartialMerge(
void* arg, const char* key, size_t key_length,
const char* const* operands_list, const size_t* operands_list_length,
int num_operands, unsigned char* success, size_t* new_value_length) {
(void)arg;
(void)key;
(void)key_length;
(void)operands_list;
(void)operands_list_length;
(void)num_operands;
*success = 0;
*new_value_length = 0;
return NULL;
}
static void CheckTxnGet(rocksdb_transaction_t* txn,
const rocksdb_readoptions_t* options, const char* key,
const char* expected) {
@@ -2723,17 +2639,12 @@ int main(int argc, char** argv) {
// use dbpathname2 as the cf_path for "cf1"
rocksdb_dbpath_t* dbpath2;
char dbpathname2[200];
rocksdb_mergeoperator_t* failing_merge_operator;
snprintf(dbpathname2, sizeof(dbpathname2),
"%s/rocksdb_c_test-%" PRIu64 "-dbpath2", GetTempDir(),
GetTestId());
dbpath2 = rocksdb_dbpath_create(dbpathname2, 1024 * 1024);
const rocksdb_dbpath_t* cf_paths[1] = {dbpath2};
rocksdb_options_set_cf_paths(cf_options_2, cf_paths, 1);
failing_merge_operator = rocksdb_mergeoperator_create(
NULL, MergeOperatorDestroy, FailingMergeOperatorFullMerge,
FailingMergeOperatorPartialMerge, NULL, MergeOperatorName);
rocksdb_options_set_merge_operator(cf_options_2, failing_merge_operator);
const char* cf_names[2] = {"default", "cf1"};
const rocksdb_options_t* cf_opts[2] = {cf_options_1, cf_options_2};
@@ -3256,95 +3167,6 @@ int main(int argc, char** argv) {
}
}
{
rocksdb_slice_t pinned_keys[6] = {{"box", 3}, {"missing", 7},
{"empty", 5}, {"merge-error", 11},
{"box", 3}, {"owned", 5}};
rocksdb_pinnable_multi_get_t* multi_get;
const char* value;
const char* error;
size_t value_size;
size_t error_size;
int result;
rocksdb_put_cf(db, woptions, handles[1], "empty", 5, "", 0, &err);
CheckNoError(err);
rocksdb_put_cf(db, woptions, handles[1], "merge-error", 11, "base", 4,
&err);
CheckNoError(err);
rocksdb_merge_cf(db, woptions, handles[1], "merge-error", 11, "operand",
7, &err);
CheckNoError(err);
rocksdb_put_cf(db, woptions, handles[1], "owned", 5, "before", 6, &err);
CheckNoError(err);
multi_get = rocksdb_batched_multi_get_pinned_cf(db, roptions, handles[1],
6, pinned_keys, 0);
CheckCondition(rocksdb_pinnable_multi_get_count(multi_get) == 6);
CheckPinnableMultiGetFound(multi_get, 0, "c", 1);
CheckPinnableMultiGetNotFound(multi_get, 1);
CheckPinnableMultiGetFound(multi_get, 2, "", 0);
CheckPinnableMultiGetError(multi_get, 3, "Merge operator failed");
CheckPinnableMultiGetFound(multi_get, 4, "c", 1);
CheckPinnableMultiGetFound(multi_get, 5, "before", 6);
value = "unchanged";
error = "unchanged";
value_size = 9;
error_size = 9;
result = rocksdb_pinnable_multi_get_result(
multi_get, 6, &value, &value_size, &error, &error_size);
CheckCondition(result == rocksdb_pinnable_multi_get_out_of_bounds);
CheckCondition(value == NULL);
CheckCondition(value_size == 0);
CheckCondition(error == NULL);
CheckCondition(error_size == 0);
result = rocksdb_pinnable_multi_get_result(
multi_get, 5, &value, &value_size, &error, &error_size);
CheckCondition(result == rocksdb_pinnable_multi_get_found);
const char* borrowed_value = value;
size_t borrowed_value_size = value_size;
result = rocksdb_pinnable_multi_get_result(
multi_get, 3, &value, &value_size, &error, &error_size);
CheckCondition(result == rocksdb_pinnable_multi_get_error);
const char* borrowed_error = error;
size_t borrowed_error_size = error_size;
rocksdb_put_cf(db, woptions, handles[1], "owned", 5, "after", 5, &err);
CheckNoError(err);
CheckCondition(borrowed_value_size == 6);
CheckCondition(memcmp(borrowed_value, "before", 6) == 0);
CheckCondition(borrowed_error_size == strlen(borrowed_error));
CheckCondition(strstr(borrowed_error, "Merge operator failed") != NULL);
rocksdb_pinnable_multi_get_destroy(multi_get);
}
{
rocksdb_slice_t sorted_keys[4] = {
{"box", 3}, {"box", 3}, {"empty", 5}, {"missing", 7}};
rocksdb_pinnable_multi_get_t* multi_get =
rocksdb_batched_multi_get_pinned_cf(db, roptions, handles[1], 4,
sorted_keys, 1);
CheckCondition(rocksdb_pinnable_multi_get_count(multi_get) == 4);
CheckPinnableMultiGetFound(multi_get, 0, "c", 1);
CheckPinnableMultiGetFound(multi_get, 1, "c", 1);
CheckPinnableMultiGetFound(multi_get, 2, "", 0);
CheckPinnableMultiGetNotFound(multi_get, 3);
rocksdb_pinnable_multi_get_destroy(multi_get);
multi_get = rocksdb_batched_multi_get_pinned_cf(db, roptions, handles[1],
0, sorted_keys, 1);
CheckCondition(rocksdb_pinnable_multi_get_count(multi_get) == 0);
rocksdb_pinnable_multi_get_destroy(multi_get);
}
rocksdb_delete_cf(db, woptions, handles[1], "empty", 5, &err);
CheckNoError(err);
rocksdb_delete_cf(db, woptions, handles[1], "merge-error", 11, &err);
CheckNoError(err);
rocksdb_delete_cf(db, woptions, handles[1], "owned", 5, &err);
CheckNoError(err);
{
unsigned char value_found = 0;
@@ -4709,11 +4531,6 @@ int main(int argc, char** argv) {
CheckNoError(err);
rocksdb_flushoptions_set_wait(flush_options, 1);
// Ensure the OnFlushCompleted callbacks (which update listener_state) have
// finished by the time rocksdb_flush() returns, so the flush_count /
// saw_flush_entries_* assertions below are not racy.
rocksdb_flushoptions_set_listener_wait(flush_options, 1);
CheckCondition(1 == rocksdb_flushoptions_get_listener_wait(flush_options));
rocksdb_put(local_db, local_woptions, "a", 1, "1", 1, &err);
CheckNoError(err);
+2 -45
View File
@@ -29,7 +29,6 @@
#include "trace_replay/block_cache_tracer.h"
#include "util/cast_util.h"
#include "util/hash_containers.h"
#include "util/mutexlock.h"
#include "util/thread_local.h"
namespace ROCKSDB_NAMESPACE {
@@ -521,32 +520,6 @@ class ColumnFamilyData {
bool queued_for_flush() { return queued_for_flush_; }
bool queued_for_compaction() { return queued_for_compaction_; }
int compaction_aborted() const {
return compaction_aborted_.obj_.load(std::memory_order_acquire);
}
void inc_compaction_aborted(InstrumentedMutex* db_mutex) {
db_mutex->AssertHeld();
compaction_aborted_.obj_.fetch_add(1, std::memory_order_release);
}
int dec_compaction_aborted(InstrumentedMutex* db_mutex) {
db_mutex->AssertHeld();
return compaction_aborted_.obj_.fetch_sub(1, std::memory_order_acq_rel) - 1;
}
int num_in_flight_compactions(InstrumentedMutex* db_mutex) const {
db_mutex->AssertHeld();
return num_in_flight_compactions_;
}
void inc_num_in_flight_compactions(InstrumentedMutex* db_mutex) {
db_mutex->AssertHeld();
++num_in_flight_compactions_;
}
void dec_num_in_flight_compactions(InstrumentedMutex* db_mutex) {
db_mutex->AssertHeld();
assert(num_in_flight_compactions_ > 0);
--num_in_flight_compactions_;
}
static std::pair<WriteStallCondition, WriteStallCause>
GetWriteStallConditionAndCause(
int num_unflushed_memtables, int num_l0_files,
@@ -738,26 +711,10 @@ class ColumnFamilyData {
// If true --> this ColumnFamily is currently present in DBImpl::flush_queue_
bool queued_for_flush_;
// If true, this ColumnFamily is in DBImpl::compaction_queue_ or its parked
// compaction set.
// If true --> this ColumnFamily is currently present in
// DBImpl::compaction_queue_
bool queued_for_compaction_;
// Read outside the DB mutex by compaction workers (acquire-loaded roughly
// every 1024 records in ProcessKeyValueCompaction). Given its own cache line
// via CacheAlignedWrapper to avoid false sharing with the DB-mutex-written
// fields packed around it.
CacheAlignedWrapper<std::atomic<int>> compaction_aborted_{};
// Per-CF count of compactions "in flight" for AbortCompactions(): a picked
// Compaction (or one CompactFiles call), tracked from
// BeginInFlightCompaction() until EndInFlightCompaction() at the end of
// BackgroundCompaction, so it covers the NotifyOnCompactionCompleted window
// that CompactionPicker's compactions_in_progress_ set does not. NOT the same
// as DBImpl::num_running_compactions_ (which counts BackgroundCallCompaction
// worker invocations, backs the public rocksdb.num-running-compactions
// property, and excludes CompactFiles). Protected by the DB mutex.
int num_in_flight_compactions_{0};
uint64_t prev_compaction_needed_bytes_;
// if the database was opened with 2pc enabled
+16 -18
View File
@@ -251,9 +251,8 @@ void CompactionIterator::SetBlobFetcher(const Version* version,
read_options.io_activity = io_activity;
read_options.fill_cache = false;
blob_fetcher_ = std::make_unique<OwningVersionBlobFetcher>(
version, std::move(read_options), blob_file_cache,
allow_write_path_fallback);
blob_fetcher_ = std::make_unique<BlobFetcher>(
version, read_options, blob_file_cache, allow_write_path_fallback);
blob_resolver_.Init(blob_fetcher_.get(), prefetch_buffers_.get(),
&iter_stats_);
}
@@ -468,14 +467,14 @@ bool CompactionIterator::InvokeFilterIfNeeded(bool* need_skip,
}
}
if (UNLIKELY(has_blob_columns)) {
// Entity has blob columns. Deserialize() populates
// Entity has blob columns. DeserializeV2() populates
// entity_columns_ with the full column set; blob-backed entries still
// carry the serialized BlobIndex bytes in value(). The companion
// entity_blob_columns_ side list identifies which column indexes are
// blob references and provides the decoded BlobIndex objects.
Slice input_copy = value_;
Status s = WideColumnSerialization::Deserialize(
input_copy, entity_columns_, &entity_blob_columns_);
Status s = WideColumnSerialization::DeserializeV2(
input_copy, entity_columns_, entity_blob_columns_);
if (!s.ok()) {
status_ = s;
validity_info_.Invalidate();
@@ -542,7 +541,7 @@ bool CompactionIterator::InvokeFilterIfNeeded(bool* need_skip,
} else {
// No blob columns, use fast path
Slice value_copy = value_;
const Status s = WideColumnSerialization::DeserializeSimple(
const Status s = WideColumnSerialization::Deserialize(
value_copy, filter_existing_columns_);
if (!s.ok()) {
@@ -1551,8 +1550,8 @@ void CompactionIterator::ExtractLargeColumnValuesIfNeeded() {
Slice entity_slice = value_;
entity_columns_.clear();
entity_blob_columns_.clear();
Status s = WideColumnSerialization::Deserialize(
entity_slice, entity_columns_, &entity_blob_columns_);
Status s = WideColumnSerialization::DeserializeV2(
entity_slice, entity_columns_, entity_blob_columns_);
if (!s.ok()) {
status_ = s;
validity_info_.Invalidate();
@@ -1670,7 +1669,7 @@ bool CompactionIterator::FetchBlobsNeedingGC(
Status s = blob_fetcher_->FetchBlob(user_key(), blob_index, prefetch_buffer,
&blob_value, &bytes_read);
if (!s.ok()) {
status_ = std::move(s);
status_ = s;
validity_info_.Invalidate();
return false;
}
@@ -1818,8 +1817,8 @@ void CompactionIterator::GarbageCollectEntityBlobsIfNeeded() {
Slice entity_slice = value_;
entity_columns_.clear();
entity_blob_columns_.clear();
Status s = WideColumnSerialization::Deserialize(
entity_slice, entity_columns_, &entity_blob_columns_);
Status s = WideColumnSerialization::DeserializeV2(
entity_slice, entity_columns_, entity_blob_columns_);
if (!s.ok()) {
status_ = s;
validity_info_.Invalidate();
@@ -1870,13 +1869,13 @@ void CompactionIterator::PrepareOutput() {
"CompactionIterator::PrepareOutput:DeserializeEntity");
// Deserialize entity once into member variables, then decide between
// blob GC and extraction based on whether blob columns exist.
// This avoids the double parse of HasBlobColumns() + Deserialize().
// This avoids the double parse of HasBlobColumns() + DeserializeV2().
entity_columns_.clear();
entity_blob_columns_.clear();
Slice entity_slice = value_;
{
Status s_deser = WideColumnSerialization::Deserialize(
entity_slice, entity_columns_, &entity_blob_columns_);
Status s_deser = WideColumnSerialization::DeserializeV2(
entity_slice, entity_columns_, entity_blob_columns_);
if (!s_deser.ok()) {
status_ = s_deser;
validity_info_.Invalidate();
@@ -2065,9 +2064,8 @@ std::unique_ptr<BlobFetcher> CompactionIterator::CreateBlobFetcherIfNeeded(
}
}
return std::unique_ptr<BlobFetcher>(
new OwningVersionBlobFetcher(version, std::move(read_options),
blob_file_cache, allow_write_path_fallback));
return std::unique_ptr<BlobFetcher>(new BlobFetcher(
version, read_options, blob_file_cache, allow_write_path_fallback));
}
std::unique_ptr<PrefetchBufferCollection>
+20 -26
View File
@@ -1896,8 +1896,8 @@ TEST_F(WideColumnEntityBlobExtractionTest,
Slice value_slice(output_values[0]);
std::vector<WideColumn> output_columns;
std::vector<std::pair<size_t, BlobIndex>> blob_columns;
ASSERT_OK(WideColumnSerialization::Deserialize(value_slice, output_columns,
&blob_columns));
ASSERT_OK(WideColumnSerialization::DeserializeV2(value_slice, output_columns,
blob_columns));
// The large column should now be a blob reference
ASSERT_EQ(1, blob_columns.size());
@@ -1941,8 +1941,8 @@ TEST_F(WideColumnEntityBlobExtractionTest,
Slice value_slice(output_values[0]);
std::vector<WideColumn> output_columns;
std::vector<std::pair<size_t, BlobIndex>> blob_columns;
ASSERT_OK(WideColumnSerialization::Deserialize(value_slice, output_columns,
&blob_columns));
ASSERT_OK(WideColumnSerialization::DeserializeV2(value_slice, output_columns,
blob_columns));
// All three columns should be blob references
ASSERT_EQ(3, blob_columns.size());
@@ -2014,8 +2014,8 @@ TEST_F(WideColumnEntityBlobExtractionTest, WideColumnEntityMixedSizes) {
Slice value_slice(output_values[0]);
std::vector<WideColumn> output_columns;
std::vector<std::pair<size_t, BlobIndex>> blob_columns;
ASSERT_OK(WideColumnSerialization::Deserialize(value_slice, output_columns,
&blob_columns));
ASSERT_OK(WideColumnSerialization::DeserializeV2(value_slice, output_columns,
blob_columns));
// Only the large column should be a blob reference
ASSERT_EQ(1, blob_columns.size());
@@ -2058,8 +2058,8 @@ TEST_F(WideColumnEntityBlobExtractionTest,
Slice value_slice(output_values[0]);
std::vector<WideColumn> output_columns;
std::vector<std::pair<size_t, BlobIndex>> blob_columns;
ASSERT_OK(WideColumnSerialization::Deserialize(value_slice, output_columns,
&blob_columns));
ASSERT_OK(WideColumnSerialization::DeserializeV2(value_slice, output_columns,
blob_columns));
// The default column should be a blob reference
ASSERT_EQ(1, blob_columns.size());
@@ -2078,14 +2078,11 @@ TEST_F(WideColumnEntityBlobExtractionTest,
// Mock BlobFetcher for testing blob GC without a real Version
class MockBlobFetcher : public BlobFetcher {
public:
MockBlobFetcher() = default;
using BlobFetcher::FetchBlob;
MockBlobFetcher() : BlobFetcher(nullptr /* version */, ReadOptions()) {}
Status FetchBlob(const Slice& /* user_key */, const BlobIndex& blob_index,
FilePrefetchBuffer* /* prefetch_buffer */,
PinnableSlice* blob_value,
uint64_t* bytes_read) const override {
PinnableSlice* blob_value, uint64_t* bytes_read) const {
auto it = blob_data_.find(
std::make_pair(blob_index.file_number(), blob_index.offset()));
if (it == blob_data_.end()) {
@@ -2099,8 +2096,6 @@ class MockBlobFetcher : public BlobFetcher {
return Status::OK();
}
const ReadOptions& read_options() const override { return read_options_; }
void AddBlob(uint64_t file_number, uint64_t offset,
const std::string& value) {
blob_data_[std::make_pair(file_number, offset)] = value;
@@ -2108,7 +2103,6 @@ class MockBlobFetcher : public BlobFetcher {
private:
std::map<std::pair<uint64_t, uint64_t>, std::string> blob_data_;
ReadOptions read_options_;
};
// FakeCompaction that supports blob garbage collection
@@ -2378,8 +2372,8 @@ TEST_F(WideColumnEntityBlobGCTest, WideColumnEntityBlobGCRelocate) {
Slice value_slice(output_values[0]);
std::vector<WideColumn> output_columns;
std::vector<std::pair<size_t, BlobIndex>> blob_columns_out;
ASSERT_OK(WideColumnSerialization::Deserialize(value_slice, output_columns,
&blob_columns_out));
ASSERT_OK(WideColumnSerialization::DeserializeV2(value_slice, output_columns,
blob_columns_out));
// Entity structure should be preserved
ASSERT_EQ(2, output_columns.size());
@@ -2437,8 +2431,8 @@ TEST_F(WideColumnEntityBlobGCTest, WideColumnEntityBlobGCNoRelocateNewerFile) {
Slice value_slice(output_values[0]);
std::vector<WideColumn> output_columns;
std::vector<std::pair<size_t, BlobIndex>> blob_columns_out;
ASSERT_OK(WideColumnSerialization::Deserialize(value_slice, output_columns,
&blob_columns_out));
ASSERT_OK(WideColumnSerialization::DeserializeV2(value_slice, output_columns,
blob_columns_out));
// Blob column should still exist and reference the same file
ASSERT_EQ(1, blob_columns_out.size());
@@ -2497,8 +2491,8 @@ TEST_F(WideColumnEntityBlobGCTest, WideColumnEntityBlobGCPartialRelocation) {
Slice value_slice(output_values[0]);
std::vector<WideColumn> output_columns;
std::vector<std::pair<size_t, BlobIndex>> blob_columns_out;
ASSERT_OK(WideColumnSerialization::Deserialize(value_slice, output_columns,
&blob_columns_out));
ASSERT_OK(WideColumnSerialization::DeserializeV2(value_slice, output_columns,
blob_columns_out));
// All three columns should exist
ASSERT_EQ(3, output_columns.size());
@@ -2569,8 +2563,8 @@ TEST_F(WideColumnEntityBlobGCTest, WideColumnEntityBlobGCToInline) {
Slice value_slice(output_values[0]);
std::vector<WideColumn> output_columns;
std::vector<std::pair<size_t, BlobIndex>> blob_columns_out;
ASSERT_OK(WideColumnSerialization::Deserialize(value_slice, output_columns,
&blob_columns_out));
ASSERT_OK(WideColumnSerialization::DeserializeV2(value_slice, output_columns,
blob_columns_out));
// Both columns should exist
ASSERT_EQ(2, output_columns.size());
@@ -2794,8 +2788,8 @@ TEST_F(WideColumnEntityBlobGCTest,
Slice value_slice(output_values[0]);
std::vector<WideColumn> output_columns;
std::vector<std::pair<size_t, BlobIndex>> output_blob_columns;
ASSERT_OK(WideColumnSerialization::Deserialize(value_slice, output_columns,
&output_blob_columns));
ASSERT_OK(WideColumnSerialization::DeserializeV2(value_slice, output_columns,
output_blob_columns));
ASSERT_EQ(2, output_columns.size());
ASSERT_EQ("alpha", output_columns[0].name().ToString());
+6 -14
View File
@@ -152,8 +152,7 @@ CompactionJob::CompactionJob(
const std::atomic<int>& compaction_aborted, const std::string& db_id,
const std::string& db_session_id, std::string full_history_ts_low,
std::string trim_ts, BlobFileCompletionCallback* blob_callback,
int* bg_compaction_scheduled, int* bg_bottom_compaction_scheduled,
std::atomic<int>* num_running_remote_compactions)
int* bg_compaction_scheduled, int* bg_bottom_compaction_scheduled)
: compact_(new CompactionState(compaction)),
internal_stats_(compaction->compaction_reason(), 1),
db_options_(db_options),
@@ -199,8 +198,7 @@ CompactionJob::CompactionJob(
blob_callback_(blob_callback),
extra_num_subcompaction_threads_reserved_(0),
bg_compaction_scheduled_(bg_compaction_scheduled),
bg_bottom_compaction_scheduled_(bg_bottom_compaction_scheduled),
num_running_remote_compactions_(num_running_remote_compactions) {
bg_bottom_compaction_scheduled_(bg_bottom_compaction_scheduled) {
assert(job_stats_ != nullptr);
assert(log_buffer_ != nullptr);
assert(job_context);
@@ -1670,12 +1668,8 @@ Status CompactionJob::ProcessKeyValue(
const uint64_t kCronEveryMask = (1 << 10) - 1;
[[maybe_unused]] const std::optional<const Slice> end = sub_compact->end;
// Check for abort signal before starting key processing. The DB-wide
// (AbortAllCompactions) and per-CF (AbortCompactions) counters compose here;
// either aborts this job. See DB::AbortCompactions() in db.h for how the
// abort knobs relate to each other and to the other compaction controls.
if (compaction_aborted_.load(std::memory_order_acquire) > 0 ||
cfd->compaction_aborted() > 0) {
// Check for abort signal before starting key processing
if (compaction_aborted_.load(std::memory_order_acquire) > 0) {
return Status::Incomplete(Status::SubCode::kCompactionAborted);
}
@@ -1697,8 +1691,7 @@ Status CompactionJob::ProcessKeyValue(
// Periodic cron operations: stats update, abort check.
if ((num_records & kCronEveryMask) == kCronEveryMask) {
// Check for abort signal periodically
if (compaction_aborted_.load(std::memory_order_acquire) > 0 ||
cfd->compaction_aborted() > 0) {
if (compaction_aborted_.load(std::memory_order_acquire) > 0) {
status = Status::Incomplete(Status::SubCode::kCompactionAborted);
break;
}
@@ -2620,8 +2613,7 @@ Status CompactionJob::OpenCompactionOutputFile(SubcompactionState* sub_compact,
bottommost_level_, TableFileCreationReason::kCompaction,
0 /* oldest_key_time */, current_time, db_id_, db_session_id_,
sub_compact->compaction->max_output_file_size(), file_number,
proximal_after_seqno_ /*last_level_inclusive_max_seqno_threshold*/,
dbname_ /*db_name*/, IsRemoteCompaction() /*is_remote_compaction*/);
proximal_after_seqno_ /*last_level_inclusive_max_seqno_threshold*/);
outputs.NewBuilder(tboptions);
+2 -14
View File
@@ -40,7 +40,7 @@
#include "rocksdb/db.h"
#include "rocksdb/env.h"
#include "rocksdb/memtablerep.h"
#include "rocksdb/wal_iterator.h"
#include "rocksdb/transaction_log.h"
#include "util/autovector.h"
#include "util/stop_watch.h"
#include "util/thread_local.h"
@@ -166,8 +166,7 @@ class CompactionJob {
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,
std::atomic<int>* num_running_remote_compactions = nullptr);
int* bg_bottom_compaction_scheduled = nullptr);
virtual ~CompactionJob();
@@ -501,12 +500,6 @@ class CompactionJob {
int* bg_compaction_scheduled_;
int* bg_bottom_compaction_scheduled_;
// Stores the pointer to DBImpl::num_running_remote_compactions_, backing the
// public rocksdb.num-running-remote-compactions property. Null when the job
// has no owning DBImpl to report to (compaction service workers, unit tests).
// Updated without the DB mutex held.
std::atomic<int>* num_running_remote_compactions_;
// Stores the sequence number to time mapping gathered from all input files
// it also collects the smallest_seqno -> oldest_ancester_time from the SST.
SeqnoToTimeMapping seqno_to_time_mapping_;
@@ -530,10 +523,6 @@ class CompactionJob {
// Get table file name in where it's outputting to, which should also be in
// `output_directory_`.
virtual std::string GetTableFileName(uint64_t file_number);
// True if this job builds output files as a remote (offloaded)
// CompactionService worker. Overridden by CompactionServiceCompactionJob.
virtual bool IsRemoteCompaction() const { return false; }
// The rate limiter priority (io_priority) is determined dynamically here.
// The Compaction Read and Write priorities are the same for different
// scenarios, such as write stalled.
@@ -741,7 +730,6 @@ class CompactionServiceCompactionJob : private CompactionJob {
private:
// Get table file name in output_path
std::string GetTableFileName(uint64_t file_number) override;
bool IsRemoteCompaction() const override { return true; }
// Specific the compaction output path, otherwise it uses default DB path
const std::string output_path_;
+13 -64
View File
@@ -15,7 +15,6 @@
#include "monitoring/thread_status_util.h"
#include "options/options_helper.h"
#include "rocksdb/utilities/options_type.h"
#include "util/defer.h"
namespace ROCKSDB_NAMESPACE {
class SubcompactionState;
@@ -115,6 +114,9 @@ CompactionJob::ProcessKeyValueCompactionWithCompactionService(
break;
}
std::string debug_str_before_wait =
compaction->input_version()->DebugString(/*hex=*/true);
// TODO: Update CompactionService API to support abort and resume
// functionality. Currently, remote compaction jobs cannot be aborted via
// AbortAllCompactions() because the CompactionService interface lacks methods
@@ -127,29 +129,18 @@ CompactionJob::ProcessKeyValueCompactionWithCompactionService(
"[%s] [JOB %d] Waiting for remote compaction...",
compaction->column_family_data()->GetName().c_str(), job_id_);
std::string compaction_result_binary;
CompactionServiceJobStatus compaction_status;
{
// Increment rocksdb.num-running-remote-compactions while this compaction
// service job is waiting in CompactionService::Wait().
std::atomic<int>* const num_running = num_running_remote_compactions_;
if (num_running != nullptr) {
num_running->fetch_add(1, std::memory_order_relaxed);
}
Defer decrement_num_running([num_running]() {
if (num_running != nullptr) {
num_running->fetch_sub(1, std::memory_order_relaxed);
}
});
compaction_status = db_options_.compaction_service->Wait(
response.scheduled_job_id, &compaction_result_binary);
}
CompactionServiceJobStatus compaction_status =
db_options_.compaction_service->Wait(response.scheduled_job_id,
&compaction_result_binary);
if (compaction_status != CompactionServiceJobStatus::kSuccess) {
ROCKS_LOG_ERROR(
db_options_.info_log,
"[%s] [JOB %d] Wait() status is not kSuccess. "
"\nDebugString Before Wait():\n%s"
"\nDebugString After Wait():\n%s",
compaction->column_family_data()->GetName().c_str(), job_id_,
debug_str_before_wait.c_str(),
compaction->input_version()->DebugString(/*hex=*/true).c_str());
}
@@ -786,40 +777,6 @@ static std::unordered_map<std::string, OptionTypeInfo>
OptionTypeFlags::kNone}},
};
namespace {
// Like OptionTypeInfo::Array<T, kSize> but deserialization tolerates
// size mismatches: extra elements beyond kSize are silently ignored,
// missing elements are zero-filled. Serialization and comparison are
// inherited from Array<T, kSize> unchanged; only the parse
// (deserialize) callback is overridden.
template <typename T, size_t kSize>
OptionTypeInfo SizeTolerantDeserializeArray(int offset,
OptionVerificationType verification,
OptionTypeFlags flags,
const OptionTypeInfo& elem_info,
char separator = ':') {
return OptionTypeInfo::Array<T, kSize>(offset, verification, flags, elem_info,
separator)
.SetParseFunc([elem_info, separator](
const ConfigOptions& opts, const std::string& name,
const std::string& value, void* addr) {
std::vector<T> parsed;
Status s =
ParseVector<T>(opts, elem_info, separator, name, value, &parsed);
if (!s.ok()) {
return Status(std::move(s));
}
auto* arr = static_cast<std::array<T, kSize>*>(addr);
for (size_t i = 0; i < kSize; ++i) {
(*arr)[i] = (i < parsed.size()) ? parsed[i] : T{};
}
return Status::OK();
});
}
} // namespace
static std::unordered_map<std::string, OptionTypeInfo>
compaction_stats_type_info = {
{"micros",
@@ -911,20 +868,12 @@ static std::unordered_map<std::string, OptionTypeInfo>
{offsetof(struct InternalStats::CompactionStats, count),
OptionType::kUInt64T, OptionVerificationType::kNormal,
OptionTypeFlags::kNone}},
// The remote worker may serialize a different number of
// CompactionReason counts than this primary expects (RocksDB versions
// can disagree on kNumOfReasons). Deserialization tolerates the
// mismatch: extra trailing elements are dropped, missing ones are
// zero-filled.
//
// The serialized width is intentionally kept at kNumOfReasons - 1 (the
// reduced width) so this change does NOT alter what is written -- only
// the read path becomes tolerant. Widening the serialized width to the
// full kNumOfReasons is a separate, later change that must not land
// until this tolerant read has been deployed to every primary,
// including rollback targets.
{"counts",
SizeTolerantDeserializeArray<
OptionTypeInfo::Array<
/* In release 11.2, a new compaction reason was added. This broken
* the reader and writer. To unblock release 11.1, we temporarily
* reduce the count array size to the old one. TODO add a proper
* serialization and deserialization method. */
int, static_cast<int>(CompactionReason::kNumOfReasons) - 1>(
offsetof(struct InternalStats::CompactionStats, counts),
OptionVerificationType::kNormal, OptionTypeFlags::kNone,
-345
View File
@@ -3,86 +3,15 @@
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
#include <atomic>
#include <memory>
#include "db/db_test_util.h"
#include "file/file_util.h"
#include "port/stack_trace.h"
#include "rocksdb/advanced_compression.h"
#include "rocksdb/filter_policy.h"
#include "rocksdb/utilities/object_registry.h"
#include "rocksdb/utilities/options_util.h"
#include "table/unique_id_impl.h"
#include "utilities/merge_operators/string_append/stringappend.h"
namespace ROCKSDB_NAMESPACE {
namespace {
// Append ":extra_value" to every "counts=...;" field in a serialized
// CompactionServiceResult string to simulate a worker with more
// CompactionReason enums than the reader. Loops because the serialized
// result contains multiple CompactionStats structs (output_level_stats,
// proximal_level_stats), each with its own "counts=" field.
void AppendToCountsFields(std::string* s, const std::string& extra_value) {
const std::string prefix = "counts=";
size_t pos = s->find(prefix);
while (pos != std::string::npos) {
// Find the semicolon that terminates this field's value.
size_t semi = s->find(';', pos + prefix.size());
assert(semi != std::string::npos);
// Insert ":extra_value" just before the semicolon.
s->insert(semi, ":" + extra_value);
// Advance past the inserted text to find the next occurrence.
pos = s->find(prefix, semi + extra_value.size() + 2);
}
}
// Remove the last colon-separated element from every "counts=...;" field
// to simulate a worker with fewer CompactionReason enums than the reader.
// Loops for the same reason as AppendToCountsFields (multiple counts fields).
void RemoveLastFromCountsFields(std::string* s) {
const std::string prefix = "counts=";
size_t pos = s->find(prefix);
while (pos != std::string::npos) {
size_t val_begin = pos + prefix.size();
size_t semi = s->find(';', val_begin);
assert(semi != std::string::npos);
// Find the last ':' separator within the value.
size_t last_sep = s->rfind(':', semi - 1);
assert(last_sep != std::string::npos && last_sep >= val_begin);
// Erase from the last ':' up to (not including) the ';'.
// e.g. "counts=0:3:5;" -> erase ":5" -> "counts=0:3;"
s->erase(last_sep, semi - last_sep);
pos = s->find(prefix, last_sep);
}
}
// Count the colon-separated elements in the first "counts=...;" field of a
// serialized CompactionServiceResult. Used to assert the serialized width
// (how many CompactionReason counts this binary writes).
size_t CountFirstCountsFieldElements(const std::string& s) {
const std::string prefix = "counts=";
size_t pos = s.find(prefix);
assert(pos != std::string::npos);
size_t val_begin = pos + prefix.size();
size_t semi = s.find(';', val_begin);
assert(semi != std::string::npos);
if (semi == val_begin) {
return 0;
}
size_t count = 1;
for (size_t i = val_begin; i < semi; ++i) {
if (s[i] == ':') {
++count;
}
}
return count;
}
} // namespace
class MyTestCompactionService : public CompactionService {
public:
MyTestCompactionService(
@@ -364,7 +293,6 @@ class CompactionServiceTest : public DBTestBase {
TEST_F(CompactionServiceTest, BasicCompactions) {
Options options = CurrentOptions();
options.max_open_files = -1;
ReopenWithCompactionService(&options);
Statistics* primary_statistics = GetPrimaryStatistics();
@@ -485,113 +413,6 @@ TEST_F(CompactionServiceTest, BasicCompactions) {
SyncPoint::GetInstance()->DisableProcessing();
}
namespace {
// A CompressionManager that records, per GetCompressorForSST() call, whether
// the FilterBuildingContext reports the SST as being built by a remote
// (offloaded) compaction worker. Observations go into process-global counters
// because the remote worker reconstructs its own manager instance from the
// persisted OPTIONS file (same process in this test).
struct RemoteAwareObservations {
std::atomic<int> num_remote{0};
std::atomic<int> num_non_remote{0};
void Reset() {
num_remote.store(0);
num_non_remote.store(0);
}
};
RemoteAwareObservations& GetRemoteAwareObservations() {
static RemoteAwareObservations obs;
return obs;
}
class RemoteAwareCompressionManager : public CompressionManagerWrapper {
public:
RemoteAwareCompressionManager()
: CompressionManagerWrapper(GetBuiltinV2CompressionManager()) {}
static const char* kClassName() { return "RemoteAwareCompressionManager"; }
const char* Name() const override { return kClassName(); }
std::unique_ptr<Compressor> GetCompressorForSST(
const FilterBuildingContext& context, const CompressionOptions& opts,
CompressionType preferred) override {
if (context.is_remote_compaction) {
GetRemoteAwareObservations().num_remote.fetch_add(1);
} else {
GetRemoteAwareObservations().num_non_remote.fetch_add(1);
}
return CompressionManagerWrapper::GetCompressorForSST(context, opts,
preferred);
}
};
} // namespace
TEST_F(CompactionServiceTest, IsRemoteCompactionInCompressorContext) {
// Register so the remote worker's DB::OpenAndCompact can reconstruct the
// custom CompressionManager from the persisted OPTIONS file
// (CompactionServiceOptionsOverride does not carry a compression_manager).
ObjectLibrary::Default()->AddFactory<CompressionManager>(
RemoteAwareCompressionManager::kClassName(),
[](const std::string& /*uri*/, std::unique_ptr<CompressionManager>* guard,
std::string* /*errmsg*/) {
*guard = std::make_unique<RemoteAwareCompressionManager>();
return guard->get();
});
auto& obs = GetRemoteAwareObservations();
obs.Reset();
Options options = CurrentOptions();
options.compression_manager =
std::make_shared<RemoteAwareCompressionManager>();
ReopenWithCompactionService(&options);
GenerateTestData();
ASSERT_OK(dbfull()->TEST_WaitForCompact());
VerifyTestData();
auto my_cs = GetCompactionService();
ASSERT_GE(my_cs->GetCompactionNum(), 1);
// The offloaded worker built the compaction output SSTs and therefore must
// have observed is_remote_compaction == true in GetCompressorForSST().
ASSERT_GT(obs.num_remote.load(), 0);
// The primary's own flushes, seen by the same manager, must report false
ASSERT_GT(obs.num_non_remote.load(), 0);
Close();
}
TEST_F(CompactionServiceTest, IsRemoteCompactionFalseForLocalCompaction) {
// Same custom manager, but no compaction_service: everything runs locally,
// so GetCompressorForSST() must never see is_remote_compaction == true.
auto& obs = GetRemoteAwareObservations();
obs.Reset();
Options options = CurrentOptions();
options.compression_manager =
std::make_shared<RemoteAwareCompressionManager>();
DestroyAndReopen(options);
Random rnd(301);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 100; j++) {
ASSERT_OK(Put(Key(i * 100 + j), rnd.RandomString(64)));
}
ASSERT_OK(Flush());
}
ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
// Local flushes and compactions must all report not-remote.
ASSERT_GT(obs.num_non_remote.load(), 0);
ASSERT_EQ(obs.num_remote.load(), 0);
Close();
}
TEST_F(CompactionServiceTest, SkipWALRecoveryInOpenAndCompact) {
// Verify that OpenAndCompact skips WAL recovery when opening the secondary
// instance. WAL replay is unnecessary for remote compaction since it only
@@ -1788,68 +1609,6 @@ TEST_F(CompactionServiceTest, InvalidResultFallsBackToLocal) {
my_cs->GetFinalCompactionServiceJobStatus());
}
TEST_F(CompactionServiceTest, CompatCheckCountsWidthTolerance) {
// Number of per-CompactionReason counts this binary serializes and expects.
constexpr size_t kExpected =
static_cast<size_t>(CompactionReason::kNumOfReasons) - 1;
constexpr size_t kLastIndex = kExpected - 1;
constexpr int kFirstCount = 3;
constexpr int kLastCount = 5;
CompactionServiceResult result;
result.status = Status::OK();
result.output_level = 2;
result.output_path = "/tmp/output";
result.internal_stats.output_level_stats.counts[0] = kFirstCount;
result.internal_stats.output_level_stats.counts[kLastIndex] = kLastCount;
std::string serialized;
ASSERT_OK(result.Write(&serialized));
// Guard the produced format: this binary writes exactly kExpected counts.
// That element count is what a remote worker hands to the primary to read,
// so pinning it catches an accidental change to what is written.
ASSERT_EQ(CountFirstCountsFieldElements(serialized), kExpected);
// Peer agrees on kNumOfReasons: every written count is read back unchanged.
{
CompactionServiceResult parsed;
ASSERT_OK(CompactionServiceResult::Read(serialized, &parsed));
ASSERT_OK(parsed.status);
const auto& counts = parsed.internal_stats.output_level_stats.counts;
ASSERT_EQ(counts[0], kFirstCount);
ASSERT_EQ(counts[kLastIndex], kLastCount);
}
// Peer serialized one more count than this binary knows (a worker with an
// extra CompactionReason): the surplus trailing count is ignored, and the
// counts this binary understands are read unchanged.
{
std::string from_wider_peer = serialized;
AppendToCountsFields(&from_wider_peer, "7");
ASSERT_EQ(CountFirstCountsFieldElements(from_wider_peer), kExpected + 1);
CompactionServiceResult parsed;
ASSERT_OK(CompactionServiceResult::Read(from_wider_peer, &parsed));
ASSERT_OK(parsed.status);
const auto& counts = parsed.internal_stats.output_level_stats.counts;
ASSERT_EQ(counts[0], kFirstCount);
ASSERT_EQ(counts[kLastIndex], kLastCount);
}
// Peer serialized one fewer count than this binary knows (a worker missing
// the newest CompactionReason): the absent trailing count reads as zero.
{
std::string from_narrower_peer = serialized;
RemoveLastFromCountsFields(&from_narrower_peer);
ASSERT_EQ(CountFirstCountsFieldElements(from_narrower_peer), kExpected - 1);
CompactionServiceResult parsed;
ASSERT_OK(CompactionServiceResult::Read(from_narrower_peer, &parsed));
ASSERT_OK(parsed.status);
const auto& counts = parsed.internal_stats.output_level_stats.counts;
ASSERT_EQ(counts[0], kFirstCount);
ASSERT_EQ(counts[kLastIndex], 0);
}
}
TEST_F(CompactionServiceTest, SubCompaction) {
Options options = CurrentOptions();
options.max_subcompactions = 10;
@@ -1873,109 +1632,6 @@ TEST_F(CompactionServiceTest, SubCompaction) {
ASSERT_GE(compaction_num, 2);
}
class PropertySamplingCompactionService : public MyTestCompactionService {
public:
using MyTestCompactionService::MyTestCompactionService;
void SetPrimaryDB(DB* db) { db_ = db; }
CompactionServiceJobStatus Wait(const std::string& scheduled_job_id,
std::string* result) override {
EXPECT_TRUE(
db_->GetIntProperty(DB::Properties::kNumRunningRemoteCompactions,
&num_running_while_waiting_));
return MyTestCompactionService::Wait(scheduled_job_id, result);
}
uint64_t GetNumRunningWhileWaiting() const {
return num_running_while_waiting_;
}
private:
DB* db_ = nullptr;
uint64_t num_running_while_waiting_ = 0;
};
TEST_F(CompactionServiceTest, NumRunningRemoteCompactionsProperty) {
Options options = CurrentOptions();
options.disable_auto_compactions = true;
options.env = env_;
auto statistics = CreateDBStatistics();
auto compaction_service = std::make_shared<PropertySamplingCompactionService>(
dbname_, options, statistics,
std::vector<std::shared_ptr<EventListener>>{},
std::vector<std::shared_ptr<TablePropertiesCollectorFactory>>{});
options.compaction_service = compaction_service;
DestroyAndReopen(options);
compaction_service->SetPrimaryDB(db_.get());
// Overlapping key ranges across files so the compaction is not a trivial
// move, which would bypass the compaction service entirely.
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 10; j++) {
ASSERT_OK(Put(Key(j), "value" + std::to_string(i * 10 + j)));
}
ASSERT_OK(Flush());
}
// No remote compaction is in flight yet.
uint64_t num_running = 0;
ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kNumRunningRemoteCompactions,
&num_running));
ASSERT_EQ(num_running, 0U);
ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
ASSERT_GE(compaction_service->GetCompactionNum(), 1);
ASSERT_GE(compaction_service->GetNumRunningWhileWaiting(), 1U);
// The counter is back to 0 once the remote jobs are installed.
ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kNumRunningRemoteCompactions,
&num_running));
ASSERT_EQ(num_running, 0U);
}
TEST_F(CompactionServiceTest, NumRunningRemoteCompactionsPropertyLocalOnly) {
// Without a compaction_service configured, the property stays 0.
Options options = CurrentOptions();
options.disable_auto_compactions = true;
DestroyAndReopen(options);
// Overlapping key ranges across files so the compaction is not a trivial
// move, which would bypass the compaction service entirely.
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 10; j++) {
ASSERT_OK(Put(Key(j), "value" + std::to_string(i * 10 + j)));
}
ASSERT_OK(Flush());
}
std::atomic<int> property_samples{0};
std::atomic_bool observed_non_zero{false};
SyncPoint::GetInstance()->SetCallBack(
"CompactionJob::ProcessKeyValueCompaction()::Processing",
[&](void* /*arg*/) {
uint64_t num_running = 0;
EXPECT_TRUE(db_->GetIntProperty(
DB::Properties::kNumRunningRemoteCompactions, &num_running));
property_samples.fetch_add(1);
if (num_running != 0) {
observed_non_zero.store(true);
}
});
SyncPoint::GetInstance()->EnableProcessing();
ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
SyncPoint::GetInstance()->DisableProcessing();
SyncPoint::GetInstance()->ClearAllCallBacks();
ASSERT_GT(property_samples.load(), 0);
ASSERT_FALSE(observed_non_zero.load());
uint64_t num_running = 0;
ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kNumRunningRemoteCompactions,
&num_running));
ASSERT_EQ(num_running, 0U);
}
class PartialDeleteCompactionFilter : public CompactionFilter {
public:
CompactionFilter::Decision FilterV2(
@@ -1994,7 +1650,6 @@ class PartialDeleteCompactionFilter : public CompactionFilter {
TEST_F(CompactionServiceTest, CompactionFilter) {
Options options = CurrentOptions();
options.disable_auto_compactions = true;
std::unique_ptr<CompactionFilter> delete_comp_filter(
new PartialDeleteCompactionFilter());
options.compaction_filter = delete_comp_filter.get();
-160
View File
@@ -1,160 +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 "rocksdb/rocksdb_namespace.h"
#if USE_COROUTINES
#include <algorithm>
#include <array>
#include <cassert>
#include <vector>
#include "folly/Executor.h"
#include "folly/coro/Nothrow.h"
#include "folly/executors/IOExecutor.h"
#include "folly/io/async/EventBase.h"
#include "rocksdb/coro_db.h"
#include "rocksdb/file_system.h"
#include "table/multiget_context.h"
namespace ROCKSDB_NAMESPACE {
folly::coro::Task<Status> CoroDB::CoGet(DB* db, const ReadOptions& options,
ColumnFamilyHandle* column_family,
const Slice& key, PinnableSlice* value,
std::string* timestamp) {
assert(db != nullptr);
CoroDB* coro_db = db->GetCoroDB();
auto* file_system = db->GetFileSystem();
auto* read_executor =
file_system == nullptr ? nullptr : file_system->GetReadExecutor();
auto* read_event_base =
read_executor == nullptr ? nullptr : read_executor->getEventBase();
Status status;
if (coro_db == nullptr || read_event_base == nullptr) {
status = db->Get(options, column_family, key, value, timestamp);
} else {
status = co_await folly::coro::co_nothrow(folly::coro::co_withExecutor(
folly::Executor::getKeepAliveToken(read_event_base),
coro_db->GetCoroutine(options, column_family, key, value, timestamp)));
}
co_return status;
}
folly::coro::Task<Status> CoroDB::CoGet(DB* db, const ReadOptions& options,
ColumnFamilyHandle* column_family,
const Slice& key, std::string* value,
std::string* timestamp) {
assert(value != nullptr);
PinnableSlice pinnable_value(value);
assert(!pinnable_value.IsPinned());
Status status = co_await folly::coro::co_nothrow(
CoGet(db, options, column_family, key, &pinnable_value, timestamp));
if (status.ok() && pinnable_value.IsPinned()) {
value->assign(pinnable_value.data(), pinnable_value.size());
}
co_return status;
}
folly::coro::Task<Status> CoroDB::CoGet(DB* db, const ReadOptions& options,
const Slice& key, std::string* value) {
assert(db != nullptr);
return CoGet(db, options, db->DefaultColumnFamily(), key, value);
}
folly::coro::Task<Status> CoroDB::CoGet(DB* db, const ReadOptions& options,
const Slice& key, std::string* value,
std::string* timestamp) {
assert(db != nullptr);
return CoGet(db, options, db->DefaultColumnFamily(), key, value, timestamp);
}
folly::coro::Task<std::vector<Status>> CoroDB::CoMultiGet(
DB* db, const ReadOptions& options,
const std::vector<ColumnFamilyHandle*>& column_families,
const std::vector<Slice>& keys, std::vector<std::string>* values,
std::vector<std::string>* timestamps) {
const size_t num_keys = keys.size();
std::vector<Status> statuses(num_keys);
std::vector<PinnableSlice> pinnable_values(num_keys);
values->resize(num_keys);
if (timestamps != nullptr) {
timestamps->resize(num_keys);
}
co_await folly::coro::co_nothrow(CoMultiGet(
db, options, num_keys,
const_cast<ColumnFamilyHandle**>(column_families.data()), keys.data(),
pinnable_values.data(),
timestamps == nullptr ? nullptr : timestamps->data(), statuses.data(),
/*sorted_input=*/false));
for (size_t i = 0; i < num_keys; ++i) {
if (statuses[i].ok()) {
(*values)[i].assign(pinnable_values[i].data(), pinnable_values[i].size());
}
}
co_return statuses;
}
folly::coro::Task<std::vector<Status>> CoroDB::CoMultiGet(
DB* db, const ReadOptions& options, const std::vector<Slice>& keys,
std::vector<std::string>* values, std::vector<std::string>* timestamps) {
assert(db != nullptr);
std::vector<ColumnFamilyHandle*> column_families(keys.size(),
db->DefaultColumnFamily());
co_return co_await folly::coro::co_nothrow(
CoMultiGet(db, options, column_families, keys, values, timestamps));
}
folly::coro::Task<void> CoroDB::CoMultiGet(
DB* db, const ReadOptions& options, size_t num_keys,
ColumnFamilyHandle** column_families, const Slice* keys,
PinnableSlice* values, std::string* timestamps, Status* statuses,
bool sorted_input) {
assert(db != nullptr);
CoroDB* coro_db = db->GetCoroDB();
auto* file_system = db->GetFileSystem();
auto* read_executor =
file_system == nullptr ? nullptr : file_system->GetReadExecutor();
auto* read_event_base =
read_executor == nullptr ? nullptr : read_executor->getEventBase();
if (coro_db == nullptr || read_event_base == nullptr) {
db->MultiGet(options, num_keys, column_families, keys, values, timestamps,
statuses, sorted_input);
} else {
co_await folly::coro::co_nothrow(folly::coro::co_withExecutor(
folly::Executor::getKeepAliveToken(read_event_base),
coro_db->MultiGetCoroutine(options, num_keys, column_families, keys,
values, timestamps, statuses,
sorted_input)));
}
}
folly::coro::Task<void> CoroDB::CoMultiGet(
DB* db, const ReadOptions& options, ColumnFamilyHandle* column_family,
size_t num_keys, const Slice* keys, PinnableSlice* values,
std::string* timestamps, Status* statuses, bool sorted_input) {
if (num_keys > MultiGetContext::MAX_BATCH_SIZE) {
std::vector<ColumnFamilyHandle*> column_families(num_keys, column_family);
co_await folly::coro::co_nothrow(
CoMultiGet(db, options, num_keys, column_families.data(), keys, values,
timestamps, statuses, sorted_input));
} else {
std::array<ColumnFamilyHandle*, MultiGetContext::MAX_BATCH_SIZE>
column_families;
std::fill(column_families.begin(), column_families.begin() + num_keys,
column_family);
co_await folly::coro::co_nothrow(
CoMultiGet(db, options, num_keys, column_families.data(), keys, values,
timestamps, statuses, sorted_input));
}
}
} // namespace ROCKSDB_NAMESPACE
#endif // USE_COROUTINES
+272 -363
View File
@@ -10,9 +10,6 @@
#include <cstring>
#include "db/db_test_util.h"
#include "db/log_writer.h"
#include "db/version_edit.h"
#include "file/writable_file_writer.h"
#include "options/options_helper.h"
#include "port/stack_trace.h"
#include "rocksdb/filter_policy.h"
@@ -81,7 +78,6 @@ class MyFlushBlockPolicyFactory : public FlushBlockPolicyFactory {
private:
const int num_keys_in_block_;
};
} // namespace
static bool enable_io_uring = true;
@@ -92,15 +88,6 @@ class DBBasicTest : public DBTestBase {
DBBasicTest() : DBTestBase("db_basic_test", /*env_do_fsync=*/false) {}
};
class DBBasicGetWithParam : public DBBasicTest,
public testing::WithParamInterface<bool> {
public:
DBBasicGetWithParam() : DBBasicTest(), use_coroutine_(GetParam()) {}
protected:
const bool use_coroutine_;
};
TEST_F(DBBasicTest, OpenWhenOpen) {
Options options = CurrentOptions();
options.env = env_;
@@ -220,9 +207,8 @@ TEST_F(DBBasicTest, OptimizeManifestForRecoveryEmitsPerCFWhenLogAdvances) {
ASSERT_EQ("v", Get("k"));
}
// With track_and_verify_wals_in_manifest=true and a clean close, the
// close-time code already advances WalSet markers. Recovery's
// DeleteWalsBefore is redundant and should be skipped.
// With track_and_verify_wals_in_manifest=true, the wal_deletion edit
// must STILL be emitted (the DeleteWalsBefore record is required).
TEST_F(DBBasicTest, OptimizeManifestForRecoveryPreservesWalTracking) {
Options options = CurrentOptions();
options.create_if_missing = true;
@@ -238,7 +224,7 @@ TEST_F(DBBasicTest, OptimizeManifestForRecoveryPreservesWalTracking) {
Reopen(options);
counters.Uninstall();
ASSERT_EQ(1, counters.wal_deletion.load());
ASSERT_EQ(0, counters.wal_deletion.load());
}
// best_efforts_recovery requires a fresh MANIFEST + CURRENT to be
@@ -511,60 +497,11 @@ TEST_F(DBBasicTest, OptimizeManifestForRecoveryEmitsWalDeletionWhenTracking) {
counters.Uninstall();
ASSERT_GT(counters.per_cf.load(), 0);
ASSERT_EQ(0, records.load());
ASSERT_EQ(1, records.load());
ASSERT_GT(dbfull()->GetVersionSet()->GetWalSet().GetMinWalNumberToKeep(), 0u);
ASSERT_EQ("v", Get("k"));
}
// Zero MANIFEST growth on clean reopen with optimize_manifest_for_recovery=1,
// reuse_manifest_on_open=1, and track_and_verify_wals_in_manifest=1.
// Regression test for the stress test failure where a redundant
// DeleteWalsBefore edit was written during recovery.
TEST_F(DBBasicTest, OptimizeManifestForRecoveryZeroGrowthOnCleanReopen) {
Options options = CurrentOptions();
options.create_if_missing = true;
options.optimize_manifest_for_recovery = true;
options.reuse_manifest_on_open = true;
options.track_and_verify_wals_in_manifest = true;
options.avoid_flush_during_recovery = true;
options.write_dbid_to_manifest = false;
DestroyAndReopen(options);
ASSERT_OK(Put("k", "v"));
ASSERT_OK(Flush());
Close();
// Get MANIFEST size after close
std::vector<std::string> files;
ASSERT_OK(env_->GetChildren(dbname_, &files));
uint64_t manifest_size_before = 0;
for (const auto& f : files) {
if (f.find("MANIFEST-") == 0) {
ASSERT_OK(env_->GetFileSize(dbname_ + "/" + f, &manifest_size_before));
break;
}
}
ASSERT_GT(manifest_size_before, 0u);
// Reopen - should not grow MANIFEST at all
Reopen(options);
// Get MANIFEST size after reopen
files.clear();
ASSERT_OK(env_->GetChildren(dbname_, &files));
uint64_t manifest_size_after = 0;
for (const auto& f : files) {
if (f.find("MANIFEST-") == 0) {
ASSERT_OK(env_->GetFileSize(dbname_ + "/" + f, &manifest_size_after));
break;
}
}
ASSERT_EQ(manifest_size_before, manifest_size_after)
<< "MANIFEST grew by " << (manifest_size_after - manifest_size_before)
<< " bytes on clean reopen; expected zero growth";
ASSERT_EQ("v", Get("k"));
}
// Regression for the close-time marker path: if a new WAL is created while an
// otherwise-empty user CF stays empty, Close() must reserve the next file
// number before persisting SetLogNumber(cur_wal + 1) for that CF.
@@ -1021,92 +958,6 @@ TEST_F(DBBasicTest, ReuseManifestOnOpenSkipsOnTailCorruption) {
ASSERT_EQ("v", Get("k"));
}
// Regression test for corrupted atomic group when reuse_manifest_on_open
// appends after an incomplete atomic group at the MANIFEST tail.
// Before the fix, last_valid_record_end_ included records from an incomplete
// trailing atomic group, causing ReopenManifestForAppend to append new records
// after them. On subsequent recovery the incomplete group followed by new
// records triggers "corrupted atomic group".
TEST_F(DBBasicTest, ReuseManifestOnOpenIncompleteAtomicGroupAtTail) {
Options options = CurrentOptions();
options.create_if_missing = true;
options.reuse_manifest_on_open = true;
DestroyAndReopen(options);
ASSERT_OK(Put("k", "v"));
ASSERT_OK(Flush());
Close();
// Find the MANIFEST file.
std::string manifest_path;
{
std::vector<std::string> files;
ASSERT_OK(env_->GetChildren(dbname_, &files));
for (const auto& f : files) {
uint64_t number;
FileType type;
if (ParseFileName(f, &number, &type) && type == kDescriptorFile) {
manifest_path = dbname_ + "/" + f;
break;
}
}
}
ASSERT_FALSE(manifest_path.empty());
// Append an incomplete atomic group (2 records of a 3-member group) to the
// MANIFEST. These are valid log records with correct CRCs but the atomic
// group is not complete (missing the third record with remaining_entries=0).
{
uint64_t file_size;
ASSERT_OK(env_->GetFileSize(manifest_path, &file_size));
const auto& fs = env_->GetFileSystem();
std::unique_ptr<FSWritableFile> fs_file;
ASSERT_OK(fs->ReopenWritableFile(manifest_path, FileOptions(), &fs_file,
nullptr));
std::unique_ptr<WritableFileWriter> file_writer(new WritableFileWriter(
std::move(fs_file), manifest_path, FileOptions()));
log::Writer log_writer(std::move(file_writer), 0, false, false,
kNoCompression, false, file_size % log::kBlockSize);
// Write 2 records of a 3-member atomic group
VersionEdit edit1;
edit1.SetLogNumber(0);
edit1.SetNextFile(100);
edit1.SetLastSequence(100);
edit1.MarkAtomicGroup(2); // remaining_entries=2, expects 3 total
std::string record1;
ASSERT_TRUE(edit1.EncodeTo(&record1, 0));
ASSERT_OK(log_writer.AddRecord(WriteOptions(), record1));
VersionEdit edit2;
edit2.SetLogNumber(0);
edit2.SetNextFile(100);
edit2.SetLastSequence(100);
edit2.MarkAtomicGroup(1); // remaining_entries=1
std::string record2;
ASSERT_TRUE(edit2.EncodeTo(&record2, 0));
ASSERT_OK(log_writer.AddRecord(WriteOptions(), record2));
// Deliberately NOT writing the third record (remaining_entries=0)
}
// Reopen: recovery should succeed (incomplete trailing group is ignored).
// With the fix, ReopenManifestForAppend will NOT reuse the MANIFEST because
// manifest_last_valid_record_end_ < physical_size (the incomplete group
// records are excluded from the valid end).
Reopen(options);
ASSERT_EQ("v", Get("k"));
// Write new data to create new MANIFEST records.
ASSERT_OK(Put("k2", "v2"));
ASSERT_OK(Flush());
Close();
// Final reopen: must NOT fail with "corrupted atomic group".
Reopen(options);
ASSERT_EQ("v", Get("k"));
ASSERT_EQ("v2", Get("k2"));
Close();
}
TEST_F(DBBasicTest, EnableDirectIOWithZeroBuf) {
if (!IsDirectIOSupported()) {
ROCKSDB_GTEST_BYPASS("Direct IO not supported");
@@ -1469,36 +1320,27 @@ TEST_F(DBBasicTest, LevelLimitReopen) {
ASSERT_OK(TryReopenWithColumnFamilies({"default", "pikachu"}, options));
}
TEST_P(DBBasicGetWithParam, PutDeleteGet) {
TEST_F(DBBasicTest, PutDeleteGet) {
do {
CreateAndReopenWithCF({"pikachu"}, CurrentOptions());
ASSERT_OK(Put(1, "foo", "v1"));
ASSERT_EQ("v1", Get(1, "foo", nullptr, use_coroutine_));
ASSERT_EQ("v1", Get(1, "foo"));
ASSERT_OK(Put(1, "foo", "v2"));
ASSERT_EQ("v2", Get(1, "foo", nullptr, use_coroutine_));
ASSERT_EQ("v2", Get(1, "foo"));
ASSERT_OK(Delete(1, "foo"));
ASSERT_EQ("NOT_FOUND", Get(1, "foo", nullptr, use_coroutine_));
ASSERT_OK(Put("default_foo", "default_v1"));
ASSERT_EQ("default_v1",
Get("default_foo", static_cast<const Snapshot*>(nullptr),
use_coroutine_));
PinnableSlice default_pinnable_value;
ASSERT_OK(Get("default_foo", &default_pinnable_value, use_coroutine_));
ASSERT_EQ("default_v1", default_pinnable_value.ToString());
ASSERT_EQ("NOT_FOUND", Get(1, "foo"));
} while (ChangeOptions());
}
TEST_P(DBBasicGetWithParam, PutSingleDeleteGet) {
TEST_F(DBBasicTest, PutSingleDeleteGet) {
do {
CreateAndReopenWithCF({"pikachu"}, CurrentOptions());
ASSERT_OK(Put(1, "foo", "v1"));
ASSERT_EQ("v1", Get(1, "foo", nullptr, use_coroutine_));
ASSERT_EQ("v1", Get(1, "foo"));
ASSERT_OK(Put(1, "foo2", "v2"));
ASSERT_EQ("v2", Get(1, "foo2", nullptr, use_coroutine_));
ASSERT_EQ("v2", Get(1, "foo2"));
ASSERT_OK(SingleDelete(1, "foo"));
ASSERT_EQ("NOT_FOUND", Get(1, "foo", nullptr, use_coroutine_));
ASSERT_EQ("NOT_FOUND", Get(1, "foo"));
// Ski FIFO and universal compaction because they do not apply to the test
// case. Skip MergePut because single delete does not get removed when it
// encounters a merge.
@@ -1506,40 +1348,40 @@ TEST_P(DBBasicGetWithParam, PutSingleDeleteGet) {
kSkipMergePut));
}
TEST_P(DBBasicGetWithParam, TimedPutBasic) {
TEST_F(DBBasicTest, TimedPutBasic) {
do {
Options options = CurrentOptions();
options.merge_operator = MergeOperators::CreateStringAppendOperator();
CreateAndReopenWithCF({"pikachu"}, options);
ASSERT_OK(TimedPut(1, "foo", "v1", /*write_unix_time=*/0));
// Read from memtable
ASSERT_EQ("v1", Get(1, "foo", nullptr, use_coroutine_));
ASSERT_EQ("v1", Get(1, "foo"));
ASSERT_OK(TimedPut(1, "foo", "v2.1", /*write_unix_time=*/3));
ASSERT_EQ("v2.1", Get(1, "foo", nullptr, use_coroutine_));
ASSERT_EQ("v2.1", Get(1, "foo"));
// Read from sst file
ASSERT_OK(db_->Flush(FlushOptions(), handles_[1]));
ASSERT_OK(Merge(1, "foo", "v2.2"));
ASSERT_EQ("v2.1,v2.2", Get(1, "foo", nullptr, use_coroutine_));
ASSERT_EQ("v2.1,v2.2", Get(1, "foo"));
ASSERT_OK(Delete(1, "foo"));
ASSERT_EQ("NOT_FOUND", Get(1, "foo", nullptr, use_coroutine_));
ASSERT_EQ("NOT_FOUND", Get(1, "foo"));
ASSERT_OK(TimedPut(1, "bar", "bv1", /*write_unix_time=*/0));
ASSERT_EQ("bv1", Get(1, "bar", nullptr, use_coroutine_));
ASSERT_EQ("bv1", Get(1, "bar"));
ASSERT_OK(TimedPut(1, "baz", "bzv1", /*write_unix_time=*/0));
ASSERT_EQ("bzv1", Get(1, "baz", nullptr, use_coroutine_));
ASSERT_EQ("bzv1", Get(1, "baz"));
if (option_config_ != kRowCache) {
std::string range_del_begin = "b";
std::string range_del_end = "baz";
Slice begin_rdel = range_del_begin, end_rdel = range_del_end;
ASSERT_OK(
db_->DeleteRange(WriteOptions(), handles_[1], begin_rdel, end_rdel));
ASSERT_EQ("NOT_FOUND", Get(1, "bar", nullptr, use_coroutine_));
ASSERT_EQ("NOT_FOUND", Get(1, "bar"));
}
ASSERT_EQ("bzv1", Get(1, "baz", nullptr, use_coroutine_));
ASSERT_EQ("bzv1", Get(1, "baz"));
ASSERT_OK(SingleDelete(1, "baz"));
ASSERT_EQ("NOT_FOUND", Get(1, "baz", nullptr, use_coroutine_));
ASSERT_EQ("NOT_FOUND", Get(1, "baz"));
} while (ChangeOptions(kSkipPlainTable));
}
@@ -1565,17 +1407,17 @@ TEST_F(DBBasicTest, EmptyFlush) {
kSkipMergePut));
}
TEST_P(DBBasicGetWithParam, GetFromVersions) {
TEST_F(DBBasicTest, GetFromVersions) {
do {
CreateAndReopenWithCF({"pikachu"}, CurrentOptions());
ASSERT_OK(Put(1, "foo", "v1"));
ASSERT_OK(Flush(1));
ASSERT_EQ("v1", Get(1, "foo", nullptr, use_coroutine_));
ASSERT_EQ("NOT_FOUND", Get(0, "foo", nullptr, use_coroutine_));
ASSERT_EQ("v1", Get(1, "foo"));
ASSERT_EQ("NOT_FOUND", Get(0, "foo"));
} while (ChangeOptions());
}
TEST_P(DBBasicGetWithParam, GetSnapshot) {
TEST_F(DBBasicTest, GetSnapshot) {
anon::OptionsOverride options_override;
options_override.skip_policy = kSkipNoSnapshot;
do {
@@ -1586,11 +1428,11 @@ TEST_P(DBBasicGetWithParam, GetSnapshot) {
ASSERT_OK(Put(1, key, "v1"));
const Snapshot* s1 = db_->GetSnapshot();
ASSERT_OK(Put(1, key, "v2"));
ASSERT_EQ("v2", Get(1, key, nullptr, use_coroutine_));
ASSERT_EQ("v1", Get(1, key, s1, use_coroutine_));
ASSERT_EQ("v2", Get(1, key));
ASSERT_EQ("v1", Get(1, key, s1));
ASSERT_OK(Flush(1));
ASSERT_EQ("v2", Get(1, key, nullptr, use_coroutine_));
ASSERT_EQ("v1", Get(1, key, s1, use_coroutine_));
ASSERT_EQ("v2", Get(1, key));
ASSERT_EQ("v1", Get(1, key, s1));
db_->ReleaseSnapshot(s1);
}
} while (ChangeOptions());
@@ -1847,7 +1689,7 @@ TEST_F(DBBasicTest, LockFileRecovery) {
}
}
TEST_P(DBBasicGetWithParam, Snapshot) {
TEST_F(DBBasicTest, Snapshot) {
env_->SetMockSleep();
anon::OptionsOverride options_override;
options_override.skip_policy = kSkipNoSnapshot;
@@ -1881,31 +1723,31 @@ TEST_P(DBBasicGetWithParam, Snapshot) {
ASSERT_OK(Put(0, "foo", "0v4"));
ASSERT_OK(Put(1, "foo", "1v4"));
ASSERT_EQ("0v1", Get(0, "foo", s1, use_coroutine_));
ASSERT_EQ("1v1", Get(1, "foo", s1, use_coroutine_));
ASSERT_EQ("0v2", Get(0, "foo", s2, use_coroutine_));
ASSERT_EQ("1v2", Get(1, "foo", s2, use_coroutine_));
ASSERT_EQ("0v3", Get(0, "foo", s3.snapshot(), use_coroutine_));
ASSERT_EQ("1v3", Get(1, "foo", s3.snapshot(), use_coroutine_));
ASSERT_EQ("0v4", Get(0, "foo", nullptr, use_coroutine_));
ASSERT_EQ("1v4", Get(1, "foo", nullptr, use_coroutine_));
ASSERT_EQ("0v1", Get(0, "foo", s1));
ASSERT_EQ("1v1", Get(1, "foo", s1));
ASSERT_EQ("0v2", Get(0, "foo", s2));
ASSERT_EQ("1v2", Get(1, "foo", s2));
ASSERT_EQ("0v3", Get(0, "foo", s3.snapshot()));
ASSERT_EQ("1v3", Get(1, "foo", s3.snapshot()));
ASSERT_EQ("0v4", Get(0, "foo"));
ASSERT_EQ("1v4", Get(1, "foo"));
}
ASSERT_EQ(2U, GetNumSnapshots());
ASSERT_EQ(time_snap1, GetTimeOldestSnapshots());
ASSERT_EQ(GetSequenceOldestSnapshots(), s1->GetSequenceNumber());
ASSERT_EQ("0v1", Get(0, "foo", s1, use_coroutine_));
ASSERT_EQ("1v1", Get(1, "foo", s1, use_coroutine_));
ASSERT_EQ("0v2", Get(0, "foo", s2, use_coroutine_));
ASSERT_EQ("1v2", Get(1, "foo", s2, use_coroutine_));
ASSERT_EQ("0v4", Get(0, "foo", nullptr, use_coroutine_));
ASSERT_EQ("1v4", Get(1, "foo", nullptr, use_coroutine_));
ASSERT_EQ("0v1", Get(0, "foo", s1));
ASSERT_EQ("1v1", Get(1, "foo", s1));
ASSERT_EQ("0v2", Get(0, "foo", s2));
ASSERT_EQ("1v2", Get(1, "foo", s2));
ASSERT_EQ("0v4", Get(0, "foo"));
ASSERT_EQ("1v4", Get(1, "foo"));
db_->ReleaseSnapshot(s1);
ASSERT_EQ("0v2", Get(0, "foo", s2, use_coroutine_));
ASSERT_EQ("1v2", Get(1, "foo", s2, use_coroutine_));
ASSERT_EQ("0v4", Get(0, "foo", nullptr, use_coroutine_));
ASSERT_EQ("1v4", Get(1, "foo", nullptr, use_coroutine_));
ASSERT_EQ("0v2", Get(0, "foo", s2));
ASSERT_EQ("1v2", Get(1, "foo", s2));
ASSERT_EQ("0v4", Get(0, "foo"));
ASSERT_EQ("1v4", Get(1, "foo"));
ASSERT_EQ(1U, GetNumSnapshots());
ASSERT_LT(time_snap1, GetTimeOldestSnapshots());
ASSERT_EQ(GetSequenceOldestSnapshots(), s2->GetSequenceNumber());
@@ -1913,19 +1755,11 @@ TEST_P(DBBasicGetWithParam, Snapshot) {
db_->ReleaseSnapshot(s2);
ASSERT_EQ(0U, GetNumSnapshots());
ASSERT_EQ(GetSequenceOldestSnapshots(), 0);
ASSERT_EQ("0v4", Get(0, "foo", nullptr, use_coroutine_));
ASSERT_EQ("1v4", Get(1, "foo", nullptr, use_coroutine_));
ASSERT_EQ("0v4", Get(0, "foo"));
ASSERT_EQ("1v4", Get(1, "foo"));
} while (ChangeOptions());
}
#if USE_COROUTINES
INSTANTIATE_TEST_CASE_P(DBBasicGetWithParam, DBBasicGetWithParam,
testing::Bool());
#else
INSTANTIATE_TEST_CASE_P(DBBasicGetWithParam, DBBasicGetWithParam,
testing::Values(false));
#endif // USE_COROUTINES
class DBBasicMultiConfigs : public DBBasicTest,
public ::testing::WithParamInterface<int> {
public:
@@ -3874,15 +3708,11 @@ INSTANTIATE_TEST_CASE_P(DBMultiGetTestWithParam, DBMultiGetTestWithParam,
testing::Combine(testing::Bool(), testing::Bool()));
#if USE_COROUTINES
class DBMultiGetAsyncIOTest
: public DBBasicTest,
public ::testing::WithParamInterface<std::tuple<bool, bool>> {
class DBMultiGetAsyncIOTest : public DBBasicTest,
public ::testing::WithParamInterface<bool> {
public:
DBMultiGetAsyncIOTest()
: DBBasicTest(),
optimize_multiget_for_io_(std::get<0>(GetParam())),
use_coroutine_(std::get<1>(GetParam())),
statistics_(ROCKSDB_NAMESPACE::CreateDBStatistics()) {
: DBBasicTest(), statistics_(ROCKSDB_NAMESPACE::CreateDBStatistics()) {
BlockBasedTableOptions bbto;
bbto.filter_policy.reset(NewBloomFilterPolicy(10));
options_ = CurrentOptions();
@@ -3956,20 +3786,6 @@ class DBMultiGetAsyncIOTest
const std::shared_ptr<Statistics>& statistics() { return statistics_; }
protected:
void AssertMultiGetIOBatchSize(uint64_t expected_count,
uint64_t expected_max) {
HistogramData multiget_io_batch_size;
statistics()->histogramData(MULTIGET_IO_BATCH_SIZE,
&multiget_io_batch_size);
ASSERT_EQ(multiget_io_batch_size.count, expected_count);
ASSERT_EQ(multiget_io_batch_size.max, expected_max);
}
bool UseCoroutineRead() const {
return use_coroutine_ &&
options_.env->GetFileSystem()->GetReadExecutor() != nullptr;
}
void PrepareDBForTest() {
#ifdef ROCKSDB_IOURING_PRESENT
Reopen(options_);
@@ -3985,9 +3801,6 @@ class DBMultiGetAsyncIOTest
void ReopenDB() { Reopen(options_); }
const bool optimize_multiget_for_io_;
const bool use_coroutine_;
private:
std::shared_ptr<Statistics> statistics_;
Options options_;
@@ -3996,89 +3809,104 @@ class DBMultiGetAsyncIOTest
TEST_P(DBMultiGetAsyncIOTest, GetFromL0) {
// All 3 keys in L0. The L0 files should be read serially.
std::vector<std::string> key_strs{Key(0), Key(40), Key(80)};
std::vector<Slice> keys{key_strs[0], key_strs[1], key_strs[2]};
std::vector<PinnableSlice> values(key_strs.size());
std::vector<Status> statuses(key_strs.size());
PrepareDBForTest();
std::vector<std::string> values =
MultiGet(key_strs, /*snapshot=*/nullptr, /*async=*/true,
optimize_multiget_for_io_, use_coroutine_);
ReadOptions ro;
ro.async_io = true;
ro.optimize_multiget_for_io = GetParam();
dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
keys.data(), values.data(), statuses.data());
ASSERT_EQ(values.size(), 3);
ASSERT_OK(statuses[0]);
ASSERT_OK(statuses[1]);
ASSERT_OK(statuses[2]);
ASSERT_EQ(values[0], "val_l0_" + std::to_string(0));
ASSERT_EQ(values[1], "val_l0_" + std::to_string(40));
ASSERT_EQ(values[2], "val_l0_" + std::to_string(80));
HistogramData multiget_io_batch_size;
statistics()->histogramData(MULTIGET_IO_BATCH_SIZE, &multiget_io_batch_size);
// With async IO, lookups will happen in parallel for each key
#ifdef ROCKSDB_IOURING_PRESENT
if (UseCoroutineRead()) {
AssertMultiGetIOBatchSize(3, 1);
ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT), 3);
} else if (optimize_multiget_for_io_) {
AssertMultiGetIOBatchSize(1, 3);
if (GetParam()) {
ASSERT_EQ(multiget_io_batch_size.count, 1);
ASSERT_EQ(multiget_io_batch_size.max, 3);
ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT), 3);
} else {
// Without Async IO, MultiGet will call MultiRead 3 times, once for each
// L0 file
AssertMultiGetIOBatchSize(3, 1);
ASSERT_EQ(multiget_io_batch_size.count, 3);
}
#else // ROCKSDB_IOURING_PRESENT
ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT),
UseCoroutineRead() ? 3 : 0);
ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT), 0);
#endif // ROCKSDB_IOURING_PRESENT
}
TEST_P(DBMultiGetAsyncIOTest, GetFromL1) {
std::vector<std::string> key_strs{Key(33), Key(54), Key(102)};
std::vector<std::string> key_strs;
std::vector<Slice> keys;
std::vector<PinnableSlice> values;
std::vector<Status> statuses;
key_strs.push_back(Key(33));
key_strs.push_back(Key(54));
key_strs.push_back(Key(102));
keys.emplace_back(key_strs[0]);
keys.emplace_back(key_strs[1]);
keys.emplace_back(key_strs[2]);
values.resize(keys.size());
statuses.resize(keys.size());
PrepareDBForTest();
std::vector<std::string> values =
MultiGet(key_strs, /*snapshot=*/nullptr, /*async=*/true,
optimize_multiget_for_io_, use_coroutine_);
ReadOptions ro;
ro.async_io = true;
ro.optimize_multiget_for_io = GetParam();
dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
keys.data(), values.data(), statuses.data());
ASSERT_EQ(values.size(), 3);
ASSERT_EQ(statuses[0], Status::OK());
ASSERT_EQ(statuses[1], Status::OK());
ASSERT_EQ(statuses[2], Status::OK());
ASSERT_EQ(values[0], "val_l1_" + std::to_string(33));
ASSERT_EQ(values[1], "val_l1_" + std::to_string(54));
ASSERT_EQ(values[2], "val_l1_" + std::to_string(102));
HistogramData multiget_io_batch_size;
statistics()->histogramData(MULTIGET_IO_BATCH_SIZE, &multiget_io_batch_size);
#ifdef ROCKSDB_IOURING_PRESENT
if (UseCoroutineRead()) {
AssertMultiGetIOBatchSize(3, 1);
} else {
// A batch of 3 async IOs is expected, one for each overlapping file in L1.
AssertMultiGetIOBatchSize(1, 3);
}
ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT),
UseCoroutineRead() ? 6 : 3);
// A batch of 3 async IOs is expected, one for each overlapping file in L1
ASSERT_EQ(multiget_io_batch_size.count, 1);
ASSERT_EQ(multiget_io_batch_size.max, 3);
ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT), 3);
#else // ROCKSDB_IOURING_PRESENT
ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT),
UseCoroutineRead() ? 6 : 0);
ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT), 0);
#endif // ROCKSDB_IOURING_PRESENT
}
TEST_P(DBMultiGetAsyncIOTest, SingleGetFromL1UsesCoroutineRead) {
int coroutine_read_count = 0;
SyncPoint::GetInstance()->SetCallBack(
"RandomAccessFileReader::ReadCoroutine:SubmitReadAsync",
[&](void*) { ++coroutine_read_count; });
SyncPoint::GetInstance()->EnableProcessing();
PrepareDBForTest();
ASSERT_EQ(
"val_l1_" + std::to_string(33),
Get(Key(33), static_cast<const Snapshot*>(nullptr), use_coroutine_));
SyncPoint::GetInstance()->DisableProcessing();
SyncPoint::GetInstance()->ClearAllCallBacks();
if (UseCoroutineRead()) {
ASSERT_GT(coroutine_read_count, 0);
} else {
ASSERT_EQ(coroutine_read_count, 0);
}
}
#ifdef ROCKSDB_IOURING_PRESENT
TEST_P(DBMultiGetAsyncIOTest, GetFromL1Error) {
std::vector<std::string> key_strs{Key(33), Key(54), Key(102)};
std::vector<std::string> key_strs;
std::vector<Slice> keys;
std::vector<PinnableSlice> values;
std::vector<Status> statuses;
key_strs.push_back(Key(33));
key_strs.push_back(Key(54));
key_strs.push_back(Key(102));
keys.emplace_back(key_strs[0]);
keys.emplace_back(key_strs[1]);
keys.emplace_back(key_strs[2]);
values.resize(keys.size());
statuses.resize(keys.size());
int count = 0;
SyncPoint::GetInstance()->SetCallBack(
@@ -4107,137 +3935,210 @@ TEST_P(DBMultiGetAsyncIOTest, GetFromL1Error) {
PrepareDBForTest();
std::vector<std::string> values =
MultiGet(key_strs, /*snapshot=*/nullptr, /*async=*/true,
optimize_multiget_for_io_, use_coroutine_);
ReadOptions ro;
ro.async_io = true;
ro.optimize_multiget_for_io = GetParam();
dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
keys.data(), values.data(), statuses.data());
SyncPoint::GetInstance()->DisableProcessing();
ASSERT_EQ(values.size(), 3);
ASSERT_EQ(values[0], "val_l1_" + std::to_string(33));
ASSERT_EQ(values[1], "val_l1_" + std::to_string(54));
ASSERT_EQ(values[2], Status::IOError().ToString());
ASSERT_EQ(statuses[0], Status::OK());
ASSERT_EQ(statuses[1], Status::OK());
ASSERT_EQ(statuses[2], Status::IOError());
if (UseCoroutineRead()) {
AssertMultiGetIOBatchSize(2, 1);
} else {
// A batch of 3 async IOs is expected, one for each overlapping file in L1.
AssertMultiGetIOBatchSize(1, 2);
}
ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT),
UseCoroutineRead() ? 5 : 2);
HistogramData multiget_io_batch_size;
statistics()->histogramData(MULTIGET_IO_BATCH_SIZE, &multiget_io_batch_size);
// A batch of 3 async IOs is expected, one for each overlapping file in L1
ASSERT_EQ(multiget_io_batch_size.count, 1);
ASSERT_EQ(multiget_io_batch_size.max, 2);
ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT), 2);
}
#endif // ROCKSDB_IOURING_PRESENT
TEST_P(DBMultiGetAsyncIOTest, LastKeyInFile) {
std::vector<std::string> key_strs;
std::vector<Slice> keys;
std::vector<PinnableSlice> values;
std::vector<Status> statuses;
// 21 is the last key in the first L1 file
std::vector<std::string> key_strs{Key(21), Key(54), Key(102)};
key_strs.push_back(Key(21));
key_strs.push_back(Key(54));
key_strs.push_back(Key(102));
keys.emplace_back(key_strs[0]);
keys.emplace_back(key_strs[1]);
keys.emplace_back(key_strs[2]);
values.resize(keys.size());
statuses.resize(keys.size());
PrepareDBForTest();
std::vector<std::string> values =
MultiGet(key_strs, /*snapshot=*/nullptr, /*async=*/true,
optimize_multiget_for_io_, use_coroutine_);
ReadOptions ro;
ro.async_io = true;
ro.optimize_multiget_for_io = GetParam();
dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
keys.data(), values.data(), statuses.data());
ASSERT_EQ(values.size(), 3);
ASSERT_EQ(statuses[0], Status::OK());
ASSERT_EQ(statuses[1], Status::OK());
ASSERT_EQ(statuses[2], Status::OK());
ASSERT_EQ(values[0], "val_l1_" + std::to_string(21));
ASSERT_EQ(values[1], "val_l1_" + std::to_string(54));
ASSERT_EQ(values[2], "val_l1_" + std::to_string(102));
#ifdef ROCKSDB_IOURING_PRESENT
HistogramData multiget_io_batch_size;
statistics()->histogramData(MULTIGET_IO_BATCH_SIZE, &multiget_io_batch_size);
// Since the first MultiGet key is the last key in a file, the MultiGet is
// expected to lookup in that file first, before moving on to other files.
// So the first file lookup will issue one async read, and the next lookup
// will lookup 2 files in parallel and issue 2 async reads
if (UseCoroutineRead()) {
AssertMultiGetIOBatchSize(3, 1);
} else {
AssertMultiGetIOBatchSize(2, 2);
}
ASSERT_EQ(multiget_io_batch_size.count, 2);
ASSERT_EQ(multiget_io_batch_size.max, 2);
#endif // ROCKSDB_IOURING_PRESENT
}
TEST_P(DBMultiGetAsyncIOTest, GetFromL1AndL2) {
std::vector<std::string> key_strs;
std::vector<Slice> keys;
std::vector<PinnableSlice> values;
std::vector<Status> statuses;
// 33 and 102 are in L1, and 56 is in L2
std::vector<std::string> key_strs{Key(33), Key(56), Key(102)};
key_strs.push_back(Key(33));
key_strs.push_back(Key(56));
key_strs.push_back(Key(102));
keys.emplace_back(key_strs[0]);
keys.emplace_back(key_strs[1]);
keys.emplace_back(key_strs[2]);
values.resize(keys.size());
statuses.resize(keys.size());
PrepareDBForTest();
std::vector<std::string> values =
MultiGet(key_strs, /*snapshot=*/nullptr, /*async=*/true,
optimize_multiget_for_io_, use_coroutine_);
ReadOptions ro;
ro.async_io = true;
ro.optimize_multiget_for_io = GetParam();
dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
keys.data(), values.data(), statuses.data());
ASSERT_EQ(values.size(), 3);
ASSERT_EQ(statuses[0], Status::OK());
ASSERT_EQ(statuses[1], Status::OK());
ASSERT_EQ(statuses[2], Status::OK());
ASSERT_EQ(values[0], "val_l1_" + std::to_string(33));
ASSERT_EQ(values[1], "val_l2_" + std::to_string(56));
ASSERT_EQ(values[2], "val_l1_" + std::to_string(102));
#ifdef ROCKSDB_IOURING_PRESENT
HistogramData multiget_io_batch_size;
statistics()->histogramData(MULTIGET_IO_BATCH_SIZE, &multiget_io_batch_size);
// There are 2 keys in L1 in twp separate files, and 1 in L2. With
// optimize_multiget_for_io, all three lookups will happen in parallel.
// Otherwise, the L2 lookup will happen after L1.
if (UseCoroutineRead()) {
AssertMultiGetIOBatchSize(3, 1);
} else {
AssertMultiGetIOBatchSize(optimize_multiget_for_io_ ? 1 : 2,
optimize_multiget_for_io_ ? 3 : 2);
}
ASSERT_EQ(multiget_io_batch_size.count, GetParam() ? 1 : 2);
ASSERT_EQ(multiget_io_batch_size.max, GetParam() ? 3 : 2);
#endif // ROCKSDB_IOURING_PRESENT
}
TEST_P(DBMultiGetAsyncIOTest, GetFromL2WithRangeOverlapL0L1) {
std::vector<std::string> key_strs;
std::vector<Slice> keys;
std::vector<PinnableSlice> values;
std::vector<Status> statuses;
// 19 and 26 are in L2, but overlap with L0 and L1 file ranges
std::vector<std::string> key_strs{Key(19), Key(26)};
key_strs.push_back(Key(19));
key_strs.push_back(Key(26));
keys.emplace_back(key_strs[0]);
keys.emplace_back(key_strs[1]);
values.resize(keys.size());
statuses.resize(keys.size());
PrepareDBForTest();
std::vector<std::string> values =
MultiGet(key_strs, /*snapshot=*/nullptr, /*async=*/true,
optimize_multiget_for_io_, use_coroutine_);
ReadOptions ro;
ro.async_io = true;
ro.optimize_multiget_for_io = GetParam();
dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
keys.data(), values.data(), statuses.data());
ASSERT_EQ(values.size(), 2);
ASSERT_EQ(statuses[0], Status::OK());
ASSERT_EQ(statuses[1], Status::OK());
ASSERT_EQ(values[0], "val_l2_" + std::to_string(19));
ASSERT_EQ(values[1], "val_l2_" + std::to_string(26));
#ifdef ROCKSDB_IOURING_PRESENT
// Bloom filters in L0/L1 avoid the coroutine calls in those levels. The
// coroutine path counts every per-file MultiGetFromSST coroutine (including
// serial reads), whereas the async_io path counts only the parallel overlap
// batch, so the coroutine path observes one more.
ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT),
UseCoroutineRead() ? 3 : 2);
// Bloom filters in L0/L1 will avoid the coroutine calls in those levels
ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT), 2);
#else // ROCKSDB_IOURING_PRESENT
ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT),
UseCoroutineRead() ? 3 : 0);
ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT), 0);
#endif // ROCKSDB_IOURING_PRESENT
}
#ifdef ROCKSDB_IOURING_PRESENT
TEST_P(DBMultiGetAsyncIOTest, GetFromL2WithRangeDelInL1) {
std::vector<std::string> key_strs;
std::vector<Slice> keys;
std::vector<PinnableSlice> values;
std::vector<Status> statuses;
// 139 and 163 are in L2, but overlap with a range deletes in L1
std::vector<std::string> key_strs{Key(139), Key(163)};
key_strs.push_back(Key(139));
key_strs.push_back(Key(163));
keys.emplace_back(key_strs[0]);
keys.emplace_back(key_strs[1]);
values.resize(keys.size());
statuses.resize(keys.size());
PrepareDBForTest();
std::vector<std::string> values =
MultiGet(key_strs, /*snapshot=*/nullptr, /*async=*/true,
optimize_multiget_for_io_, use_coroutine_);
ReadOptions ro;
ro.async_io = true;
ro.optimize_multiget_for_io = GetParam();
dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
keys.data(), values.data(), statuses.data());
ASSERT_EQ(values.size(), 2);
ASSERT_EQ(values[0], "NOT_FOUND");
ASSERT_EQ(values[1], "NOT_FOUND");
ASSERT_EQ(statuses[0], Status::NotFound());
ASSERT_EQ(statuses[1], Status::NotFound());
// Bloom filters in L0/L1 will avoid the coroutine calls in those levels
ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT), 2);
}
TEST_P(DBMultiGetAsyncIOTest, GetFromL1AndL2WithRangeDelInL1) {
std::vector<std::string> key_strs;
std::vector<Slice> keys;
std::vector<PinnableSlice> values;
std::vector<Status> statuses;
// 139 and 163 are in L2, but overlap with a range deletes in L1
std::vector<std::string> key_strs{Key(139), Key(144), Key(163)};
key_strs.push_back(Key(139));
key_strs.push_back(Key(144));
key_strs.push_back(Key(163));
keys.emplace_back(key_strs[0]);
keys.emplace_back(key_strs[1]);
keys.emplace_back(key_strs[2]);
values.resize(keys.size());
statuses.resize(keys.size());
PrepareDBForTest();
std::vector<std::string> values =
MultiGet(key_strs, /*snapshot=*/nullptr, /*async=*/true,
optimize_multiget_for_io_, use_coroutine_);
ASSERT_EQ(values.size(), 3);
ASSERT_EQ(values[0], "NOT_FOUND");
ReadOptions ro;
ro.async_io = true;
ro.optimize_multiget_for_io = GetParam();
dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
keys.data(), values.data(), statuses.data());
ASSERT_EQ(values.size(), keys.size());
ASSERT_EQ(statuses[0], Status::NotFound());
ASSERT_EQ(statuses[1], Status::OK());
ASSERT_EQ(values[1], "val_l1_" + std::to_string(144));
ASSERT_EQ(values[2], "NOT_FOUND");
ASSERT_EQ(statuses[2], Status::NotFound());
// Bloom filters in L0/L1 will avoid the coroutine calls in those levels
ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT), 3);
@@ -4245,18 +4146,32 @@ TEST_P(DBMultiGetAsyncIOTest, GetFromL1AndL2WithRangeDelInL1) {
#endif // ROCKSDB_IOURING_PRESENT
TEST_P(DBMultiGetAsyncIOTest, GetNoIOUring) {
std::vector<std::string> key_strs{Key(33), Key(54), Key(102)};
std::vector<std::string> key_strs;
std::vector<Slice> keys;
std::vector<PinnableSlice> values;
std::vector<Status> statuses;
key_strs.push_back(Key(33));
key_strs.push_back(Key(54));
key_strs.push_back(Key(102));
keys.emplace_back(key_strs[0]);
keys.emplace_back(key_strs[1]);
keys.emplace_back(key_strs[2]);
values.resize(keys.size());
statuses.resize(keys.size());
enable_io_uring = false;
ReopenDB();
std::vector<std::string> values =
MultiGet(key_strs, /*snapshot=*/nullptr, /*async=*/true,
optimize_multiget_for_io_, use_coroutine_);
ReadOptions ro;
ro.async_io = true;
ro.optimize_multiget_for_io = GetParam();
dbfull()->MultiGet(ro, dbfull()->DefaultColumnFamily(), keys.size(),
keys.data(), values.data(), statuses.data());
ASSERT_EQ(values.size(), 3);
ASSERT_EQ(values[0], "val_l1_" + std::to_string(33));
ASSERT_EQ(values[1], "val_l1_" + std::to_string(54));
ASSERT_EQ(values[2], "val_l1_" + std::to_string(102));
ASSERT_EQ(statuses[0], Status::OK());
ASSERT_EQ(statuses[1], Status::OK());
ASSERT_EQ(statuses[2], Status::OK());
HistogramData async_read_bytes;
@@ -4264,17 +4179,11 @@ TEST_P(DBMultiGetAsyncIOTest, GetNoIOUring) {
// A batch of 3 async IOs is expected, one for each overlapping file in L1
ASSERT_EQ(async_read_bytes.count, 0);
const uint64_t coroutine_count =
statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT);
if (UseCoroutineRead()) {
ASSERT_GT(coroutine_count, 0);
} else {
ASSERT_EQ(coroutine_count, 0);
}
ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT), 0);
}
INSTANTIATE_TEST_CASE_P(DBMultiGetAsyncIOTest, DBMultiGetAsyncIOTest,
testing::Combine(testing::Bool(), testing::Bool()));
testing::Bool());
#endif // USE_COROUTINES
TEST_F(DBBasicTest, MultiGetStats) {
+9 -30
View File
@@ -1800,7 +1800,6 @@ static std::map<TableFileCreationReason, std::string>
{TableFileCreationReason::kFlush, "kFlush"},
{TableFileCreationReason::kMisc, "kMisc"},
{TableFileCreationReason::kRecovery, "kRecovery"},
{TableFileCreationReason::kSstFileWriter, "kSstFileWriter"},
};
class TestingContextCustomFilterPolicy
@@ -1815,15 +1814,6 @@ class TestingContextCustomFilterPolicy
const FilterBuildingContext& context) const override {
test_report_ += "cf=";
test_report_ += context.column_family_name;
// Token rather than path, so expectations don't depend on test directory
test_report_ += ",db=";
if (context.db_name.empty()) {
test_report_ += "none";
} else if (context.db_name == Slice(expected_db_name_)) {
test_report_ += "expected";
} else {
test_report_ += "UNEXPECTED:" + context.db_name.ToString();
}
test_report_ += ",s=";
test_report_ +=
OptionsHelper::compaction_style_to_string[context.compaction_style];
@@ -1846,13 +1836,8 @@ class TestingContextCustomFilterPolicy
return rv;
}
void SetExpectedDbName(std::string db_name) {
expected_db_name_ = std::move(db_name);
}
private:
mutable std::string test_report_;
std::string expected_db_name_;
};
} // anonymous namespace
@@ -1874,13 +1859,6 @@ TEST_F(DBBloomFilterTest, ContextCustomFilterPolicy) {
ASSERT_OK(TryReopen(options));
CreateAndReopenWithCF({fifo ? "abe" : "bob"}, options);
policy->SetExpectedDbName(dbname_);
const char* expected_flush_report =
fifo
? "cf=abe,db=expected,s=kCompactionStyleFIFO,n=7,l=0,b=0,r=kFlush\n"
: "cf=bob,db=expected,s=kCompactionStyleLevel,n=7,l=0,b=0,r="
"kFlush\n";
const int maxKey = 10000;
for (int i = 0; i < maxKey / 2; i++) {
@@ -1889,13 +1867,17 @@ TEST_F(DBBloomFilterTest, ContextCustomFilterPolicy) {
// Add a large key to make the file contain wide range
ASSERT_OK(Put(1, Key(maxKey + 55555), Key(maxKey + 55555)));
ASSERT_OK(Flush(1));
EXPECT_EQ(policy->DumpTestReport(), expected_flush_report);
EXPECT_EQ(policy->DumpTestReport(),
fifo ? "cf=abe,s=kCompactionStyleFIFO,n=7,l=0,b=0,r=kFlush\n"
: "cf=bob,s=kCompactionStyleLevel,n=7,l=0,b=0,r=kFlush\n");
for (int i = maxKey / 2; i < maxKey; i++) {
ASSERT_OK(Put(1, Key(i), Key(i)));
}
ASSERT_OK(Flush(1));
EXPECT_EQ(policy->DumpTestReport(), expected_flush_report);
EXPECT_EQ(policy->DumpTestReport(),
fifo ? "cf=abe,s=kCompactionStyleFIFO,n=7,l=0,b=0,r=kFlush\n"
: "cf=bob,s=kCompactionStyleLevel,n=7,l=0,b=0,r=kFlush\n");
// Check that they can be found
for (int i = 0; i < maxKey; i++) {
@@ -1922,8 +1904,7 @@ TEST_F(DBBloomFilterTest, ContextCustomFilterPolicy) {
ASSERT_OK(db_->CompactRange(CompactRangeOptions(), handles_[1], nullptr,
nullptr));
EXPECT_EQ(policy->DumpTestReport(),
"cf=bob,db=expected,s=kCompactionStyleLevel,n=7,l=1,b=1,r="
"kCompaction\n");
"cf=bob,s=kCompactionStyleLevel,n=7,l=1,b=1,r=kCompaction\n");
// Check that we now have one filter, about 9.2% FP rate (5 bits per key)
for (int i = 0; i < maxKey; i++) {
@@ -1945,8 +1926,7 @@ TEST_F(DBBloomFilterTest, ContextCustomFilterPolicy) {
}
// Note: kCompactionStyleLevel is default, ignored if num_levels == -1
EXPECT_EQ(policy->DumpTestReport(),
"cf=abe,db=none,s=kCompactionStyleLevel,n=-1,l=-1,b=0,r="
"kSstFileWriter\n");
"cf=abe,s=kCompactionStyleLevel,n=-1,l=-1,b=0,r=kMisc\n");
}
// Destroy
@@ -3998,8 +3978,7 @@ static std::vector<std::string> RangeQueryKeys(
ReadOptions ro;
ro.iterate_lower_bound = &lb;
ro.iterate_upper_bound = &ub;
auto filter = factory.GetTableFilterForRangeQuery(lb, ub);
ro.table_filter = &filter;
ro.table_filter = factory.GetTableFilterForRangeQuery(lb, ub);
auto it = db.NewIterator(ro);
std::vector<std::string> ret;
for (it->Seek(lb); it->Valid(); it->Next()) {
-494
View File
@@ -4,9 +4,6 @@
// (found in the LICENSE.Apache file in the root directory).
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <set>
#include <thread>
#include <unordered_map>
@@ -17,7 +14,6 @@
#include "options/options_helper.h"
#include "port/stack_trace.h"
#include "rocksdb/db.h"
#include "rocksdb/listener.h"
#include "rocksdb/sst_file_writer.h"
#include "test_util/sync_point.h"
#include "test_util/testharness.h"
@@ -95,19 +91,6 @@ class AbortSynchronizer {
}
}
void TriggerAbort(DBImpl* db, ColumnFamilyHandle* column_family) {
if (abort_triggered_.load() && abort_completed_.load()) {
Reset();
}
if (!abort_triggered_.exchange(true)) {
abort_thread_ = std::thread([this, db, column_family]() {
db->AbortCompactions(column_family);
SignalAbortCompleted();
});
}
}
// Wait for the abort thread to complete.
// Call this AFTER compaction returns to ensure the abort thread has finished
// before proceeding with Resume or other operations.
@@ -476,483 +459,6 @@ TEST_F(DBCompactionAbortTest, AbortScheduledAutomaticCompactionBeforePick) {
VerifyDataIntegrity(/*num_keys=*/100);
}
TEST_F(DBCompactionAbortTest, AbortCompactionsIsScopedToColumnFamily) {
Options options = CurrentOptions();
options.level0_file_num_compaction_trigger = 100;
options.max_background_compactions = 2;
options.max_subcompactions = 1;
options.disable_auto_compactions = true;
CreateAndReopenWithCF({"target", "sibling"}, options);
Random rnd(301);
for (int cf = 1; cf <= 2; ++cf) {
for (int file = 0; file < 4; ++file) {
for (int key = 0; key < 100; ++key) {
ASSERT_OK(Put(cf, Key(key), rnd.RandomString(1000)));
}
ASSERT_OK(Flush(cf));
}
}
AbortSynchronizer abort_sync;
std::atomic<int> compactions_started{0};
std::mutex sibling_mutex;
std::condition_variable sibling_cv;
bool sibling_started = false;
bool allow_sibling_to_finish = false;
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency({
{"DBImpl::AbortCompactions:FlagSet",
"DBCompactionAbortTest::ScopedAbort:WaitForAbort"},
});
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
"CompactionJob::ProcessKeyValueCompaction:Start", [&](void* /*arg*/) {
if (compactions_started.fetch_add(1) == 0) {
std::unique_lock<std::mutex> lock(sibling_mutex);
sibling_started = true;
sibling_cv.notify_all();
sibling_cv.wait(lock, [&]() { return allow_sibling_to_finish; });
return;
}
abort_sync.TriggerAbort(dbfull(), handles_[1]);
TEST_SYNC_POINT_CALLBACK(
"DBCompactionAbortTest::ScopedAbort:WaitForAbort", nullptr);
});
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
Status sibling_status;
std::thread sibling_thread([&]() {
sibling_status = dbfull()->CompactRange(CompactRangeOptions(), handles_[2],
nullptr, nullptr);
});
{
std::unique_lock<std::mutex> lock(sibling_mutex);
sibling_cv.wait(lock, [&]() { return sibling_started; });
}
Status target_status = dbfull()->CompactRange(CompactRangeOptions(),
handles_[1], nullptr, nullptr);
abort_sync.WaitForAbortCompletion();
{
std::lock_guard<std::mutex> guard(sibling_mutex);
allow_sibling_to_finish = true;
}
sibling_cv.notify_all();
sibling_thread.join();
CleanupSyncPoints();
ASSERT_TRUE(target_status.IsIncomplete());
ASSERT_TRUE(target_status.IsCompactionAborted());
ASSERT_OK(sibling_status);
target_status = dbfull()->CompactRange(CompactRangeOptions(), handles_[1],
nullptr, nullptr);
ASSERT_TRUE(target_status.IsIncomplete());
ASSERT_TRUE(target_status.IsCompactionAborted());
dbfull()->ResumeCompactions(handles_[1]);
ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), handles_[1], nullptr,
nullptr));
}
TEST_F(DBCompactionAbortTest, PerColumnFamilyAndGlobalAbortCountersCompose) {
Options options = CurrentOptions();
options.level0_file_num_compaction_trigger = 100;
options.disable_auto_compactions = true;
CreateAndReopenWithCF({"target", "sibling"}, options);
for (int cf = 1; cf <= 2; ++cf) {
for (int file = 0; file < 2; ++file) {
ASSERT_OK(Put(cf, Key(file), "value"));
ASSERT_OK(Flush(cf));
}
}
dbfull()->AbortAllCompactions();
dbfull()->AbortCompactions(handles_[1]);
dbfull()->AbortCompactions(handles_[1]);
dbfull()->ResumeCompactions(handles_[1]);
Status sibling_status = dbfull()->CompactRange(CompactRangeOptions(),
handles_[2], nullptr, nullptr);
ASSERT_TRUE(sibling_status.IsIncomplete());
ASSERT_TRUE(sibling_status.IsCompactionAborted());
dbfull()->ResumeAllCompactions();
ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), handles_[2], nullptr,
nullptr));
Status target_status = dbfull()->CompactRange(CompactRangeOptions(),
handles_[1], nullptr, nullptr);
ASSERT_TRUE(target_status.IsIncomplete());
ASSERT_TRUE(target_status.IsCompactionAborted());
dbfull()->ResumeCompactions(handles_[1]);
ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), handles_[1], nullptr,
nullptr));
}
TEST_F(DBCompactionAbortTest, AbortCompactionsRejectsCompactFilesTrivialMove) {
Options options = CurrentOptions();
options.disable_auto_compactions = true;
CreateAndReopenWithCF({"target"}, options);
ASSERT_OK(Put(1, "key", "value"));
ASSERT_OK(Flush(1));
ColumnFamilyMetaData metadata;
dbfull()->GetColumnFamilyMetaData(handles_[1], &metadata);
ASSERT_EQ(metadata.levels[0].files.size(), 1);
const std::vector<std::string> input_files = {
metadata.levels[0].files.front().name};
CompactionOptions compaction_options;
compaction_options.allow_trivial_move = true;
dbfull()->AbortCompactions(handles_[1]);
Status status =
dbfull()->CompactFiles(compaction_options, handles_[1], input_files, 1);
ASSERT_TRUE(status.IsIncomplete());
ASSERT_TRUE(status.IsCompactionAborted());
dbfull()->ResumeCompactions(handles_[1]);
ASSERT_OK(
dbfull()->CompactFiles(compaction_options, handles_[1], input_files, 1));
}
TEST_F(DBCompactionAbortTest, ResumeRestoresParkedAutomaticCompaction) {
constexpr int kCompactionTrigger = 4;
Options options = CurrentOptions();
options.level0_file_num_compaction_trigger = kCompactionTrigger;
options.max_background_compactions = 1;
options.disable_auto_compactions = false;
CreateAndReopenWithCF({"target", "sibling"}, options);
AbortSynchronizer abort_sync;
std::mutex parked_mutex;
std::condition_variable parked_cv;
bool compaction_parked = false;
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency({
{"DBImpl::AbortCompactions:FlagSet",
"DBCompactionAbortTest::ParkedCompaction:WaitForAbort"},
});
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
"BackgroundCallCompaction:0", [&](void* /*arg*/) {
abort_sync.TriggerAbort(dbfull(), handles_[1]);
TEST_SYNC_POINT_CALLBACK(
"DBCompactionAbortTest::ParkedCompaction:WaitForAbort", nullptr);
});
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
"DBImpl::PickCompactionFromQueue:Parked", [&](void* /*arg*/) {
std::lock_guard<std::mutex> guard(parked_mutex);
compaction_parked = true;
parked_cv.notify_all();
});
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
Random rnd(301);
for (int file = 0; file < kCompactionTrigger; ++file) {
for (int key = 0; key < 100; ++key) {
ASSERT_OK(Put(1, Key(key), rnd.RandomString(1000)));
}
ASSERT_OK(Flush(1));
}
{
std::unique_lock<std::mutex> lock(parked_mutex);
parked_cv.wait(lock, [&]() { return compaction_parked; });
}
CleanupSyncPoints();
abort_sync.WaitForAbortCompletion();
const int l0_files_before_resume = NumTableFilesAtLevel(0, 1);
ASSERT_GE(l0_files_before_resume, kCompactionTrigger);
WaitForCompactOptions wait_options;
wait_options.timeout = std::chrono::milliseconds(1);
ASSERT_TRUE(dbfull()->WaitForCompact(wait_options).IsTimedOut());
for (int file = 0; file < kCompactionTrigger; ++file) {
for (int key = 0; key < 100; ++key) {
ASSERT_OK(Put(2, Key(key), rnd.RandomString(1000)));
}
ASSERT_OK(Flush(2));
}
ASSERT_OK(dbfull()->TEST_WaitForBackgroundWork());
ASSERT_LT(NumTableFilesAtLevel(0, 2), kCompactionTrigger);
ASSERT_EQ(NumTableFilesAtLevel(0, 1), l0_files_before_resume);
std::atomic<bool> target_reenqueued{false};
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
"DBImpl::RestoreParkedCompaction:cfd", [&](void* arg) {
auto* cfd = static_cast<ColumnFamilyData*>(arg);
if (cfd->GetName() == "target") {
target_reenqueued.store(true);
}
});
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
dbfull()->ResumeCompactions(handles_[1]);
ASSERT_TRUE(target_reenqueued.load());
CleanupSyncPoints();
ASSERT_OK(dbfull()->TEST_WaitForCompact());
ASSERT_LT(NumTableFilesAtLevel(0, 1), l0_files_before_resume);
}
TEST_F(DBCompactionAbortTest, DropColumnFamilyReleasesParkedCompaction) {
constexpr int kCompactionTrigger = 4;
Options options = CurrentOptions();
options.level0_file_num_compaction_trigger = kCompactionTrigger;
options.max_background_compactions = 1;
options.disable_auto_compactions = false;
CreateAndReopenWithCF({"target"}, options);
AbortSynchronizer abort_sync;
std::mutex parked_mutex;
std::condition_variable parked_cv;
bool compaction_parked = false;
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency({
{"DBImpl::AbortCompactions:FlagSet",
"DBCompactionAbortTest::DropParkedCompaction:WaitForAbort"},
});
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
"BackgroundCallCompaction:0", [&](void* /*arg*/) {
abort_sync.TriggerAbort(dbfull(), handles_[1]);
TEST_SYNC_POINT_CALLBACK(
"DBCompactionAbortTest::DropParkedCompaction:WaitForAbort",
nullptr);
});
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
"DBImpl::PickCompactionFromQueue:Parked", [&](void* /*arg*/) {
std::lock_guard<std::mutex> guard(parked_mutex);
compaction_parked = true;
parked_cv.notify_all();
});
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
Random rnd(301);
for (int file = 0; file < kCompactionTrigger; ++file) {
for (int key = 0; key < 100; ++key) {
ASSERT_OK(Put(1, Key(key), rnd.RandomString(1000)));
}
ASSERT_OK(Flush(1));
}
{
std::unique_lock<std::mutex> lock(parked_mutex);
parked_cv.wait(lock, [&]() { return compaction_parked; });
}
CleanupSyncPoints();
abort_sync.WaitForAbortCompletion();
ASSERT_OK(dbfull()->DropColumnFamily(handles_[1]));
WaitForCompactOptions wait_options;
wait_options.timeout = std::chrono::seconds(10);
ASSERT_OK(dbfull()->WaitForCompact(wait_options));
dbfull()->ResumeCompactions(handles_[1]);
}
TEST_F(DBCompactionAbortTest, DropColumnFamilyBeforeAbortedQueueEntryIsParked) {
constexpr int kCompactionTrigger = 4;
Options options = CurrentOptions();
options.level0_file_num_compaction_trigger = kCompactionTrigger;
options.max_background_compactions = 1;
options.disable_auto_compactions = false;
CreateAndReopenWithCF({"target"}, options);
std::mutex worker_mutex;
std::condition_variable worker_cv;
bool worker_started = false;
bool allow_worker_to_pick = false;
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
"BackgroundCallCompaction:0", [&](void* /*arg*/) {
std::unique_lock<std::mutex> lock(worker_mutex);
worker_started = true;
worker_cv.notify_all();
worker_cv.wait(lock, [&]() { return allow_worker_to_pick; });
});
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
for (int file = 0; file < kCompactionTrigger; ++file) {
ASSERT_OK(Put(1, Key(file), "value"));
ASSERT_OK(Flush(1));
}
{
std::unique_lock<std::mutex> lock(worker_mutex);
worker_cv.wait(lock, [&]() { return worker_started; });
}
dbfull()->AbortCompactions(handles_[1]);
const Status drop_status = dbfull()->DropColumnFamily(handles_[1]);
{
std::lock_guard<std::mutex> guard(worker_mutex);
allow_worker_to_pick = true;
}
worker_cv.notify_all();
WaitForCompactOptions wait_options;
wait_options.timeout = std::chrono::seconds(10);
const Status wait_status = dbfull()->WaitForCompact(wait_options);
CleanupSyncPoints();
dbfull()->ResumeCompactions(handles_[1]);
ASSERT_OK(drop_status);
ASSERT_OK(wait_status);
}
TEST_F(DBCompactionAbortTest, NewCompactionWorkWhileAbortedIsParked) {
constexpr int kCompactionTrigger = 4;
Options options = CurrentOptions();
options.level0_file_num_compaction_trigger = kCompactionTrigger;
options.max_background_compactions = 1;
options.disable_auto_compactions = false;
CreateAndReopenWithCF({"target"}, options);
dbfull()->AbortCompactions(handles_[1]);
for (int file = 0; file < kCompactionTrigger; ++file) {
ASSERT_OK(Put(1, Key(file), "value"));
ASSERT_OK(Flush(1));
}
const int l0_files_before_resume = NumTableFilesAtLevel(0, 1);
WaitForCompactOptions wait_options;
wait_options.timeout = std::chrono::milliseconds(1);
const Status wait_status = dbfull()->WaitForCompact(wait_options);
dbfull()->ResumeCompactions(handles_[1]);
ASSERT_TRUE(wait_status.IsTimedOut());
ASSERT_GE(l0_files_before_resume, kCompactionTrigger);
ASSERT_OK(dbfull()->TEST_WaitForCompact());
ASSERT_LT(NumTableFilesAtLevel(0, 1), l0_files_before_resume);
}
TEST_F(DBCompactionAbortTest, AbortWaitsForCompactionCompletionCallback) {
constexpr int kCompactionTrigger = 4;
Options options = CurrentOptions();
options.level0_file_num_compaction_trigger = kCompactionTrigger;
options.max_background_compactions = 1;
options.disable_auto_compactions = false;
options.listeners.emplace_back(std::make_shared<EventListener>());
CreateAndReopenWithCF({"target"}, options);
std::mutex callback_mutex;
std::condition_variable callback_cv;
bool callback_started = false;
bool allow_callback_to_finish = false;
enum class AbortState { kNotObserved, kWaiting, kComplete };
AbortState abort_state = AbortState::kNotObserved;
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
"DBImpl::NotifyOnCompactionCompleted::UnlockMutex", [&](void* /*arg*/) {
std::unique_lock<std::mutex> lock(callback_mutex);
callback_started = true;
callback_cv.notify_all();
callback_cv.wait(lock, [&]() { return allow_callback_to_finish; });
});
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
"DBImpl::AbortCompactions:Waiting", [&](void* /*arg*/) {
std::lock_guard<std::mutex> guard(callback_mutex);
abort_state = AbortState::kWaiting;
callback_cv.notify_all();
});
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
"DBImpl::AbortCompactions:Complete", [&](void* /*arg*/) {
std::lock_guard<std::mutex> guard(callback_mutex);
abort_state = AbortState::kComplete;
callback_cv.notify_all();
});
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
for (int file = 0; file < kCompactionTrigger; ++file) {
ASSERT_OK(Put(1, Key(file), "value"));
ASSERT_OK(Flush(1));
}
{
std::unique_lock<std::mutex> lock(callback_mutex);
callback_cv.wait(lock, [&]() { return callback_started; });
}
std::thread abort_thread([&]() { dbfull()->AbortCompactions(handles_[1]); });
bool returned_while_callback_blocked = false;
{
std::unique_lock<std::mutex> lock(callback_mutex);
callback_cv.wait(lock,
[&]() { return abort_state != AbortState::kNotObserved; });
returned_while_callback_blocked = abort_state == AbortState::kComplete;
}
{
std::lock_guard<std::mutex> guard(callback_mutex);
allow_callback_to_finish = true;
}
callback_cv.notify_all();
abort_thread.join();
CleanupSyncPoints();
dbfull()->ResumeCompactions(handles_[1]);
ASSERT_FALSE(returned_while_callback_blocked);
}
TEST_F(DBCompactionAbortTest,
DroppedColumnFamilyFilesPurgedAfterTrackedCompaction) {
constexpr int kCompactionTrigger = 4;
Options options = CurrentOptions();
options.level0_file_num_compaction_trigger = kCompactionTrigger;
options.max_background_compactions = 1;
options.disable_auto_compactions = false;
CreateAndReopenWithCF({"target"}, options);
std::mutex compaction_mutex;
std::condition_variable compaction_cv;
bool compaction_started = false;
bool allow_compaction_to_finish = false;
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
"CompactionJob::Run():Start", [&](void* /*arg*/) {
std::unique_lock<std::mutex> lock(compaction_mutex);
compaction_started = true;
compaction_cv.notify_all();
compaction_cv.wait(lock, [&]() { return allow_compaction_to_finish; });
});
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
Random rnd(301);
for (int file = 0; file < kCompactionTrigger; ++file) {
for (int key = 0; key < 100; ++key) {
ASSERT_OK(Put(1, Key(key), rnd.RandomString(1000)));
}
ASSERT_OK(Flush(1));
}
{
std::unique_lock<std::mutex> lock(compaction_mutex);
compaction_cv.wait(lock, [&]() { return compaction_started; });
}
const int sst_files_before_drop = GetSstFileCount(dbname_);
const Status drop_status = dbfull()->DropColumnFamily(handles_[1]);
Status destroy_handle_status;
if (drop_status.ok()) {
destroy_handle_status = dbfull()->DestroyColumnFamilyHandle(handles_[1]);
if (destroy_handle_status.ok()) {
handles_.erase(handles_.begin() + 1);
}
}
{
std::lock_guard<std::mutex> guard(compaction_mutex);
allow_compaction_to_finish = true;
}
compaction_cv.notify_all();
const Status wait_status = dbfull()->TEST_WaitForCompact();
CleanupSyncPoints();
ASSERT_OK(drop_status);
ASSERT_OK(destroy_handle_status);
ASSERT_OK(wait_status);
ASSERT_GT(sst_files_before_drop, 0);
ASSERT_EQ(0, GetSstFileCount(dbname_));
}
TEST_F(DBCompactionAbortTest, ResumeCompactionsAfterCloseIsNoOp) {
auto* const default_column_family = dbfull()->DefaultColumnFamily();
dbfull()->AbortCompactions(default_column_family);
ASSERT_OK(dbfull()->Close());
dbfull()->ResumeCompactions(default_column_family);
}
TEST_F(DBCompactionAbortTest, AbortAndVerifyNoOutputFiles) {
Options options = CurrentOptions();
options.level0_file_num_compaction_trigger = 4;
+2 -41
View File
@@ -813,23 +813,6 @@ TEST_F(DBCompactionTest, CompactRangeBottomPri) {
int low_pri_count = 0;
int bottom_pri_count = 0;
bool bottom_running_seen = false;
std::atomic<bool> bottom_property_seen = false;
SyncPoint::GetInstance()->SetCallBack(
"CompactionJob::Run():Start", [&](void*) {
uint64_t total = 0;
uint64_t bottom = 0;
ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kNumRunningCompactions,
&total));
ASSERT_TRUE(db_->GetIntProperty(
DB::Properties::kNumRunningBottomCompactions, &bottom));
ASSERT_GE(total, bottom);
ASSERT_GE(total, 1);
ASSERT_LE(total, 2);
ASSERT_LE(bottom, 1);
if (bottom > 0) {
bottom_property_seen = true;
}
});
SyncPoint::GetInstance()->SetCallBack(
"BackgroundCallCompaction:1", [&](void*) {
if (dbfull()->TEST_NumRunningBottomCompactions() > 0) {
@@ -855,7 +838,6 @@ TEST_F(DBCompactionTest, CompactRangeBottomPri) {
ASSERT_EQ(1, low_pri_count);
ASSERT_EQ(1, bottom_pri_count);
ASSERT_TRUE(bottom_running_seen);
ASSERT_TRUE(bottom_property_seen);
ASSERT_EQ("0,0,2", FilesPerLevel(0));
// Recompact bottom most level uses bottom pool
@@ -6174,7 +6156,6 @@ TEST_F(DBCompactionTest, CompactRangeFlushOverlappingMemtable) {
TEST_F(DBCompactionTest, CompactionStatsTest) {
Options options = CurrentOptions();
options.level0_file_num_compaction_trigger = 2;
options.max_background_compactions = 1;
CompactionStatsCollector* collector = new CompactionStatsCollector();
options.listeners.emplace_back(collector);
DestroyAndReopen(options);
@@ -6182,13 +6163,9 @@ TEST_F(DBCompactionTest, CompactionStatsTest) {
// Verify that the internal statistics for num_running_compactions and
// num_running_compaction_sorted_runs start and end at valid states
uint64_t num_running_compactions = 0;
uint64_t num_running_bottom_compactions = 0;
ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kNumRunningCompactions,
&num_running_compactions));
ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kNumRunningBottomCompactions,
&num_running_bottom_compactions));
ASSERT_EQ(0, num_running_compactions);
ASSERT_EQ(0, num_running_bottom_compactions);
ASSERT_EQ(num_running_compactions, 0);
uint64_t num_running_compaction_sorted_runs = 0;
ASSERT_TRUE(
db_->GetIntProperty(DB::Properties::kNumRunningCompactionSortedRuns,
@@ -6197,18 +6174,6 @@ TEST_F(DBCompactionTest, CompactionStatsTest) {
// Check that the stat actually gets changed some time between the start and
// end of compaction
std::atomic<bool> sorted_runs_count_incremented = false;
std::atomic<bool> running_compaction_seen = false;
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
"CompactionJob::Run():Start", [&](void*) {
ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kNumRunningCompactions,
&num_running_compactions));
ASSERT_TRUE(
db_->GetIntProperty(DB::Properties::kNumRunningBottomCompactions,
&num_running_bottom_compactions));
ASSERT_EQ(1, num_running_compactions);
ASSERT_EQ(0, num_running_bottom_compactions);
running_compaction_seen = true;
});
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
"CompactionMergingIterator::UpdateInternalStats",
[&](void*) { sorted_runs_count_incremented = true; });
@@ -6232,15 +6197,11 @@ TEST_F(DBCompactionTest, CompactionStatsTest) {
// to process
ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kNumRunningCompactions,
&num_running_compactions));
ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kNumRunningBottomCompactions,
&num_running_bottom_compactions));
ASSERT_EQ(0, num_running_compactions);
ASSERT_EQ(0, num_running_bottom_compactions);
ASSERT_EQ(num_running_compactions, 0);
ASSERT_TRUE(
db_->GetIntProperty(DB::Properties::kNumRunningCompactionSortedRuns,
&num_running_compaction_sorted_runs));
ASSERT_EQ(num_running_compaction_sorted_runs, 0);
ASSERT_TRUE(running_compaction_seen);
ASSERT_TRUE(sorted_runs_count_incremented);
SyncPoint::GetInstance()->DisableProcessing();
+1 -124
View File
@@ -28,7 +28,6 @@
#include "rocksdb/wal_filter.h"
#include "test_util/testutil.h"
#include "util/defer.h"
#include "util/mutexlock.h"
#include "util/random.h"
#include "utilities/fault_injection_env.h"
@@ -7903,10 +7902,7 @@ class FastOpenTestFS : public FileSystemWrapper {
IODebugContext* dbg) override {
if (file_opts.file_metadata != nullptr) {
metadata_passed_on_open_.fetch_add(1, std::memory_order_relaxed);
{
MutexLock l(&last_metadata_mu_);
last_metadata_received_ = *file_opts.file_metadata;
}
last_metadata_received_ = *file_opts.file_metadata;
}
IOStatus s = target()->NewRandomAccessFile(fname, file_opts, result, dbg);
if (s.ok()) {
@@ -7925,21 +7921,18 @@ class FastOpenTestFS : public FileSystemWrapper {
}
std::string GetLastMetadataReceived() const {
MutexLock l(&last_metadata_mu_);
return last_metadata_received_;
}
void ResetCounters() {
metadata_retrieved_count_.store(0, std::memory_order_relaxed);
metadata_passed_on_open_.store(0, std::memory_order_relaxed);
MutexLock l(&last_metadata_mu_);
last_metadata_received_.clear();
}
private:
std::atomic<int> metadata_retrieved_count_{0};
std::atomic<int> metadata_passed_on_open_{0};
mutable port::Mutex last_metadata_mu_;
std::string last_metadata_received_;
};
@@ -8281,122 +8274,6 @@ TEST_F(DBTest2, FastSstOpenDisableAfterMetadataPersisted) {
ASSERT_OK(DestroyDB(test_dbname, options));
}
TEST_F(DBTest2, FastSstOpenMetadataPreservedAcrossManifestRotation) {
// Regression test: FileMetaData::file_open_metadata for unchanged live
// SSTs must survive a MANIFEST rotation. WriteCurrentStateToManifest
// snapshots live SSTs into a new MANIFEST; if it drops file_open_metadata
// for those unchanged SSTs, the fast_sst_open optimization is silently
// disabled for them until they are rewritten by flush/compaction/ingest.
auto test_fs = std::make_shared<FastOpenTestFS>(env_->GetFileSystem());
std::unique_ptr<Env> test_env(new CompositeEnvWrapper(env_, test_fs));
Options options;
options.env = test_env.get();
options.fast_sst_open = true;
options.create_if_missing = true;
// Keep the pre-rotation SST from being rewritten by compaction.
options.disable_auto_compactions = true;
std::string test_dbname = test::PerThreadDBPath("fast_open_manifest_rotate");
ASSERT_OK(DestroyDB(test_dbname, options));
std::unique_ptr<DB> db;
ASSERT_OK(DB::Open(options, test_dbname, &db));
// Flush an SST; metadata is retrieved and persisted in the MANIFEST.
ASSERT_OK(db->Put(WriteOptions(), "key1", "value1"));
ASSERT_OK(db->Flush(FlushOptions()));
ASSERT_EQ(1, test_fs->GetMetadataRetrievedCount());
// Shrink max_manifest_file_size so the next MANIFEST write rotates and
// exercises WriteCurrentStateToManifest.
ASSERT_OK(db->SetDBOptions(
{{"max_manifest_file_size", "1"}, {"max_manifest_space_amp_pct", "0"}}));
uint64_t manifest_before =
static_cast<DBImpl*>(db.get())->TEST_Current_Manifest_FileNo();
// Flush a second SST to trigger the rotation. SST #1 is unchanged, so
// the rotated MANIFEST snapshot must carry SST #1's file_open_metadata.
ASSERT_OK(db->Put(WriteOptions(), "key2", "value2"));
ASSERT_OK(db->Flush(FlushOptions()));
uint64_t manifest_after =
static_cast<DBImpl*>(db.get())->TEST_Current_Manifest_FileNo();
ASSERT_GT(manifest_after, manifest_before);
db.reset();
test_fs->ResetCounters();
// Reopen. Every live SST should be opened with file_open_metadata.
// Pre-fix: only SST #2 (added by the rotating edit) has metadata; SST #1
// was stripped by the rotation snapshot, so the count would be 1.
ASSERT_OK(DB::Open(options, test_dbname, &db));
std::string value;
ASSERT_OK(db->Get(ReadOptions(), "key1", &value));
ASSERT_EQ("value1", value);
ASSERT_OK(db->Get(ReadOptions(), "key2", &value));
ASSERT_EQ("value2", value);
ASSERT_EQ(2, test_fs->GetMetadataPassedOnOpenCount());
db.reset();
ASSERT_OK(DestroyDB(test_dbname, options));
}
TEST_F(DBTest2, FastSstOpenMetadataPreservedAcrossTrivialMove) {
// Regression test: FileMetaData::file_open_metadata must survive a trivial
// move. Trivial move re-records an SST at a new level via DeleteFile +
// AddFile without physically rewriting the file. If AddFile drops
// file_open_metadata, the file loses its fast_sst_open advantage until
// it is next rewritten by real compaction/flush/ingest.
auto test_fs = std::make_shared<FastOpenTestFS>(env_->GetFileSystem());
std::unique_ptr<Env> test_env(new CompositeEnvWrapper(env_, test_fs));
Options options;
options.env = test_env.get();
options.fast_sst_open = true;
options.create_if_missing = true;
options.disable_auto_compactions = true;
std::string test_dbname = test::PerThreadDBPath("fast_open_trivial_move");
ASSERT_OK(DestroyDB(test_dbname, options));
std::unique_ptr<DB> db;
ASSERT_OK(DB::Open(options, test_dbname, &db));
// Flush a single SST at L0; metadata is retrieved once and persisted.
ASSERT_OK(db->Put(WriteOptions(), "key1", "value1"));
ASSERT_OK(db->Flush(FlushOptions()));
ASSERT_EQ(1, test_fs->GetMetadataRetrievedCount());
// Manual compaction. With a single L0 file and empty lower levels, the
// compaction picker converts this into a trivial move (no physical
// rewrite), exercising PrepareTrivialMoveEdit.
ASSERT_OK(db->CompactRange(CompactRangeOptions(), nullptr, nullptr));
// If the SST had been rewritten, metadata retrieval would have re-run on
// the new file. Unchanged count confirms this was a trivial move.
ASSERT_EQ(1, test_fs->GetMetadataRetrievedCount());
db.reset();
test_fs->ResetCounters();
// Reopen. The trivially-moved SST should still carry its
// file_open_metadata and be opened via the fast_sst_open fast path.
// Pre-fix, the trivial move stripped it and this count would be 0.
ASSERT_OK(DB::Open(options, test_dbname, &db));
std::string value;
ASSERT_OK(db->Get(ReadOptions(), "key1", &value));
ASSERT_EQ("value1", value);
ASSERT_EQ(1, test_fs->GetMetadataPassedOnOpenCount());
db.reset();
ASSERT_OK(DestroyDB(test_dbname, options));
}
} // namespace ROCKSDB_NAMESPACE
int main(int argc, char** argv) {
+4 -78
View File
@@ -8,7 +8,6 @@
#include <cstdint>
#include <memory>
#include <string>
#include <unordered_set>
#include <vector>
#include "db/db_impl/db_impl.h"
@@ -21,8 +20,8 @@
#include "rocksdb/db.h"
#include "rocksdb/env.h"
#include "rocksdb/metadata.h"
#include "rocksdb/transaction_log.h"
#include "rocksdb/types.h"
#include "rocksdb/wal_iterator.h"
#include "test_util/sync_point.h"
#include "util/file_checksum_helper.h"
#include "util/mutexlock.h"
@@ -196,64 +195,14 @@ Status DBImpl::GetCurrentWalFile(std::unique_ptr<WalFile>* current_wal_file) {
return wal_manager_.GetLiveWalFile(current_logfile_number, current_wal_file);
}
Status DBImpl::AppendColumnFamilyDropsToManifest(
const std::string& manifest_path, uint64_t manifest_size,
const std::vector<uint32_t>& cf_ids) {
const WriteOptions write_options;
// Snapshot manifest_preallocation_size_ under the DB mutex per VersionSet's
// contract (the field is mutated by SetDBOptions under this mutex).
uint64_t preallocation_size = 0;
{
InstrumentedMutexLock l(&mutex_);
preallocation_size = versions_->manifest_preallocation_size_;
}
return versions_->AppendColumnFamilyDropsToManifest(
manifest_path, manifest_size, cf_ids, write_options, preallocation_size);
}
Status DBImpl::GetLiveFilesStorageInfo(
const LiveFilesStorageInfoOptions& opts,
std::vector<LiveFileStorageInfo>* files) {
return GetLiveFilesStorageInfoImpl(opts, /*include_cf_ids=*/{}, files,
/*excluded_cf_ids=*/nullptr);
}
Status DBImpl::GetLiveFilesStorageInfoForSubsetCheckpoint(
const LiveFilesStorageInfoOptions& opts,
const std::vector<uint32_t>& include_cf_ids,
std::vector<LiveFileStorageInfo>* files,
std::vector<uint32_t>* excluded_cf_ids) {
// Internal contract: caller must coalesce ids and always include the default
// CF (it cannot be dropped, so a subset checkpoint without it would produce
// an unopenable DB). CheckpointImpl enforces this before calling here.
assert(!include_cf_ids.empty());
assert(std::find(include_cf_ids.begin(), include_cf_ids.end(),
default_cf_handle_->GetID()) != include_cf_ids.end());
assert(excluded_cf_ids != nullptr);
return GetLiveFilesStorageInfoImpl(opts, include_cf_ids, files,
excluded_cf_ids);
}
Status DBImpl::GetLiveFilesStorageInfoImpl(
const LiveFilesStorageInfoOptions& opts,
const std::vector<uint32_t>& include_cf_ids,
std::vector<LiveFileStorageInfo>* files,
std::vector<uint32_t>* excluded_cf_ids) {
// To avoid returning partial results, only move results to files on success.
assert(files);
files->clear();
std::vector<LiveFileStorageInfo> results;
const bool cf_subset = !include_cf_ids.empty();
assert(!cf_subset || excluded_cf_ids != nullptr);
const std::unordered_set<uint32_t> include_cf_id_set(include_cf_ids.begin(),
include_cf_ids.end());
// Tracks which requested ids remain to be observed as live under the DB
// mutex; any id still present after the enumeration was either dropped
// before or during the checkpoint (race) and must not silently disappear
// from the checkpoint.
std::unordered_set<uint32_t> unseen_include_cf_ids = include_cf_id_set;
// NOTE: This implementation was largely migrated from Checkpoint.
VectorWalPtr live_wal_files;
@@ -303,7 +252,7 @@ Status DBImpl::GetLiveFilesStorageInfoImpl(
"capturing live files. Retry with flush enabled.");
}
if (flush_memtable) {
wal_locked = !lock_wal_owner_thread_id_counts_.empty();
wal_locked = lock_wal_count_ > 0;
if (wal_locked) {
if (needs_blob_direct_write_flush) {
mutex_.Unlock();
@@ -311,12 +260,8 @@ Status DBImpl::GetLiveFilesStorageInfoImpl(
"Blob direct write requires flushing active blob files before "
"capturing live files. Retry with WAL unlocked.");
}
}
if (wal_locked && !has_unpersisted_data_.load(std::memory_order_relaxed)) {
ROCKS_LOG_INFO(
immutable_db_options_.info_log,
"Skipping FlushForGetLiveFiles while WAL is locked and all data is "
"already persisted");
ROCKS_LOG_INFO(immutable_db_options_.info_log,
"Can't FlushForGetLiveFiles while WAL is locked");
} else {
Status status = FlushForGetLiveFiles(opts.atomic_flush);
if (!status.ok()) {
@@ -333,14 +278,6 @@ Status DBImpl::GetLiveFilesStorageInfoImpl(
if (cfd->IsDropped()) {
continue;
}
if (cf_subset &&
include_cf_id_set.find(cfd->GetID()) == include_cf_id_set.end()) {
excluded_cf_ids->push_back(cfd->GetID());
continue;
}
if (cf_subset) {
unseen_include_cf_ids.erase(cfd->GetID());
}
VersionStorageInfo& vsi = *cfd->current()->storage_info();
auto& cf_paths = cfd->ioptions().cf_paths;
@@ -402,17 +339,6 @@ Status DBImpl::GetLiveFilesStorageInfoImpl(
}
}
// Release-build validation: every id the subset-checkpoint caller asked for
// must have been observed as live under the mutex. If any is missing, it was
// dropped before we ran (stale handle) or lost a race with a concurrent
// drop; either way the checkpoint would silently omit it, violating the
// caller's contract that the checkpoint contains the requested CFs.
if (cf_subset && !unseen_include_cf_ids.empty()) {
mutex_.Unlock();
return Status::InvalidArgument(
"Requested column family id was not live at checkpoint time");
}
// Capture some final info before releasing mutex
const uint64_t manifest_number = versions_->manifest_file_number();
const uint64_t manifest_size = versions_->manifest_file_size();
+5 -138
View File
@@ -8,9 +8,7 @@
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include <atomic>
#include <condition_variable>
#include <limits>
#include <mutex>
#include "db/db_impl/db_impl.h"
#include "db/db_test_util.h"
@@ -2221,12 +2219,8 @@ TEST_F(DBFlushTest, FireOnFlushCompletedAfterCommittedResult) {
listener->seq1 = db_->GetLatestSequenceNumber();
// t1 will wait for the second flush complete before committing flush result.
auto t1 = port::Thread([&]() {
// flush_opts.wait = true, and listener_wait = true so that Flush() does not
// return until the OnFlushCompleted callbacks (which set completed1 and
// completed2) have finished running.
FlushOptions flush_opts;
flush_opts.listener_wait = true;
ASSERT_OK(db_->Flush(flush_opts));
// flush_opts.wait = true
ASSERT_OK(db_->Flush(FlushOptions()));
});
// Wait for first flush started.
TEST_SYNC_POINT(
@@ -2239,142 +2233,15 @@ TEST_F(DBFlushTest, FireOnFlushCompletedAfterCommittedResult) {
flush_opts.wait = false;
ASSERT_OK(db_->Flush(flush_opts));
t1.join();
// listener_wait on t1's flush above guarantees both OnFlushCompleted
// callbacks have finished by the time Flush() returned; no need to
// additionally wait for background work here.
// Ensure background work is fully finished including listener callbacks
// before accessing listener state.
ASSERT_OK(dbfull()->TEST_WaitForBackgroundWork());
ASSERT_TRUE(listener->completed1);
ASSERT_TRUE(listener->completed2);
SyncPoint::GetInstance()->DisableProcessing();
SyncPoint::GetInstance()->ClearAllCallBacks();
}
namespace {
// EventListener whose OnFlushCompleted blocks until explicitly released, used
// to verify FlushOptions::listener_wait. Optionally only blocks on the first
// callback (useful for atomic flush, which fires one callback per CF).
class BlockingFlushListener : public EventListener {
public:
explicit BlockingFlushListener(bool block_only_first)
: block_only_first_(block_only_first) {}
void OnFlushCompleted(DB* /*db*/, const FlushJobInfo& /*info*/) override {
if (block_only_first_ && num_completed_.fetch_add(1) != 0) {
return;
}
std::unique_lock<std::mutex> lk(mu_);
entered_ = true;
cv_.notify_all();
cv_.wait(lk, [this] { return release_; });
returned_ = true;
}
void WaitUntilEntered() {
std::unique_lock<std::mutex> lk(mu_);
cv_.wait(lk, [this] { return entered_; });
}
void Release() {
{
std::lock_guard<std::mutex> lk(mu_);
release_ = true;
}
cv_.notify_all();
}
bool CallbackReturned() {
std::lock_guard<std::mutex> lk(mu_);
return returned_;
}
private:
const bool block_only_first_;
std::atomic<int> num_completed_{0};
std::mutex mu_;
std::condition_variable cv_;
bool entered_ = false;
bool release_ = false;
bool returned_ = false;
};
} // anonymous namespace
TEST_F(DBFlushTest, ListenerWaitWaitsForOnFlushCompleted) {
// With FlushOptions::listener_wait, Flush(wait=true) must not return until
// the OnFlushCompleted callback has finished, even if the flush result is
// already committed and bg_cv_ is signalled by unrelated background work.
auto listener = std::make_shared<BlockingFlushListener>(
/*block_only_first=*/false);
Options options = CurrentOptions();
options.listeners.push_back(listener);
Reopen(options);
ASSERT_OK(Put("k", "v"));
std::atomic<bool> flush_returned{false};
port::Thread flush_thread([&] {
// Exercises the TEST_ wrapper, which flushes with wait=true and
// listener_wait=true.
ASSERT_OK(dbfull()->TEST_FlushMemTableWithListenerWait());
flush_returned.store(true);
});
// Wait until we are inside OnFlushCompleted. At this point the memtable has
// already been committed/removed, which is what unblocks a plain
// Flush(wait=true).
listener->WaitUntilEntered();
// Pump spurious bg_cv_ wakeups. A waiter that ignored listener_wait would
// wake, observe the memtable already gone, and return here.
for (int i = 0; i < 10; ++i) {
db_->DisableManualCompaction();
db_->EnableManualCompaction();
}
// The OnFlushCompleted callback has not returned, so neither must Flush().
ASSERT_FALSE(listener->CallbackReturned());
ASSERT_FALSE(flush_returned.load());
listener->Release();
flush_thread.join();
ASSERT_TRUE(flush_returned.load());
ASSERT_TRUE(listener->CallbackReturned());
}
TEST_F(DBFlushTest, ListenerWaitAtomicFlushWaitsForAllOnFlushCompleted) {
// Same guarantee for atomic flush across multiple column families. The atomic
// flush removes all CFs' memtables together and then fires OnFlushCompleted
// per CF, releasing the DB mutex between CFs; listener_wait must still block
// Flush() until the (first, still-running) callback has finished.
auto listener = std::make_shared<BlockingFlushListener>(
/*block_only_first=*/true);
Options options = CurrentOptions();
options.atomic_flush = true;
options.listeners.push_back(listener);
CreateAndReopenWithCF({"pikachu"}, options);
ASSERT_OK(Put(0, "k0", "v0"));
ASSERT_OK(Put(1, "k1", "v1"));
std::atomic<bool> flush_returned{false};
port::Thread flush_thread([&] {
FlushOptions fo;
fo.wait = true;
fo.listener_wait = true;
ASSERT_OK(db_->Flush(fo, {handles_[0], handles_[1]}));
flush_returned.store(true);
});
listener->WaitUntilEntered();
for (int i = 0; i < 10; ++i) {
db_->DisableManualCompaction();
db_->EnableManualCompaction();
}
ASSERT_FALSE(listener->CallbackReturned());
ASSERT_FALSE(flush_returned.load());
listener->Release();
flush_thread.join();
ASSERT_TRUE(flush_returned.load());
ASSERT_TRUE(listener->CallbackReturned());
}
TEST_F(DBFlushTest, FlushWithBlob) {
constexpr uint64_t min_blob_size = 10;
+182 -13
View File
@@ -34,6 +34,188 @@ size_t CompactedDBImpl::FindFile(const Slice& key) {
files_.files);
}
Status CompactedDBImpl::Get(const ReadOptions& _read_options,
ColumnFamilyHandle*, const Slice& key,
PinnableSlice* value, std::string* timestamp) {
if (_read_options.io_activity != Env::IOActivity::kUnknown &&
_read_options.io_activity != Env::IOActivity::kGet) {
return Status::InvalidArgument(
"Can only call Get with `ReadOptions::io_activity` is "
"`Env::IOActivity::kUnknown` or `Env::IOActivity::kGet`");
}
ReadOptions read_options(_read_options);
if (read_options.io_activity == Env::IOActivity::kUnknown) {
read_options.io_activity = Env::IOActivity::kGet;
}
assert(user_comparator_);
if (read_options.timestamp) {
Status s =
FailIfTsMismatchCf(DefaultColumnFamily(), *(read_options.timestamp));
if (!s.ok()) {
return s;
}
if (read_options.timestamp->size() > 0) {
s = FailIfReadCollapsedHistory(cfd_, cfd_->GetSuperVersion(),
*(read_options.timestamp));
if (!s.ok()) {
return s;
}
}
} else {
const Status s = FailIfCfHasTs(DefaultColumnFamily());
if (!s.ok()) {
return s;
}
}
// Clear the timestamps for returning results so that we can distinguish
// between tombstone or key that has never been written
if (timestamp) {
timestamp->clear();
}
GetWithTimestampReadCallback read_cb(kMaxSequenceNumber);
BlobFetcher blob_fetcher(version_, read_options);
std::string* ts =
user_comparator_->timestamp_size() > 0 ? timestamp : nullptr;
LookupKey lkey(key, kMaxSequenceNumber, read_options.timestamp);
GetContext get_context(user_comparator_, nullptr, nullptr, nullptr,
GetContext::kNotFound, lkey.user_key(), value,
/*columns=*/nullptr, ts, nullptr, nullptr, true,
nullptr, nullptr, nullptr, nullptr, &read_cb,
nullptr /* is_blob_index */, 0 /* tracing_get_id */,
&blob_fetcher);
const FdWithKeyRange& f = files_.files[FindFile(lkey.user_key())];
if (user_comparator_->CompareWithoutTimestamp(
key, /*a_has_ts=*/false,
ExtractUserKeyAndStripTimestamp(f.smallest_key,
user_comparator_->timestamp_size()),
/*b_has_ts=*/false) < 0) {
return Status::NotFound();
}
TableReader* t = nullptr;
TableCache::TypedHandle* handle = nullptr;
Status s = cfd_->table_cache()->FindTable(
read_options, cfd_->table_cache()->file_options(),
cfd_->internal_comparator(), *f.file_metadata, &handle,
version_->GetMutableCFOptions(), &t, false /* no_io */,
nullptr /* file_read_hist */, false /* skip_filters */, files_level_,
true /* prefetch_index_and_filter_in_cache */,
0 /* max_file_size_for_l0_meta_pin */, f.file_metadata->temperature,
true /* pin_table_handle */);
if (s.ok()) {
assert(handle == nullptr);
// Use TableReader directly to avoid extra table_cache->Get() overheads
s = t->Get(read_options, lkey.internal_key(), &get_context, nullptr);
}
if (!s.ok() && !s.IsNotFound()) {
return s;
}
if (get_context.State() == GetContext::kFound) {
return Status::OK();
}
return Status::NotFound();
}
void CompactedDBImpl::MultiGet(const ReadOptions& _read_options,
size_t num_keys,
ColumnFamilyHandle** /*column_families*/,
const Slice* keys, PinnableSlice* values,
std::string* timestamps, Status* statuses,
const bool /*sorted_input*/) {
assert(user_comparator_);
Status s;
if (_read_options.io_activity != Env::IOActivity::kUnknown &&
_read_options.io_activity != Env::IOActivity::kMultiGet) {
s = Status::InvalidArgument(
"Can only call MultiGet with `ReadOptions::io_activity` is "
"`Env::IOActivity::kUnknown` or `Env::IOActivity::kMultiGet`");
}
ReadOptions read_options(_read_options);
if (s.ok()) {
if (read_options.io_activity == Env::IOActivity::kUnknown) {
read_options.io_activity = Env::IOActivity::kMultiGet;
}
if (read_options.timestamp) {
s = FailIfTsMismatchCf(DefaultColumnFamily(), *(read_options.timestamp));
if (s.ok()) {
if (read_options.timestamp->size() > 0) {
s = FailIfReadCollapsedHistory(cfd_, cfd_->GetSuperVersion(),
*(read_options.timestamp));
}
}
} else {
s = FailIfCfHasTs(DefaultColumnFamily());
}
}
if (!s.ok()) {
for (size_t i = 0; i < num_keys; ++i) {
statuses[i] = s;
}
return;
}
// Clear the timestamps for returning results so that we can distinguish
// between tombstone or key that has never been written
if (timestamps) {
for (size_t i = 0; i < num_keys; ++i) {
timestamps[i].clear();
}
}
GetWithTimestampReadCallback read_cb(kMaxSequenceNumber);
BlobFetcher blob_fetcher(version_, read_options);
for (size_t i = 0; i < num_keys; ++i) {
const Slice& key = keys[i];
LookupKey lkey(key, kMaxSequenceNumber, read_options.timestamp);
const FdWithKeyRange& f = files_.files[FindFile(lkey.user_key())];
if (user_comparator_->CompareWithoutTimestamp(
key, /*a_has_ts=*/false,
ExtractUserKeyAndStripTimestamp(f.smallest_key,
user_comparator_->timestamp_size()),
/*b_has_ts=*/false) < 0) {
statuses[i] = Status::NotFound();
continue;
}
PinnableSlice& pinnable_val = values[i];
std::string* timestamp = timestamps ? &timestamps[i] : nullptr;
GetContext get_context(
user_comparator_, nullptr, nullptr, nullptr, GetContext::kNotFound,
lkey.user_key(), &pinnable_val, /*columns=*/nullptr,
user_comparator_->timestamp_size() > 0 ? timestamp : nullptr, nullptr,
nullptr, true, nullptr, nullptr, nullptr, nullptr, &read_cb,
nullptr /* is_blob_index */, 0 /* tracing_get_id */, &blob_fetcher);
TableReader* t = nullptr;
TableCache::TypedHandle* handle = nullptr;
Status status = cfd_->table_cache()->FindTable(
read_options, cfd_->table_cache()->file_options(),
cfd_->internal_comparator(), *f.file_metadata, &handle,
version_->GetMutableCFOptions(), &t, false /* no_io */,
nullptr /* file_read_hist */, false /* skip_filters */, files_level_,
true /* prefetch_index_and_filter_in_cache */,
0 /* max_file_size_for_l0_meta_pin */, f.file_metadata->temperature,
true /* pin_table_handle */);
if (status.ok()) {
assert(handle == nullptr);
// Use TableReader directly to avoid extra table_cache->Get() overheads
status = t->Get(read_options, lkey.internal_key(), &get_context, nullptr);
}
if (!status.ok() && !status.IsNotFound()) {
statuses[i] = status;
} else if (get_context.State() == GetContext::kFound) {
statuses[i] = Status::OK();
} else {
statuses[i] = Status::NotFound();
}
}
}
Status CompactedDBImpl::Init(const Options& options) {
SuperVersionContext sv_context(/* create_superversion */ true);
mutex_.Lock();
@@ -119,16 +301,3 @@ Status CompactedDBImpl::Open(const Options& options, const std::string& dbname,
}
} // namespace ROCKSDB_NAMESPACE
// Generate the regular and coroutine versions of the functions defined in
// compacted_db_impl_sync_and_async.h by including it twice. The macros expand
// differently based on whether WITH_COROUTINES or WITHOUT_COROUTINES is
// defined.
// clang-format off
#define WITHOUT_COROUTINES
#include "db/db_impl/compacted_db_impl_sync_and_async.h"
#undef WITHOUT_COROUTINES
#define WITH_COROUTINES
#include "db/db_impl/compacted_db_impl_sync_and_async.h"
#undef WITH_COROUTINES
// clang-format on
+7 -10
View File
@@ -26,21 +26,18 @@ class CompactedDBImpl : public DBImpl {
// Implementations of the DB interface
using DB::Get;
DECLARE_SYNC_AND_ASYNC_OVERRIDE(Status, Get, const ReadOptions& options,
ColumnFamilyHandle* column_family,
const Slice& key, PinnableSlice* value,
std::string* timestamp);
Status Get(const ReadOptions& options, ColumnFamilyHandle* column_family,
const Slice& key, PinnableSlice* value,
std::string* timestamp) override;
using DB::MultiGet;
// Note that CompactedDBImpl::MultiGet is not the optimized version of
// MultiGet to use.
// TODO: optimize CompactedDBImpl::MultiGet, see DBImpl::MultiGet for details.
DECLARE_SYNC_AND_ASYNC_OVERRIDE(void, MultiGet, const ReadOptions& options,
size_t num_keys,
ColumnFamilyHandle** column_families,
const Slice* keys, PinnableSlice* values,
std::string* timestamps, Status* statuses,
const bool sorted_input);
void MultiGet(const ReadOptions& options, size_t num_keys,
ColumnFamilyHandle** column_families, const Slice* keys,
PinnableSlice* values, std::string* timestamps,
Status* statuses, const bool sorted_input) override;
using DBImpl::Put;
Status Put(const WriteOptions& /*options*/,
@@ -1,211 +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/coro_utils.h"
#if defined(USE_COROUTINES) && defined(WITH_COROUTINES)
#include "util/coro_stats_util.h"
#endif // USE_COROUTINES && WITH_COROUTINES
#if defined(WITHOUT_COROUTINES) || \
(defined(USE_COROUTINES) && defined(WITH_COROUTINES))
namespace ROCKSDB_NAMESPACE {
DEFINE_SYNC_AND_ASYNC(Status, CompactedDBImpl::Get)
(const ReadOptions& _read_options, ColumnFamilyHandle*, const Slice& key,
PinnableSlice* value, std::string* timestamp) {
#ifdef WITH_COROUTINES
INSTALL_COROUTINE_STATS_CONTEXT_SCOPE(
immutable_db_options_.fs->GetReadExecutor(), immutable_db_options_.env);
#endif
if (_read_options.io_activity != Env::IOActivity::kUnknown &&
_read_options.io_activity != Env::IOActivity::kGet) {
CO_RETURN Status::InvalidArgument(
"Can only call Get with `ReadOptions::io_activity` is "
"`Env::IOActivity::kUnknown` or `Env::IOActivity::kGet`");
}
ReadOptions read_options(_read_options);
if (read_options.io_activity == Env::IOActivity::kUnknown) {
read_options.io_activity = Env::IOActivity::kGet;
}
assert(user_comparator_);
if (read_options.timestamp) {
Status s =
FailIfTsMismatchCf(DefaultColumnFamily(), *(read_options.timestamp));
if (!s.ok()) {
CO_RETURN s;
}
if (read_options.timestamp->size() > 0) {
s = FailIfReadCollapsedHistory(cfd_, cfd_->GetSuperVersion(),
*(read_options.timestamp));
if (!s.ok()) {
CO_RETURN s;
}
}
} else {
const Status s = FailIfCfHasTs(DefaultColumnFamily());
if (!s.ok()) {
CO_RETURN s;
}
}
// Clear the timestamps for returning results so that we can distinguish
// between tombstone or key that has never been written
if (timestamp) {
timestamp->clear();
}
GetWithTimestampReadCallback read_cb(kMaxSequenceNumber);
VersionBlobFetcher blob_fetcher(version_, read_options);
std::string* ts =
user_comparator_->timestamp_size() > 0 ? timestamp : nullptr;
LookupKey lkey(key, kMaxSequenceNumber, read_options.timestamp);
GetContext get_context(user_comparator_, nullptr, nullptr, nullptr,
GetContext::kNotFound, lkey.user_key(), value,
/*columns=*/nullptr, ts, nullptr, nullptr, true,
nullptr, nullptr, nullptr, nullptr, &read_cb,
nullptr /* is_blob_index */, 0 /* tracing_get_id */,
&blob_fetcher);
const FdWithKeyRange& f = files_.files[FindFile(lkey.user_key())];
if (user_comparator_->CompareWithoutTimestamp(
key, /*a_has_ts=*/false,
ExtractUserKeyAndStripTimestamp(f.smallest_key,
user_comparator_->timestamp_size()),
/*b_has_ts=*/false) < 0) {
CO_RETURN Status::NotFound();
}
TableReader* t = nullptr;
TableCache::TypedHandle* handle = nullptr;
Status s = cfd_->table_cache()->FindTable(
read_options, cfd_->table_cache()->file_options(),
cfd_->internal_comparator(), *f.file_metadata, &handle,
version_->GetMutableCFOptions(), &t, false /* no_io */,
nullptr /* file_read_hist */, false /* skip_filters */, files_level_,
true /* prefetch_index_and_filter_in_cache */,
0 /* max_file_size_for_l0_meta_pin */, f.file_metadata->temperature,
true /* pin_table_handle */);
if (s.ok()) {
assert(handle == nullptr);
// Use TableReader directly to avoid extra table_cache->Get() overheads
s = CO_AWAIT(t->Get, read_options, lkey.internal_key(), &get_context,
nullptr);
}
if (!s.ok() && !s.IsNotFound()) {
CO_RETURN s;
}
if (get_context.State() == GetContext::kFound) {
CO_RETURN Status::OK();
}
CO_RETURN Status::NotFound();
}
DEFINE_SYNC_AND_ASYNC(void, CompactedDBImpl::MultiGet)
(const ReadOptions& _read_options, size_t num_keys,
ColumnFamilyHandle** /*column_families*/, const Slice* keys,
PinnableSlice* values, std::string* timestamps, Status* statuses,
const bool /*sorted_input*/) {
#ifdef WITH_COROUTINES
INSTALL_COROUTINE_STATS_CONTEXT_SCOPE(
immutable_db_options_.fs->GetReadExecutor(), immutable_db_options_.env);
#endif
assert(user_comparator_);
Status s;
if (_read_options.io_activity != Env::IOActivity::kUnknown &&
_read_options.io_activity != Env::IOActivity::kMultiGet) {
s = Status::InvalidArgument(
"Can only call MultiGet with `ReadOptions::io_activity` is "
"`Env::IOActivity::kUnknown` or `Env::IOActivity::kMultiGet`");
}
ReadOptions read_options(_read_options);
if (s.ok()) {
if (read_options.io_activity == Env::IOActivity::kUnknown) {
read_options.io_activity = Env::IOActivity::kMultiGet;
}
if (read_options.timestamp) {
s = FailIfTsMismatchCf(DefaultColumnFamily(), *(read_options.timestamp));
if (s.ok()) {
if (read_options.timestamp->size() > 0) {
s = FailIfReadCollapsedHistory(cfd_, cfd_->GetSuperVersion(),
*(read_options.timestamp));
}
}
} else {
s = FailIfCfHasTs(DefaultColumnFamily());
}
}
if (!s.ok()) {
for (size_t i = 0; i < num_keys; ++i) {
statuses[i] = s;
}
CO_RETURN;
}
// Clear the timestamps for returning results so that we can distinguish
// between tombstone or key that has never been written
if (timestamps) {
for (size_t i = 0; i < num_keys; ++i) {
timestamps[i].clear();
}
}
GetWithTimestampReadCallback read_cb(kMaxSequenceNumber);
VersionBlobFetcher blob_fetcher(version_, read_options);
for (size_t i = 0; i < num_keys; ++i) {
const Slice& key = keys[i];
LookupKey lkey(key, kMaxSequenceNumber, read_options.timestamp);
const FdWithKeyRange& f = files_.files[FindFile(lkey.user_key())];
if (user_comparator_->CompareWithoutTimestamp(
key, /*a_has_ts=*/false,
ExtractUserKeyAndStripTimestamp(f.smallest_key,
user_comparator_->timestamp_size()),
/*b_has_ts=*/false) < 0) {
statuses[i] = Status::NotFound();
continue;
}
PinnableSlice& pinnable_val = values[i];
std::string* timestamp = timestamps ? &timestamps[i] : nullptr;
GetContext get_context(
user_comparator_, nullptr, nullptr, nullptr, GetContext::kNotFound,
lkey.user_key(), &pinnable_val, /*columns=*/nullptr,
user_comparator_->timestamp_size() > 0 ? timestamp : nullptr, nullptr,
nullptr, true, nullptr, nullptr, nullptr, nullptr, &read_cb,
nullptr /* is_blob_index */, 0 /* tracing_get_id */, &blob_fetcher);
TableReader* t = nullptr;
TableCache::TypedHandle* handle = nullptr;
Status status = cfd_->table_cache()->FindTable(
read_options, cfd_->table_cache()->file_options(),
cfd_->internal_comparator(), *f.file_metadata, &handle,
version_->GetMutableCFOptions(), &t, false /* no_io */,
nullptr /* file_read_hist */, false /* skip_filters */, files_level_,
true /* prefetch_index_and_filter_in_cache */,
0 /* max_file_size_for_l0_meta_pin */, f.file_metadata->temperature,
true /* pin_table_handle */);
if (status.ok()) {
assert(handle == nullptr);
// Use TableReader directly to avoid extra table_cache->Get() overheads
status = CO_AWAIT(t->Get, read_options, lkey.internal_key(), &get_context,
nullptr);
}
if (!status.ok() && !status.IsNotFound()) {
statuses[i] = status;
} else if (get_context.State() == GetContext::kFound) {
statuses[i] = Status::OK();
} else {
statuses[i] = Status::NotFound();
}
}
}
} // namespace ROCKSDB_NAMESPACE
#endif
+882 -631
View File
File diff suppressed because it is too large. Load diff
+73 -237
View File
@@ -21,7 +21,6 @@
#include <string>
#include <unordered_map>
#include <utility>
#include <variant>
#include <vector>
#include "db/column_family.h"
@@ -54,7 +53,6 @@
#include "memtable/wbwi_memtable.h"
#include "monitoring/instrumented_mutex.h"
#include "options/db_options.h"
#include "options/options_helper.h"
#include "port/port.h"
#include "rocksdb/attribute_groups.h"
#include "rocksdb/db.h"
@@ -62,30 +60,23 @@
#include "rocksdb/memtablerep.h"
#include "rocksdb/status.h"
#include "rocksdb/trace_reader_writer.h"
#include "rocksdb/transaction_log.h"
#include "rocksdb/user_write_callback.h"
#include "rocksdb/utilities/replayer.h"
#include "rocksdb/utilities/write_batch_with_index.h"
#include "rocksdb/wal_iterator.h"
#include "rocksdb/write_buffer_manager.h"
#include "table/merging_iterator.h"
#include "util/autovector.h"
#include "util/coro_utils.h"
#include "util/hash.h"
#include "util/repeatable_thread.h"
#include "util/stop_watch.h"
#include "util/thread_local.h"
#if USE_COROUTINES
#include "rocksdb/coro_db.h"
#endif
namespace ROCKSDB_NAMESPACE {
class Arena;
class ArenaWrappedDBIter;
class Cleanable;
class FileIngestionHandleImpl;
class SameFileBlobReader;
class InMemoryStatsHistoryIterator;
class MemTable;
class PersistentStatsHistoryIterator;
@@ -204,22 +195,14 @@ struct DBOpenLogRecordReadReporter : public log::Reader::Reporter {
//
// Since it's a very large class, the definition of the functions is
// divided in several db_impl_*.cc files, besides db_impl.cc.
#if USE_COROUTINES
class DBImpl : public DB,
public CoroDB
#else
class DBImpl : public DB
#endif
{
class DBImpl : public DB {
public:
DBImpl(const DBOptions& options, const std::string& dbname,
const bool seq_per_batch = false, const bool batch_per_txn = true,
bool read_only = false);
// No copying or moving allowed
// No copying allowed
DBImpl(const DBImpl&) = delete;
void operator=(const DBImpl&) = delete;
DBImpl(DBImpl&&) = delete;
void operator=(DBImpl&&) = delete;
virtual ~DBImpl();
@@ -285,10 +268,9 @@ class DBImpl : public DB
bool HasAnyBlobDirectWriteColumnFamily();
using DB::Get;
DECLARE_SYNC_AND_ASYNC_OVERRIDE(Status, Get, const ReadOptions& _read_options,
ColumnFamilyHandle* column_family,
const Slice& key, PinnableSlice* value,
std::string* timestamp);
Status Get(const ReadOptions& _read_options,
ColumnFamilyHandle* column_family, const Slice& key,
PinnableSlice* value, std::string* timestamp) override;
using DB::GetEntity;
Status GetEntity(const ReadOptions& options,
@@ -297,10 +279,6 @@ class DBImpl : public DB
Status GetEntity(const ReadOptions& options, const Slice& key,
PinnableAttributeGroups* result) override;
Status GetEntityLazy(const ReadOptions& options,
ColumnFamilyHandle* column_family, const Slice& key,
LazyWideColumns* result) override;
using DB::GetMergeOperands;
Status GetMergeOperands(const ReadOptions& options,
ColumnFamilyHandle* column_family, const Slice& key,
@@ -324,13 +302,10 @@ class DBImpl : public DB
// The values and statuses parameters are arrays with number of elements
// equal to keys.size(). This allows the storage for those to be alloacted
// by the caller on the stack for small batches
DECLARE_SYNC_AND_ASYNC_OVERRIDE(void, MultiGet,
const ReadOptions& _read_options,
const size_t num_keys,
ColumnFamilyHandle** column_families,
const Slice* keys, PinnableSlice* values,
std::string* timestamps, Status* statuses,
const bool sorted_input = false);
void MultiGet(const ReadOptions& _read_options, const size_t num_keys,
ColumnFamilyHandle** column_families, const Slice* keys,
PinnableSlice* values, std::string* timestamps,
Status* statuses, const bool sorted_input = false) override;
void MultiGetWithCallback(
const ReadOptions& _read_options, ColumnFamilyHandle* column_family,
@@ -352,11 +327,6 @@ class DBImpl : public DB
const Slice* keys,
PinnableAttributeGroups* results) override;
void MultiGetEntityLazy(const ReadOptions& options,
ColumnFamilyHandle* column_family, size_t num_keys,
const Slice* keys, LazyWideColumnsBatch* result,
Status* statuses, bool sorted_input) override;
void MultiGetEntityWithCallback(
const ReadOptions& read_options, ColumnFamilyHandle* column_family,
ReadCallback* callback,
@@ -494,8 +464,6 @@ class DBImpl : public DB
void DisableManualCompaction() override;
void AbortAllCompactions() override;
void ResumeAllCompactions() override;
void AbortCompactions(ColumnFamilyHandle* column_family) override;
void ResumeCompactions(ColumnFamilyHandle* column_family) override;
using DB::SetOptions;
Status SetOptions(
@@ -592,10 +560,10 @@ class DBImpl : public DB
Status GetCurrentWalFile(std::unique_ptr<WalFile>* current_wal_file) override;
Status GetCreationTimeOfOldestFile(uint64_t* creation_time) override;
Status GetUpdatesSince(SequenceNumber seq_number,
std::unique_ptr<WalIterator>* iter,
const WalIterator::ReadOptions& read_options =
WalIterator::ReadOptions()) override;
Status GetUpdatesSince(
SequenceNumber seq_number, std::unique_ptr<TransactionLogIterator>* iter,
const TransactionLogIterator::ReadOptions& read_options =
TransactionLogIterator::ReadOptions()) override;
Status DeleteFilesInRanges(ColumnFamilyHandle* column_family,
const RangeOpt* ranges, size_t n,
bool include_end = true);
@@ -608,35 +576,6 @@ class DBImpl : public DB
const LiveFilesStorageInfoOptions& opts,
std::vector<LiveFileStorageInfo>* files) override;
// Variant of GetLiveFilesStorageInfo used by subset-CF Checkpoint. Only
// table/blob files of the given column families are captured; the rest are
// reported in excluded_cf_ids so the caller can reconcile the copied
// MANIFEST (typically via AppendColumnFamilyDropsToManifest below). Caller
// must supply a non-empty include_cf_ids containing the default CF id and a
// non-null excluded_cf_ids; both are internal-contract preconditions.
Status GetLiveFilesStorageInfoForSubsetCheckpoint(
const LiveFilesStorageInfoOptions& opts,
const std::vector<uint32_t>& include_cf_ids,
std::vector<LiveFileStorageInfo>* files,
std::vector<uint32_t>* excluded_cf_ids);
// Shared body of GetLiveFilesStorageInfo and its subset-checkpoint variant.
// include_cf_ids empty -> no filter; otherwise records skipped CF ids in
// *excluded_cf_ids (which must be non-null in that case).
Status GetLiveFilesStorageInfoImpl(
const LiveFilesStorageInfoOptions& opts,
const std::vector<uint32_t>& include_cf_ids,
std::vector<LiveFileStorageInfo>* files,
std::vector<uint32_t>* excluded_cf_ids);
// Appends kColumnFamilyDrop records to the MANIFEST file at manifest_path for
// the given column family ids. Used by Checkpoint to make a subset-CF
// checkpoint's copied MANIFEST consistent with the reduced file set. Operates
// only on the given file; does not mutate this DB's live state.
Status AppendColumnFamilyDropsToManifest(const std::string& manifest_path,
uint64_t manifest_size,
const std::vector<uint32_t>& cf_ids);
Status GetPreparedFileInfoForExternalSstIngestion(
const std::string& file_path,
std::shared_ptr<const PreparedFileInfo>* file_info) override;
@@ -777,33 +716,15 @@ class DBImpl : public DB
PinnableSlice* merge_operands = nullptr;
GetMergeOperandsOptions* get_merge_operands_options = nullptr;
int* number_of_operands = nullptr;
// Lazy wide-column mode (used by GetEntityLazy / MultiGetEntityLazy). When
// `lazy_columns_pin` is non-null, the SST point-lookup path leaves a
// wide-column entity's blob references *unresolved* (see
// GetContext::SaveWideColumnEntityToColumns), so the caller can resolve
// them on demand later. On a successful lookup GetImpl then:
// - sets `*lazy_columns_version` to the Version the entity was read from
// (the resolution context for blob references), and
// - transfers an extra SuperVersion reference by registering a cleanup on
// `*lazy_columns_pin`, so the result may outlive this call (as an
// iterator's result does).
// The SameFileBlobReader for the SST that held the entity (if any) is
// stored in `*lazy_columns_same_file_reader` by the read path, so same-file
// ("embedded") references stay resolvable later. All three must be set
// together. `columns` must also be set (the entity output).
Cleanable* lazy_columns_pin = nullptr;
const Version** lazy_columns_version = nullptr;
const SameFileBlobReader** lazy_columns_same_file_reader = nullptr;
};
DECLARE_SYNC_AND_ASYNC(Status, GetImpl, const ReadOptions& read_options,
ColumnFamilyHandle* column_family, const Slice& key,
PinnableSlice* value);
Status GetImpl(const ReadOptions& read_options,
ColumnFamilyHandle* column_family, const Slice& key,
PinnableSlice* value);
DECLARE_SYNC_AND_ASYNC(Status, GetImpl, const ReadOptions& read_options,
ColumnFamilyHandle* column_family, const Slice& key,
PinnableSlice* value, std::string* timestamp);
Status GetImpl(const ReadOptions& read_options,
ColumnFamilyHandle* column_family, const Slice& key,
PinnableSlice* value, std::string* timestamp);
// Function that Get and KeyMayExist call with no_io true or false
// Note: 'value_found' from KeyMayExist propagates here
@@ -812,20 +733,8 @@ class DBImpl : public DB
// get_impl_options.key via get_impl_options.value
// If get_impl_options.get_value = false get merge operands associated with
// get_impl_options.key via get_impl_options.merge_operands
DECLARE_SYNC_AND_ASYNC_VIRTUAL(Status, GetImpl, const ReadOptions& options,
const Slice& key,
GetImplOptions& get_impl_options);
// Shared implementation of GetEntityLazy / MultiGetEntityLazy for a single
// key: performs a lazy point lookup for `key` (leaving blob references
// unresolved) into `*result`, which takes ownership of a SuperVersion pin so
// it may outlive this call. `read_options` must already be finalized (e.g.
// io_activity set). Returns OK on success, NotFound (with an empty `*result`)
// if there is no entry, or another non-OK status on error. REQUIRES:
// max_open_files == -1 has already been validated by the caller.
Status GetEntityLazyImpl(const ReadOptions& read_options,
ColumnFamilyHandle* column_family, const Slice& key,
LazyWideColumns* result);
virtual Status GetImpl(const ReadOptions& options, const Slice& key,
GetImplOptions& get_impl_options);
// If `snapshot` == kMaxSequenceNumber, set a recent one inside the file.
ArenaWrappedDBIter* NewIteratorImpl(const ReadOptions& options,
@@ -978,13 +887,6 @@ class DBImpl : public DB
void CleanupIteratorSuperVersion(SuperVersion* super_version,
bool background_purge);
// Transfer an extra reference to `super_version` into `pin` (via a cleanup
// callback), so `pin`'s owner keeps the SuperVersion -- and thus the data it
// references -- alive after the current call returns, as an iterator does.
// Shared by the lazy wide-column read path (GetEntityLazy) across the
// primary, read-only, and secondary GetImpl overrides.
void TransferSuperVersionPin(SuperVersion* super_version, Cleanable* pin);
LogsWithPrepTracker* logs_with_prep_tracker() {
return &logs_with_prep_tracker_;
}
@@ -1287,13 +1189,6 @@ class DBImpl : public DB
Status TEST_FlushMemTable(ColumnFamilyData* cfd,
const FlushOptions& flush_opts);
// Like TEST_FlushMemTable(bool wait, ...), but also sets
// FlushOptions::listener_wait so the flush does not return until the
// registered EventListener::OnFlushCompleted callbacks for the flushed
// memtables have finished running.
Status TEST_FlushMemTableWithListenerWait(bool allow_write_stall = false,
ColumnFamilyHandle* cfh = nullptr);
// Flush (multiple) ColumnFamilyData without using ColumnFamilyHandle. This
// is because in certain cases, we can flush column families, wait for the
// flush to complete, but delete the column family handle before the wait
@@ -1502,10 +1397,6 @@ class DBImpl : public DB
bool seq_per_batch() const { return seq_per_batch_; }
#if USE_COROUTINES
CoroDB* GetCoroDB() override { return this; }
#endif
protected:
const std::string dbname_;
const bool read_only_;
@@ -1650,7 +1541,7 @@ class DBImpl : public DB
// 2. db_mutex is NOT held
Status RenameTempFileToOptionsFile(const std::string& file_name,
bool is_remote_compaction_enabled);
Status DeleteObsoleteOptionsFiles(bool schedule_only);
Status DeleteObsoleteOptionsFiles();
void NotifyOnManualFlushScheduled(autovector<ColumnFamilyData*> cfds,
FlushReason flush_reason);
@@ -2328,10 +2219,7 @@ class DBImpl : public DB
// Required: DB mutex held
Status PersistentStatsProcessFormatVersion();
// `io_activity` is used to construct the ReadOptions/WriteOptions for the
// internal recovery work (e.g. the MANIFEST write in LogAndApply). Recovery
// is driven by flush operations, so callers pass Env::IOActivity::kFlush.
Status ResumeImpl(DBRecoverContext context, Env::IOActivity io_activity);
Status ResumeImpl(DBRecoverContext context);
void MaybeIgnoreError(Status* s) const;
@@ -2613,24 +2501,18 @@ class DBImpl : public DB
// memtable pending flush.
// resuming_from_bg_err indicates whether the caller is attempting to resume
// from background error.
// If wait_for_listener_notifications is true, also wait until the
// EventListener::OnFlushCompleted callbacks for the flushed memtables have
// finished running (see FlushOptions::listener_wait).
Status WaitForFlushMemTable(
ColumnFamilyData* cfd, const uint64_t* flush_memtable_id = nullptr,
bool resuming_from_bg_err = false,
std::optional<FlushReason> flush_reason = std::nullopt,
bool wait_for_listener_notifications = false) {
std::optional<FlushReason> flush_reason = std::nullopt) {
return WaitForFlushMemTables({cfd}, {flush_memtable_id},
resuming_from_bg_err, flush_reason,
wait_for_listener_notifications);
resuming_from_bg_err, flush_reason);
}
// Wait for memtables to be flushed for multiple column families.
Status WaitForFlushMemTables(
const autovector<ColumnFamilyData*>& cfds,
const autovector<const uint64_t*>& flush_memtable_ids,
bool resuming_from_bg_err, std::optional<FlushReason> flush_reason,
bool wait_for_listener_notifications = false);
bool resuming_from_bg_err, std::optional<FlushReason> flush_reason);
inline void WaitForPendingWrites() {
mutex_.AssertHeld();
@@ -2659,7 +2541,7 @@ class DBImpl : public DB
}
// Wait for any LockWAL to clear
while (!lock_wal_owner_thread_id_counts_.empty()) {
while (lock_wal_count_ > 0) {
bg_cv_.Wait();
}
}
@@ -2889,24 +2771,9 @@ class DBImpl : public DB
ColumnFamilyData* PopFirstFromCompactionQueue();
FlushRequest PopFirstFromFlushQueue();
struct CompactionQueueThrottled {};
struct CompactionQueueParked {};
struct CompactionQueuePicked {
ColumnFamilyData* cfd;
};
using CompactionQueuePickResult =
std::variant<CompactionQueuePicked, CompactionQueueThrottled,
CompactionQueueParked>;
// Pick the first unthrottled compaction with task token from queue.
CompactionQueuePickResult PickCompactionFromQueue(
ColumnFamilyData* PickCompactionFromQueue(
std::unique_ptr<TaskLimiterToken>* token, LogBuffer* log_buffer);
bool IsCompactionAborted(ColumnFamilyData* cfd) const;
bool MustWaitForCompaction(ColumnFamilyData* cfd);
bool HasPendingManualCompaction(ColumnFamilyData* cfd);
bool RestoreParkedCompaction(ColumnFamilyData* cfd);
void BeginInFlightCompaction(ColumnFamilyData* cfd);
bool EndInFlightCompaction(ColumnFamilyData* cfd);
IOStatus SyncWalImpl(bool include_current_wal,
const WriteOptions& write_options,
@@ -3087,12 +2954,11 @@ class DBImpl : public DB
PinnableWideColumns* columns, std::string* timestamps,
Status* statuses, bool sorted_input);
DECLARE_SYNC_AND_ASYNC(void, MultiGetCommon, const ReadOptions& options,
const size_t num_keys,
ColumnFamilyHandle** column_families,
const Slice* keys, PinnableSlice* values,
PinnableWideColumns* columns, std::string* timestamps,
Status* statuses, bool sorted_input);
void MultiGetCommon(const ReadOptions& options, const size_t num_keys,
ColumnFamilyHandle** column_families, const Slice* keys,
PinnableSlice* values, PinnableWideColumns* columns,
std::string* timestamps, Status* statuses,
bool sorted_input);
// A structure to hold the information required to process MultiGet of keys
// belonging to one column family. For a multi column family MultiGet, there
@@ -3167,9 +3033,8 @@ class DBImpl : public DB
// to have acquired the SuperVersion and pass in a snapshot sequence number
// in order to construct the LookupKeys. The start_key and num_keys specify
// the range of keys in the sorted_keys vector for a single column family.
DECLARE_SYNC_AND_ASYNC(
Status, MultiGetImpl, const ReadOptions& read_options, size_t start_key,
size_t num_keys,
Status MultiGetImpl(
const ReadOptions& read_options, size_t start_key, size_t num_keys,
autovector<KeyContext*, MultiGetContext::MAX_BATCH_SIZE>* sorted_keys,
SuperVersion* sv, SequenceNumber snap_seqnum, ReadCallback* callback);
@@ -3187,56 +3052,50 @@ class DBImpl : public DB
// Resolves a plain value whose current payload is an encoded direct-write
// blob index, either through `value` directly or through the default-column
// view layered on `columns`.
static Status ResolveDirectWritePlainValue(const Slice& key,
const BlobFetcher& blob_fetcher,
static Status ResolveDirectWritePlainValue(const ReadOptions& read_options,
const Slice& key,
const Version* current,
ColumnFamilyData* cfd,
PinnableSlice* value,
PinnableWideColumns* columns);
// Resolves each unresolved direct-write blob-valued column in `columns` and
// rebuilds the serialized wide-column entity in place.
static Status ResolveDirectWriteWideColumns(const Slice& key,
const BlobFetcher& blob_fetcher,
static Status ResolveDirectWriteWideColumns(const ReadOptions& read_options,
const Slice& key,
const Version* current,
ColumnFamilyData* cfd,
PinnableWideColumns* columns);
// Dispatches between plain-value and wide-column direct-write resolution for
// read results observed before flush makes the corresponding blob file
// visible through normal Version metadata.
static bool MaybeResolveDirectWriteValue(
const ReadOptions& read_options, const Slice& key,
bool resolve_direct_write_value, const BlobFetcher& blob_fetcher,
PinnableSlice* value, PinnableWideColumns* columns, Status* s,
bool* is_blob_index, bool* value_found = nullptr);
// Completes primary memtable hits that can still carry direct-write blob
// references before the blob file is visible in Version metadata.
static void PostprocessDirectWriteValueRead(
const ReadOptions& read_options, const Slice& key,
const std::string* timestamp, bool resolve_direct_write_value,
const BlobFetcher* blob_fetcher, PinnableSlice* value,
PinnableWideColumns* columns, Status* s, bool* is_blob_index,
bool* value_found = nullptr);
bool resolve_direct_write_value, const Version* current,
ColumnFamilyData* cfd, PinnableSlice* value, PinnableWideColumns* columns,
Status* s, bool* is_blob_index, bool* value_found = nullptr);
// Resolves memtable read results that still carry blob references through
// either a raw blob-index payload in `value` or unresolved blob columns in
// `columns`. This generic path is also used by read-only/secondary DBs. Sets
// *did_resolve to true iff there was a reference to resolve -- in which case
// this function has finalized `value`/`columns` (populated on success,
// cleared on error) -- and false iff there was nothing to resolve (the caller
// finalizes the plain value). Only call with an OK incoming status.
static Status MaybeResolveMemtableBlobValue(
const Slice& key, const BlobFetcher* blob_fetcher, PinnableSlice* value,
PinnableWideColumns* columns, bool* did_resolve, bool* is_blob_index,
bool* value_found = nullptr);
// Completes read-only/secondary memtable Get()/GetEntity() hits. Given the
// status from the memtable read, resolves blob-backed payloads when
// `resolve_blob_backed_memtable_value` is true, self-pins a plain value on
// success, and clears outputs on any error (never leaving a half-populated
// result). When the caller explicitly requested raw blob indices via
// `GetImplOptions::is_blob_index`, this helper leaves that payload untouched.
// `memtable_blob_fetcher` may be null when blob support is disabled for the
// column family. Returns the finalized status.
static Status PostprocessMemtableValueRead(
// `columns`. Unlike the direct-write helper above, this path only depends on
// a BlobFetcher and therefore works for read-only/secondary DBs.
static bool MaybeResolveMemtableBlobValue(const Slice& key,
const BlobFetcher* blob_fetcher,
PinnableSlice* value,
PinnableWideColumns* columns,
Status* s, bool* is_blob_index,
bool* value_found = nullptr);
// Completes read-only/secondary memtable Get()/GetEntity() hits by resolving
// blob-backed payloads when `resolve_blob_backed_memtable_value` is true,
// pinning plain values on success, and clearing outputs on error. When the
// caller explicitly requested raw blob indices via
// `GetImplOptions::is_blob_index`, this helper leaves that payload
// untouched. `memtable_blob_fetcher` may be null when blob support is
// disabled for the column family.
static void PostprocessMemtableValueRead(
const Slice& key, const std::string* timestamp,
bool resolve_blob_backed_memtable_value,
const BlobFetcher* memtable_blob_fetcher, PinnableSlice* value,
PinnableWideColumns* columns, Status memtable_read_status,
bool* is_blob_index, bool* value_found = nullptr);
PinnableWideColumns* columns, Status* s, bool* is_blob_index,
bool* value_found = nullptr);
template <typename IterType, typename ImplType,
typename ErrorIteratorFuncType>
@@ -3288,10 +3147,6 @@ class DBImpl : public DB
// DB mutex in compaction code paths.
std::atomic<int> compaction_aborted_ = 0;
// Number of AbortCompactions() callers waiting for a targeted compaction to
// finish. Protected by the DB mutex.
int per_cf_compaction_abort_waiters_ = 0;
// This condition variable is signaled on these conditions:
// * whenever bg_compaction_scheduled_ goes down to 0
// * if AnyManualCompaction, whenever a compaction finishes, even if it hasn't
@@ -3501,7 +3356,7 @@ class DBImpl : public DB
// cfd->imm()->IsFlushPending()
// A column family is inserted into compaction_queue_ when it satisfied
// condition cfd->NeedsCompaction()
// Column families in these collections are all Ref()-erenced.
// Column families in this list are all Ref()-erenced
// TODO(icanadi) Provide some kind of ReferencedColumnFamily class that will
// do RAII on ColumnFamilyData
// Column families are in this queue when they need to be flushed or
@@ -3516,23 +3371,9 @@ class DBImpl : public DB
// invariant(column family present in flush_queue_ <==>
// ColumnFamilyData::pending_flush_ == true)
std::deque<FlushRequest> flush_queue_;
// invariant((column family in compaction_queue_ or
// column family in parked_compaction_cfds_)
// <=> queued_for_compaction() == true)
//
// "Parked" means a column family whose compaction was aborted via
// AbortCompactions() while it was queued. When an aborted CF reaches the
// front of compaction_queue_, PickCompactionFromQueue() moves it to
// parked_compaction_cfds_ instead of scheduling it. The CF does not
// immediately lose its place -- only when it reaches the front of the
// queue is it parked. This preserves fairness for CFs behind it and
// avoids restoring the scheduler credit (which would cause a hot re-pick
// loop). On the final ResumeCompactions(), RestoreParkedCompaction()
// re-enqueues the CF (or releases its ref if it no longer needs
// compaction). Each parked CF carries exactly one Ref() from the
// original AddToCompactionQueue() call.
// invariant(column family present in compaction_queue_ <==>
// ColumnFamilyData::pending_compaction_ == true)
std::deque<ColumnFamilyData*> compaction_queue_;
std::unordered_set<ColumnFamilyData*> parked_compaction_cfds_;
// A map to store file numbers and filenames of the files to be purged
std::unordered_map<uint64_t, PurgeFileInfo> purge_files_;
@@ -3563,10 +3404,6 @@ class DBImpl : public DB
// stores the number of BOTTOM-priority compactions currently running
int num_running_bottom_compactions_ = 0;
// Number of compaction service jobs currently waiting in
// CompactionService::Wait(), counted per executed subcompaction.
std::atomic<int> num_running_remote_compactions_ = 0;
// number of background memtable flush jobs, submitted to the HIGH pool
int bg_flush_scheduled_ = 0;
@@ -3763,13 +3600,12 @@ class DBImpl : public DB
// Stop write token that is acquired when first LockWAL() is called.
// Destroyed when last UnlockWAL() is called. Controlled by DB mutex.
// See lock_wal_owner_thread_id_counts_
// See lock_wal_count_
std::unique_ptr<WriteControllerToken> lock_wal_write_token_;
// Thread IDs of valid LockWAL() owners and their recursive lock counts. Each
// owning thread must call UnlockWAL() the same number of times before writes
// can resume.
std::unordered_map<uint64_t, uint32_t> lock_wal_owner_thread_id_counts_;
// The number of LockWAL called without matching UnlockWAL call.
// See also lock_wal_write_token_
uint32_t lock_wal_count_ = 0;
};
class GetWithTimestampReadCallback : public ReadCallback {
@@ -3890,7 +3726,7 @@ inline Status DBImpl::FailIfTsMismatchCf(ColumnFamilyHandle* column_family,
inline Status DBImpl::FailIfTableFilterWithRangeConversion(
const ReadOptions& read_options,
const MutableCFOptions& mutable_cf_options) const {
if (HasTableFilter(read_options) &&
if (read_options.table_filter &&
mutable_cf_options.min_tombstones_for_range_conversion > 0) {
return Status::InvalidArgument(
"ReadOptions::table_filter is not supported when "
+40 -359
View File
@@ -6,7 +6,6 @@
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include <algorithm>
#include <cinttypes>
#include <deque>
#include <unordered_map>
@@ -32,7 +31,6 @@
#include "util/cast_util.h"
#include "util/coding.h"
#include "util/concurrent_task_limiter_impl.h"
#include "util/defer.h"
#include "util/udt_util.h"
namespace ROCKSDB_NAMESPACE {
@@ -360,34 +358,6 @@ Status DBImpl::FlushMemTableToOutputFile(
need_cancel = false;
}
// Reserve a pending flush-completion notification before the DB mutex can be
// released, so that a Flush(wait=true, listener_wait=true) caller cannot
// observe this flush as finished until NotifyOnFlushCompleted() below has
// run. flush_job.Run() removed the memtables from the immutable list (which
// is what unblocks the waiter) and the DB mutex has been held continuously
// since, so there is no window in which the waiter could see the flush
// committed with a zero count. Reserved only when a notification will
// actually fire (matches the NotifyOnFlushCompleted call below): flush
// committed successfully, not a mempurge, listeners are registered, and this
// job committed at least one flush result to report.
const bool reserved_flush_notification =
s.ok() && !switched_to_mempurge &&
!immutable_db_options_.listeners.empty() &&
!flush_job.GetCommittedFlushJobsInfo()->empty();
if (reserved_flush_notification) {
cfd->imm()->AddPendingFlushNotifications(1);
}
// Release the reservation on every exit path (RAII) so a future early return
// cannot leak the count and hang listener_wait waiters. The DB mutex is held
// throughout this function, including at scope exit, which
// SubPendingFlushNotifications() requires. Runs after
// NotifyOnFlushCompleted() below has returned.
Defer release_flush_notification([&] {
if (reserved_flush_notification) {
cfd->imm()->SubPendingFlushNotifications(1);
}
});
if (cfd->blob_partition_manager() != nullptr &&
prepared_blob_generations > 0) {
auto unconsumed_additions = flush_job.TakeExternalBlobFileAdditions();
@@ -930,42 +900,6 @@ Status DBImpl::AtomicFlushMemTablesToOutputFiles(
directories_.GetDbDir(), log_buffer);
}
// Reserve a pending flush-completion notification for every CF that the
// NotifyOnFlushCompleted loop below will service, while the DB mutex is still
// held continuously since InstallMemtableAtomicFlushResults removed the
// memtables. This closes the window where a
// Flush(wait=true, listener_wait=true) waiter could observe an atomic flush
// as finished before a later CF's OnFlushCompleted has run, since the notify
// loop releases and re-acquires the mutex between CFs. The reservations are
// released by a matching pass after the notify loop.
autovector<uint8_t> reserved_flush_notification;
reserved_flush_notification.reserve(num_cfs);
{
const bool has_listeners = !immutable_db_options_.listeners.empty();
for (int i = 0; i != num_cfs; ++i) {
const bool reserve = s.ok() && has_listeners &&
!switched_to_mempurge[i] && !cfds[i]->IsDropped() &&
!jobs[i]->GetCommittedFlushJobsInfo()->empty();
if (reserve) {
cfds[i]->imm()->AddPendingFlushNotifications(1);
}
reserved_flush_notification.push_back(reserve ? 1 : 0);
}
}
// Release the reservations on every exit path (RAII) so a future early return
// cannot leak the count and hang listener_wait waiters. Done independently of
// the notify loop's skips so the count stays balanced even if a CF was
// dropped after it was reserved. The DB mutex is held throughout this
// function, including at scope exit, which SubPendingFlushNotifications()
// requires.
Defer release_flush_notifications([&] {
for (int i = 0; i != num_cfs; ++i) {
if (reserved_flush_notification[i]) {
cfds[i]->imm()->SubPendingFlushNotifications(1);
}
}
});
if (!s.ok()) {
// If the atomic flush's combined MANIFEST write failed, the output files
// are cached in the table cache (added by BuildTable during FlushJob::Run)
@@ -1196,15 +1130,11 @@ Status DBImpl::CompactRange(const CompactRangeOptions& options,
ColumnFamilyHandle* column_family,
const Slice* begin_without_ts,
const Slice* end_without_ts) {
auto* cfd =
static_cast_with_check<ColumnFamilyHandleImpl>(column_family)->cfd();
assert(cfd);
if (manual_compaction_paused_.load(std::memory_order_acquire) > 0) {
return Status::Incomplete(Status::SubCode::kManualCompactionPaused);
}
if (IsCompactionAborted(cfd)) {
if (compaction_aborted_.load(std::memory_order_acquire) > 0) {
return Status::Incomplete(Status::SubCode::kCompactionAborted);
}
@@ -1615,21 +1545,6 @@ Status DBImpl::CompactFiles(const CompactionOptions& compact_options,
static_cast_with_check<ColumnFamilyHandleImpl>(column_family)->cfd();
assert(cfd);
{
InstrumentedMutexLock l(&mutex_);
BeginInFlightCompaction(cfd);
}
Defer end_in_flight_compaction([&]() {
InstrumentedMutexLock l(&mutex_);
// The caller holds a live handle to this CF, so this can never be the final
// unref (the return can only be true when the last reference is dropped).
[[maybe_unused]] const bool cfd_deleted = EndInFlightCompaction(cfd);
assert(!cfd_deleted);
if (per_cf_compaction_abort_waiters_ > 0) {
bg_cv_.SignalAll();
}
});
Status s;
JobContext job_context(next_job_id_.fetch_add(1), true);
LogBuffer log_buffer(InfoLogLevel::INFO_LEVEL,
@@ -1708,16 +1623,16 @@ void DBImpl::PrepareTrivialMoveEdit(Compaction& c, LogBuffer* log_buffer,
for (size_t i = 0; i < c.num_input_files(l); i++) {
FileMetaData* f = c.input(l, i);
c.edit()->DeleteFile(c.level(l), f->fd.GetNumber());
c.edit()->AddFile(
c.output_level(), f->fd.GetNumber(), f->fd.GetPathId(),
f->fd.GetFileSize(), f->smallest, f->largest, f->fd.smallest_seqno,
f->fd.largest_seqno, f->marked_for_compaction, f->temperature,
f->oldest_blob_file_number, f->oldest_ancester_time,
f->file_creation_time, f->epoch_number, f->file_checksum,
f->file_checksum_func_name, f->unique_id,
f->compensated_range_deletion_size, f->tail_size,
f->user_defined_timestamps_persisted, f->min_timestamp,
f->max_timestamp, f->file_open_metadata);
c.edit()->AddFile(c.output_level(), f->fd.GetNumber(), f->fd.GetPathId(),
f->fd.GetFileSize(), f->smallest, f->largest,
f->fd.smallest_seqno, f->fd.largest_seqno,
f->marked_for_compaction, f->temperature,
f->oldest_blob_file_number, f->oldest_ancester_time,
f->file_creation_time, f->epoch_number,
f->file_checksum, f->file_checksum_func_name,
f->unique_id, f->compensated_range_deletion_size,
f->tail_size, f->user_defined_timestamps_persisted,
f->min_timestamp, f->max_timestamp);
moved_bytes += static_cast<size_t>(c.input(l, i)->fd.GetFileSize());
ROCKS_LOG_BUFFER(
log_buffer, "[%s] Moved #%" PRIu64 " to level-%d %" PRIu64 " bytes\n",
@@ -1758,7 +1673,8 @@ Status DBImpl::CompactFilesImpl(
return Status::ShutdownInProgress();
}
if (IsCompactionAborted(cfd)) {
// triggered by AbortAllCompactions
if (compaction_aborted_.load(std::memory_order_acquire) > 0) {
return Status::Incomplete(Status::SubCode::kCompactionAborted);
}
@@ -1885,7 +1801,7 @@ Status DBImpl::CompactFilesImpl(
c.reset();
bg_compaction_scheduled_--;
if (bg_compaction_scheduled_ == 0 || per_cf_compaction_abort_waiters_ > 0) {
if (bg_compaction_scheduled_ == 0) {
bg_cv_.SignalAll();
}
MaybeScheduleFlushOrCompaction();
@@ -1915,7 +1831,7 @@ Status DBImpl::CompactFilesImpl(
kManualCompactionCanceledFalse_, compaction_aborted_, db_id_,
db_session_id_, c->column_family_data()->GetFullHistoryTsLow(),
c->trim_ts(), &blob_callback_, &bg_compaction_scheduled_,
&bg_bottom_compaction_scheduled_, &num_running_remote_compactions_);
&bg_bottom_compaction_scheduled_);
// Creating a compaction influences the compaction score because the score
// takes running compactions into account (by skipping files that are already
@@ -2020,7 +1936,7 @@ Status DBImpl::CompactFilesImpl(
c.reset();
bg_compaction_scheduled_--;
if (bg_compaction_scheduled_ == 0 || per_cf_compaction_abort_waiters_ > 0) {
if (bg_compaction_scheduled_ == 0) {
bg_cv_.SignalAll();
}
MaybeScheduleFlushOrCompaction();
@@ -2293,7 +2209,7 @@ Status DBImpl::ReFitLevel(ColumnFamilyData* cfd, int level, int target_level) {
f->file_checksum, f->file_checksum_func_name, f->unique_id,
f->compensated_range_deletion_size, f->tail_size,
f->user_defined_timestamps_persisted, f->min_timestamp,
f->max_timestamp, f->file_open_metadata);
f->max_timestamp);
}
ROCKS_LOG_DEBUG(immutable_db_options_.info_log,
"[%s] Apply version edit:\n%s", cfd->GetName().c_str(),
@@ -2490,10 +2406,12 @@ Status DBImpl::RunManualCompaction(
return manual.status;
}
if (IsCompactionAborted(cfd)) {
ROCKS_LOG_INFO(immutable_db_options_.info_log,
"[%s] RunManualCompaction: aborting compaction",
cfd->GetName().c_str());
if (compaction_aborted_.load(std::memory_order_acquire) > 0) {
// All compactions are being aborted. Return immediately.
int counter = compaction_aborted_.load(std::memory_order_acquire);
ROCKS_LOG_INFO(
immutable_db_options_.info_log,
"RunManualCompaction: Aborting due to compaction_aborted_=%d", counter);
manual.status = Status::Incomplete(Status::SubCode::kCompactionAborted);
manual.done = true;
return manual.status;
@@ -2523,7 +2441,7 @@ Status DBImpl::RunManualCompaction(
// and `CompactRangeOptions::canceled` might not work well together.
while (bg_bottom_compaction_scheduled_ > 0 ||
bg_compaction_scheduled_ > 0) {
if (IsCompactionAborted(cfd)) {
if (compaction_aborted_.load(std::memory_order_acquire) > 0) {
// Pretend the error came from compaction so the below cleanup/error
// handling code can process it.
manual.done = true;
@@ -2559,11 +2477,6 @@ Status DBImpl::RunManualCompaction(
// true.
while (!manual.done) {
assert(HasPendingManualCompaction());
if (IsCompactionAborted(cfd) && !scheduled && !manual.in_progress) {
manual.done = true;
manual.status = Status::Incomplete(Status::SubCode::kCompactionAborted);
break;
}
manual_conflict = false;
Compaction* compaction = nullptr;
if (ShouldntRunManualCompaction(&manual) || (manual.in_progress == true) ||
@@ -2653,7 +2566,7 @@ Status DBImpl::RunManualCompaction(
if (!scheduled) {
// There is nothing scheduled to wait on, so any cancellation can end the
// manual now.
if (IsCompactionAborted(cfd)) {
if (compaction_aborted_.load(std::memory_order_acquire) > 0) {
// Stop waiting since it was canceled. Pretend the error came from
// compaction so the below cleanup/error handling code can process it.
manual.done = true;
@@ -2736,13 +2649,6 @@ Status DBImpl::FlushMemTable(ColumnFamilyData* cfd,
"Please try again later after writes are resumed";
return Status::TryAgain(oss.str());
}
if (flush_options.wait) {
InstrumentedMutexLock lock(&mutex_);
if (lock_wal_owner_thread_id_counts_.count(env_->GetThreadID()) > 0) {
return Status::Aborted(
"Likely deadlock as the same thread called LockWAL()");
}
}
Status s;
if (!flush_options.allow_write_stall) {
bool flush_needed = true;
@@ -2881,7 +2787,7 @@ Status DBImpl::FlushMemTable(ColumnFamilyData* cfd,
s = WaitForFlushMemTables(
cfds, flush_memtable_ids,
flush_reason == FlushReason::kErrorRecovery /* resuming_from_bg_err */,
flush_reason, flush_options.listener_wait);
flush_reason);
InstrumentedMutexLock lock_guard(&mutex_);
for (auto* tmp_cfd : cfds) {
tmp_cfd->UnrefAndTryDelete();
@@ -2901,13 +2807,6 @@ Status DBImpl::AtomicFlushMemTables(
"Please try again later after writes are resumed";
return Status::TryAgain(oss.str());
}
if (flush_options.wait) {
InstrumentedMutexLock lock(&mutex_);
if (lock_wal_owner_thread_id_counts_.count(env_->GetThreadID()) > 0) {
return Status::Aborted(
"Likely deadlock as the same thread called LockWAL()");
}
}
Status s;
autovector<ColumnFamilyData*> candidate_cfds;
if (provided_candidate_cfds.empty()) {
@@ -3036,7 +2935,7 @@ Status DBImpl::AtomicFlushMemTables(
s = WaitForFlushMemTables(
cfds, flush_memtable_ids,
flush_reason == FlushReason::kErrorRecovery /* resuming_from_bg_err */,
flush_reason, flush_options.listener_wait);
flush_reason);
InstrumentedMutexLock lock_guard(&mutex_);
for (auto* cfd : cfds) {
cfd->UnrefAndTryDelete();
@@ -3205,8 +3104,7 @@ Status DBImpl::WaitUntilFlushWouldNotStallWrites(ColumnFamilyData* cfd,
Status DBImpl::WaitForFlushMemTables(
const autovector<ColumnFamilyData*>& cfds,
const autovector<const uint64_t*>& flush_memtable_ids,
bool resuming_from_bg_err, std::optional<FlushReason> flush_reason,
bool wait_for_listener_notifications) {
bool resuming_from_bg_err, std::optional<FlushReason> flush_reason) {
int num = static_cast<int>(cfds.size());
// Wait until the compaction completes
InstrumentedMutexLock l(&mutex_);
@@ -3251,13 +3149,7 @@ Status DBImpl::WaitForFlushMemTables(
flush_reason.value() != FlushReason::kExternalFileIngestion ||
cfds[i]->GetSuperVersion()->imm->GetID() ==
cfds[i]->imm()->current()->GetID()) {
// When the caller requested it, also wait for the flush-completion
// listener callbacks for this CF to finish before counting it as
// finished (see FlushOptions::listener_wait).
if (!wait_for_listener_notifications ||
cfds[i]->imm()->NumPendingFlushNotifications() == 0) {
++num_finished;
}
++num_finished;
}
}
}
@@ -3321,52 +3213,6 @@ void DBImpl::EnableManualCompaction() {
manual_compaction_paused_.fetch_sub(1, std::memory_order_release);
}
bool DBImpl::IsCompactionAborted(ColumnFamilyData* cfd) const {
return compaction_aborted_.load(std::memory_order_acquire) > 0 ||
cfd->compaction_aborted() > 0;
}
bool DBImpl::MustWaitForCompaction(ColumnFamilyData* cfd) {
mutex_.AssertHeld();
// num_in_flight_compactions_ and the picker's compactions_in_progress_ set
// cover DIFFERENT windows and neither subsumes the other:
// - the counter covers a picked Compaction from pick through the end of
// BackgroundCompaction (including NotifyOnCompactionCompleted), which the
// picker set does not -- it is cleared during Install's manifest write.
// - the picker set covers the bottom-priority handoff: when a LOW thread
// forwards a bottom compaction, its EndInFlightCompaction() dips the
// counter to 0 while the compaction is still registered and queued for the
// BOTTOM pool, and the picker set keeps AbortCompactions() waiting across
// that gap. (The re-registered "intended" bottom compaction inherits the
// original compaction_reason(), so it is not filtered out below.)
if (cfd->num_in_flight_compactions(&mutex_) > 0) {
return true;
}
for (const auto* compaction :
*cfd->compaction_picker()->compactions_in_progress()) {
const auto reason = compaction->compaction_reason();
// These are picker reservations for conflict tracking, not CompactionJobs,
// so they never observe the abort atomic in ProcessKeyValue().
if (reason != CompactionReason::kExternalSstIngestion &&
reason != CompactionReason::kRefitLevel) {
return true;
}
}
return false;
}
void DBImpl::BeginInFlightCompaction(ColumnFamilyData* cfd) {
mutex_.AssertHeld();
cfd->Ref();
cfd->inc_num_in_flight_compactions(&mutex_);
}
bool DBImpl::EndInFlightCompaction(ColumnFamilyData* cfd) {
mutex_.AssertHeld();
cfd->dec_num_in_flight_compactions(&mutex_);
return cfd->UnrefAndTryDelete();
}
void DBImpl::AbortAllCompactions() {
InstrumentedMutexLock l(&mutex_);
@@ -3393,83 +3239,6 @@ void DBImpl::AbortAllCompactions() {
}
}
void DBImpl::AbortCompactions(ColumnFamilyHandle* column_family) {
InstrumentedMutexLock l(&mutex_);
if (shutting_down_.load(std::memory_order_acquire)) {
return;
}
assert(column_family != nullptr);
auto* cfh = static_cast_with_check<ColumnFamilyHandleImpl>(column_family);
assert(cfh->db() == this);
auto* cfd = cfh->cfd();
assert(cfd != nullptr);
cfd->inc_compaction_aborted(&mutex_);
TEST_SYNC_POINT("DBImpl::AbortCompactions:FlagSet");
for (const auto* manual_compaction : manual_compaction_dequeue_) {
if (manual_compaction->cfd == cfd) {
manual_compaction->canceled.store(true, std::memory_order_release);
}
}
bg_cv_.SignalAll();
// Wait for this CF's running compactions to finish or abort. If the DB
// is shutting down, return early -- the counter stays incremented but the
// CFD and DB will be torn down anyway. Callers that use SCOPE_EXIT for
// the matching ResumeCompactions() are safe: the resume is a no-op on a
// DB that is already closed.
++per_cf_compaction_abort_waiters_;
while (!shutting_down_.load(std::memory_order_acquire) &&
(MustWaitForCompaction(cfd) || HasPendingManualCompaction(cfd))) {
TEST_SYNC_POINT("DBImpl::AbortCompactions:Waiting");
bg_cv_.Wait();
}
--per_cf_compaction_abort_waiters_;
TEST_SYNC_POINT("DBImpl::AbortCompactions:Complete");
}
void DBImpl::ResumeCompactions(ColumnFamilyHandle* column_family) {
InstrumentedMutexLock l(&mutex_);
if (shutting_down_.load(std::memory_order_acquire)) {
return;
}
assert(column_family != nullptr);
auto* cfh = static_cast_with_check<ColumnFamilyHandleImpl>(column_family);
assert(cfh->db() == this);
auto* cfd = cfh->cfd();
assert(cfd != nullptr);
const int before = cfd->compaction_aborted();
if (before <= 0) {
ROCKS_LOG_WARN(immutable_db_options_.info_log,
"ResumeCompactions called without prior AbortCompactions "
"for column family %s (counter=%d)",
cfd->GetName().c_str(), before);
return;
}
const int current = cfd->dec_compaction_aborted(&mutex_);
ROCKS_LOG_INFO(immutable_db_options_.info_log,
"[%s] ResumeCompactions: counter %d -> %d",
cfd->GetName().c_str(), before, current);
if (current == 0) {
// TODO: Aborting an automatic compaction after PickCompaction()
// releases its inputs without recomputing the compaction score, so this
// EnqueuePendingCompaction() can observe a stale sub-trigger score and
// queue nothing, leaving the CF idle until the next flush. Pre-existing
// (ResumeAllCompactions() has the same gap); fix separately for both APIs
// by recomputing the score on the abort path.
if (!RestoreParkedCompaction(cfd) && !cfd->IsDropped()) {
EnqueuePendingCompaction(cfd);
}
MaybeScheduleFlushOrCompaction();
bg_cv_.SignalAll();
}
}
void DBImpl::ResumeAllCompactions() {
InstrumentedMutexLock l(&mutex_);
int before = compaction_aborted_.load(std::memory_order_acquire);
@@ -3495,7 +3264,6 @@ void DBImpl::ResumeAllCompactions() {
// If this is the last resume call (abort counter back to 0), schedule
// compactions that may have been waiting
if (current == 0) {
// The stale-score TODO in ResumeCompactions() also applies here.
MaybeScheduleFlushOrCompaction();
}
}
@@ -3722,27 +3490,6 @@ void DBImpl::AddToCompactionQueue(ColumnFamilyData* cfd) {
++unscheduled_compactions_;
}
bool DBImpl::RestoreParkedCompaction(ColumnFamilyData* cfd) {
mutex_.AssertHeld();
auto it = parked_compaction_cfds_.find(cfd);
if (it == parked_compaction_cfds_.end()) {
return false;
}
parked_compaction_cfds_.erase(it);
assert(cfd->queued_for_compaction());
if (!cfd->IsDropped() && cfd->NeedsCompaction()) {
TEST_SYNC_POINT_CALLBACK("DBImpl::RestoreParkedCompaction:cfd",
static_cast<void*>(cfd));
compaction_queue_.push_back(cfd);
++unscheduled_compactions_;
} else {
cfd->set_queued_for_compaction(false);
cfd->UnrefAndTryDelete();
}
return true;
}
ColumnFamilyData* DBImpl::PopFirstFromCompactionQueue() {
assert(!compaction_queue_.empty());
auto cfd = *compaction_queue_.begin();
@@ -3770,37 +3517,22 @@ DBImpl::FlushRequest DBImpl::PopFirstFromFlushQueue() {
return flush_req;
}
DBImpl::CompactionQueuePickResult DBImpl::PickCompactionFromQueue(
ColumnFamilyData* DBImpl::PickCompactionFromQueue(
std::unique_ptr<TaskLimiterToken>* token, LogBuffer* log_buffer) {
assert(!compaction_queue_.empty());
assert(*token == nullptr);
autovector<ColumnFamilyData*> throttled_candidates;
CompactionQueuePickResult result = CompactionQueueThrottled{};
ColumnFamilyData* cfd = nullptr;
while (!compaction_queue_.empty()) {
auto first_cfd = *compaction_queue_.begin();
compaction_queue_.pop_front();
assert(first_cfd->queued_for_compaction());
if (first_cfd->IsDropped()) {
first_cfd->set_queued_for_compaction(false);
result = CompactionQueuePicked{first_cfd};
break;
}
if (first_cfd->compaction_aborted() > 0) {
// Parking consumes this worker's credit. Remaining queue entries retain
// their own credits and are scheduled when this worker returns.
[[maybe_unused]] const bool inserted =
parked_compaction_cfds_.insert(first_cfd).second;
assert(inserted);
TEST_SYNC_POINT("DBImpl::PickCompactionFromQueue:Parked");
result = CompactionQueueParked{};
break;
}
if (!RequestCompactionToken(first_cfd, false, token, log_buffer)) {
throttled_candidates.push_back(first_cfd);
continue;
}
first_cfd->set_queued_for_compaction(false);
result = CompactionQueuePicked{first_cfd};
cfd = first_cfd;
cfd->set_queued_for_compaction(false);
break;
}
// Add throttled compaction candidates back to queue in the original order.
@@ -3808,7 +3540,7 @@ DBImpl::CompactionQueuePickResult DBImpl::PickCompactionFromQueue(
iter != throttled_candidates.rend(); ++iter) {
compaction_queue_.push_front(*iter);
}
return result;
return cfd;
}
bool DBImpl::EnqueuePendingFlush(const FlushRequest& flush_req) {
@@ -3855,21 +3587,13 @@ bool DBImpl::EnqueuePendingFlush(const FlushRequest& flush_req) {
void DBImpl::EnqueuePendingCompaction(ColumnFamilyData* cfd) {
mutex_.AssertHeld();
if (reject_new_background_jobs_ || cfd->IsDropped()) {
if (reject_new_background_jobs_) {
return;
}
if (!cfd->queued_for_compaction() && cfd->NeedsCompaction()) {
TEST_SYNC_POINT_CALLBACK("EnqueuePendingCompaction::cfd",
static_cast<void*>(cfd));
if (cfd->compaction_aborted() > 0) {
cfd->Ref();
cfd->set_queued_for_compaction(true);
[[maybe_unused]] const bool inserted =
parked_compaction_cfds_.insert(cfd).second;
assert(inserted);
} else {
AddToCompactionQueue(cfd);
}
AddToCompactionQueue(cfd);
}
}
@@ -4329,7 +4053,7 @@ void DBImpl::BackgroundCallCompaction(PrepickedCompaction* prepicked_compaction,
prepicked_compaction->task_token.reset();
}
if (made_progress || per_cf_compaction_abort_waiters_ > 0 ||
if (made_progress ||
(bg_compaction_scheduled_ == 0 &&
bg_bottom_compaction_scheduled_ == 0) ||
HasPendingManualCompaction() || unscheduled_compactions_ == 0) {
@@ -4371,29 +4095,7 @@ Status DBImpl::BackgroundCompaction(bool* made_progress,
prepicked_compaction->compaction != nullptr) {
c.reset(prepicked_compaction->compaction);
}
// Track this CF as having an in-flight compaction for the duration of this
// BackgroundCompaction (which covers NotifyOnCompactionCompleted). The Defer
// ends tracking on every return path. BeginInFlightCompaction()'s Ref keeps a
// dropped CF alive across any c.reset() until then; if this ends the CF's
// last reference, the FindObsoleteFiles() pass in BackgroundCallCompaction
// cleans up its files.
ColumnFamilyData* in_flight_cfd = nullptr;
Defer end_in_flight_compaction([&]() {
if (in_flight_cfd != nullptr) {
EndInFlightCompaction(in_flight_cfd);
}
});
if (c != nullptr) {
in_flight_cfd = c->column_family_data();
BeginInFlightCompaction(in_flight_cfd);
}
bool is_prepicked = is_manual || c;
ColumnFamilyData* prepicked_cfd = nullptr;
if (c) {
prepicked_cfd = c->column_family_data();
} else if (manual_compaction != nullptr) {
prepicked_cfd = manual_compaction->cfd;
}
// (manual_compaction->in_progress == false);
bool trivial_move_disallowed =
@@ -4421,9 +4123,6 @@ Status DBImpl::BackgroundCompaction(bool* made_progress,
// can schedule the still-queued work.
unscheduled_compactions_++;
}
} else if (prepicked_cfd != nullptr &&
prepicked_cfd->compaction_aborted() > 0) {
status = Status::Incomplete(Status::SubCode::kCompactionAborted);
} else if (is_manual &&
manual_compaction->canceled.load(std::memory_order_acquire)) {
status = Status::Incomplete(Status::SubCode::kManualCompactionPaused);
@@ -4528,18 +4227,13 @@ Status DBImpl::BackgroundCompaction(bool* made_progress,
ColumnFamilyData* cfd = nullptr;
if (!need_repick) {
auto pick_result = PickCompactionFromQueue(&task_token, log_buffer);
if (std::holds_alternative<CompactionQueueThrottled>(pick_result)) {
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 (std::holds_alternative<CompactionQueueParked>(pick_result)) {
return Status::Incomplete(Status::SubCode::kCompactionAborted);
}
cfd = std::get<CompactionQueuePicked>(pick_result).cfd;
assert(cfd != 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
@@ -4580,10 +4274,6 @@ Status DBImpl::BackgroundCompaction(bool* made_progress,
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 (c != nullptr && in_flight_cfd == nullptr) {
in_flight_cfd = cfd;
BeginInFlightCompaction(in_flight_cfd);
}
if (thread_pri == Env::Priority::LOW) {
TEST_SYNC_POINT("DBImpl::BackgroundCompaction():AfterPickCompaction");
} else if (thread_pri == Env::Priority::BOTTOM) {
@@ -5064,7 +4754,7 @@ Status DBImpl::BackgroundCompaction(bool* made_progress,
compaction_aborted_, db_id_, db_session_id_,
c->column_family_data()->GetFullHistoryTsLow(), c->trim_ts(),
&blob_callback_, &bg_compaction_scheduled_,
&bg_bottom_compaction_scheduled_, &num_running_remote_compactions_);
&bg_bottom_compaction_scheduled_);
compaction_job.Prepare(std::nullopt /*subcompact to be computed*/);
std::unique_ptr<std::list<uint64_t>::iterator> min_options_file_number_elem;
@@ -5306,14 +4996,6 @@ bool DBImpl::HasPendingManualCompaction() {
return (!manual_compaction_dequeue_.empty());
}
bool DBImpl::HasPendingManualCompaction(ColumnFamilyData* cfd) {
return std::any_of(manual_compaction_dequeue_.begin(),
manual_compaction_dequeue_.end(),
[cfd](const ManualCompactionState* manual) {
return manual->cfd == cfd;
});
}
void DBImpl::AddManualCompaction(DBImpl::ManualCompactionState* m) {
assert(manual_compaction_paused_ == 0);
manual_compaction_dequeue_.push_back(m);
@@ -5664,7 +5346,6 @@ Status DBImpl::WaitForCompact(
}
if ((bg_bottom_compaction_scheduled_ || bg_compaction_scheduled_ ||
bg_flush_scheduled_ || unscheduled_compactions_ ||
!parked_compaction_cfds_.empty() ||
(wait_for_compact_options.wait_for_purge && bg_purge_scheduled_) ||
unscheduled_flushes_ || error_handler_.IsRecoveryInProgress()) &&
(error_handler_.GetBGError().ok())) {
+1 -17
View File
@@ -37,7 +37,7 @@ Status DBImpl::TEST_SwitchWAL() {
Status DBImpl::TEST_ResumeImpl(DBRecoverContext context) {
InstrumentedMutexLock l(&mutex_);
return ResumeImpl(context, Env::IOActivity::kFlush);
return ResumeImpl(context);
}
uint64_t DBImpl::TEST_MaxNextLevelOverlappingBytes(
@@ -164,22 +164,6 @@ Status DBImpl::TEST_FlushMemTable(ColumnFamilyData* cfd,
return FlushMemTable(cfd, flush_opts, FlushReason::kTest);
}
Status DBImpl::TEST_FlushMemTableWithListenerWait(bool allow_write_stall,
ColumnFamilyHandle* cfh) {
FlushOptions fo;
fo.wait = true;
fo.listener_wait = true;
fo.allow_write_stall = allow_write_stall;
ColumnFamilyData* cfd;
if (cfh == nullptr) {
cfd = default_cf_handle_->cfd();
} else {
auto cfhi = static_cast_with_check<ColumnFamilyHandleImpl>(cfh);
cfd = cfhi->cfd();
}
return FlushMemTable(cfd, fo, FlushReason::kTest);
}
Status DBImpl::TEST_AtomicFlushMemTables(
const autovector<ColumnFamilyData*>& provided_candidate_cfds,
const FlushOptions& flush_opts) {
+1 -1
View File
@@ -145,7 +145,7 @@ Status DBImpl::PromoteL0(ColumnFamilyHandle* column_family, int target_level) {
f->file_checksum_func_name, f->unique_id,
f->compensated_range_deletion_size, f->tail_size,
f->user_defined_timestamps_persisted, f->min_timestamp,
f->max_timestamp, f->file_open_metadata);
f->max_timestamp);
}
status = versions_->LogAndApply(cfd, read_options, write_options, &edit,
-2
View File
@@ -55,8 +55,6 @@ Env::IOActivity GetCurrentThreadIOActivityForMetadataRead() {
case ThreadStatus::OperationType::
OP_GET_FILE_CHECKSUMS_FROM_CURRENT_MANIFEST:
return Env::IOActivity::kGetFileChecksumsFromCurrentManifest;
case ThreadStatus::OperationType::OP_LAZY_RESOLVE:
return Env::IOActivity::kLazyResolve;
default:
return Env::IOActivity::kUnknown;
}
+6 -26
View File
@@ -243,11 +243,6 @@ Status DBImpl::ValidateOptions(
}
Status DBImpl::ValidateOptions(const DBOptions& db_options) {
if (db_options.read_io_executor_threads <= 0) {
return Status::InvalidArgument(
"read_io_executor_threads must be greater than zero");
}
if (db_options.db_paths.size() > 4) {
return Status::NotSupported(
"More than four DB paths are not supported yet. ");
@@ -688,8 +683,7 @@ Status DBImpl::Recover(
f->file_checksum, f->file_checksum_func_name,
f->unique_id, f->compensated_range_deletion_size,
f->tail_size, f->user_defined_timestamps_persisted,
f->min_timestamp, f->max_timestamp,
f->file_open_metadata);
f->min_timestamp, f->max_timestamp);
ROCKS_LOG_WARN(immutable_db_options_.info_log,
"[%s] Moving #%" PRIu64
" from from_level-%d to from_level-%d %" PRIu64
@@ -1947,8 +1941,10 @@ Status DBImpl::MaybeFlushFinalMemtableOrRestoreActiveLogFiles(
const uint64_t new_min_log = max_wal_number + 1;
VersionEdit wal_deletion;
bool emit_wal_deletion = false;
if (immutable_db_options_.track_and_verify_wals_in_manifest &&
new_min_log > versions_->GetWalSet().GetMinWalNumberToKeep()) {
if (immutable_db_options_.track_and_verify_wals_in_manifest) {
// Determining whether DeleteWalsBefore actually shrinks WalSet
// membership requires WalSet state outside this site, so emit
// unconditionally (pre-existing behavior).
wal_deletion.DeleteWalsBefore(new_min_log);
emit_wal_deletion = true;
}
@@ -2176,7 +2172,7 @@ Status DBImpl::WriteLevel0TableForRecovery(int job_id, ColumnFamilyData* cfd,
false /* is_bottommost */, TableFileCreationReason::kRecovery,
0 /* oldest_key_time */, 0 /* file_creation_time */, db_id_,
db_session_id_, 0 /* target_file_size */, meta.fd.GetNumber(),
kMaxSequenceNumber, dbname_ /* db_name */);
kMaxSequenceNumber);
Version* version = cfd->current();
version->Ref();
TableProperties temp_table_proerties;
@@ -2877,16 +2873,11 @@ Status DBImpl::Open(const DBOptions& db_options, const std::string& dbname,
}
TEST_SYNC_POINT("DBImpl::Open:Opened");
Status persist_options_status;
bool cleanup_obsolete_options_files = false;
if (s.ok()) {
// Persist RocksDB Options before scheduling the compaction.
// The WriteOptionsFile() will release and lock the mutex internally.
persist_options_status =
impl->WriteOptionsFile(write_options, true /*db_mutex_already_held*/);
cleanup_obsolete_options_files =
impl->immutable_db_options_.avoid_unnecessary_blocking_io &&
impl->immutable_db_options_.compaction_service == nullptr &&
!impl->disable_delete_obsolete_files_;
impl->opened_successfully_ = true;
} else {
persist_options_status.PermitUncheckedError();
@@ -2976,17 +2967,6 @@ Status DBImpl::Open(const DBOptions& db_options, const std::string& dbname,
s = impl->RegisterRecordSeqnoTimeWorker();
}
impl->options_mutex_.Unlock();
if (cleanup_obsolete_options_files) {
Status obsolete_options_status =
impl->DeleteObsoleteOptionsFiles(/*schedule_only=*/s.ok());
if (!obsolete_options_status.ok()) {
ROCKS_LOG_WARN(impl->immutable_db_options_.info_log,
"Unable to %s obsolete OPTIONS files%s: %s",
s.ok() ? "schedule deletion of" : "delete",
s.ok() ? "" : " after DB open failure",
obsolete_options_status.ToString().c_str());
}
}
if (s.ok()) {
*dbptr = std::move(impl);
} else {
+141 -13
View File
@@ -30,6 +30,147 @@ DBImplReadOnly::DBImplReadOnly(const DBOptions& db_options,
DBImplReadOnly::~DBImplReadOnly() = default;
// Implementations of the DB interface
Status DBImplReadOnly::GetImpl(const ReadOptions& read_options,
const Slice& key,
GetImplOptions& get_impl_options) {
assert(get_impl_options.value != nullptr ||
get_impl_options.columns != nullptr ||
get_impl_options.merge_operands != nullptr);
assert(get_impl_options.column_family);
Status s;
if (read_options.timestamp) {
s = FailIfTsMismatchCf(get_impl_options.column_family,
*(read_options.timestamp));
if (!s.ok()) {
return s;
}
} else {
s = FailIfCfHasTs(get_impl_options.column_family);
if (!s.ok()) {
return s;
}
}
// Clear the timestamps for returning results so that we can distinguish
// between tombstone or key that has never been written
if (get_impl_options.timestamp) {
get_impl_options.timestamp->clear();
}
PERF_CPU_TIMER_GUARD(get_cpu_nanos, immutable_db_options_.clock);
StopWatch sw(immutable_db_options_.clock, stats_, DB_GET);
PERF_TIMER_GUARD(get_snapshot_time);
const Comparator* ucmp = get_impl_options.column_family->GetComparator();
assert(ucmp);
SequenceNumber snapshot = versions_->LastSequence();
GetWithTimestampReadCallback read_cb(snapshot);
auto cfh = static_cast_with_check<ColumnFamilyHandleImpl>(
get_impl_options.column_family);
auto cfd = cfh->cfd();
bool is_blob_index = false;
bool* is_blob_ptr = get_impl_options.is_blob_index;
std::string timestamp_storage;
std::string* ts = nullptr;
if (ucmp->timestamp_size() > 0) {
ts = get_impl_options.timestamp != nullptr
? get_impl_options.timestamp
: (get_impl_options.get_value ? &timestamp_storage : nullptr);
}
if (!is_blob_ptr && get_impl_options.get_value) {
is_blob_ptr = &is_blob_index;
}
const bool resolve_blob_backed_memtable_value =
get_impl_options.get_value && (is_blob_ptr == &is_blob_index);
if (tracer_) {
InstrumentedMutexLock lock(&trace_mutex_);
if (tracer_) {
tracer_->Get(get_impl_options.column_family, key);
}
}
// In read-only mode Get(), no super version operation is needed (i.e.
// GetAndRefSuperVersion and ReturnAndCleanupSuperVersion)
SuperVersion* super_version = cfd->GetSuperVersion();
if (read_options.timestamp && read_options.timestamp->size() > 0) {
s = FailIfReadCollapsedHistory(cfd, super_version,
*(read_options.timestamp));
if (!s.ok()) {
return s;
}
}
// Prepare to store a list of merge operations if merge occurs.
MergeContext merge_context;
// TODO - Large Result Optimization for Read Only DB
// (https://github.com/facebook/rocksdb/pull/10458)
SequenceNumber max_covering_tombstone_seq = 0;
LookupKey lkey(key, snapshot, read_options.timestamp);
PERF_TIMER_STOP(get_snapshot_time);
std::optional<BlobFetcher> memtable_blob_fetcher;
if (cfd->ioptions().enable_blob_direct_write ||
cfd->GetLatestMutableCFOptions().enable_blob_files) {
// Recovered memtables can still contain older blob references after
// mutable blob-file settings change, so keep blob resolution available
// whenever either blob knob indicates it may be needed.
memtable_blob_fetcher.emplace(super_version->current, read_options,
cfd->blob_file_cache(),
/*allow_write_path_fallback=*/true);
}
const BlobFetcher* memtable_blob_fetcher_ptr =
memtable_blob_fetcher ? &*memtable_blob_fetcher : nullptr;
// Look up starts here
if (super_version->mem->Get(
lkey,
get_impl_options.value ? get_impl_options.value->GetSelf() : nullptr,
get_impl_options.columns, ts, &s, &merge_context,
&max_covering_tombstone_seq, read_options,
false /* immutable_memtable */, &read_cb, is_blob_ptr,
/*do_merge=*/get_impl_options.get_value, memtable_blob_fetcher_ptr)) {
DBImpl::PostprocessMemtableValueRead(
key, ts, resolve_blob_backed_memtable_value, memtable_blob_fetcher_ptr,
get_impl_options.value, get_impl_options.columns, &s, &is_blob_index,
get_impl_options.value_found);
RecordTick(stats_, MEMTABLE_HIT);
} else {
PERF_TIMER_GUARD(get_from_output_files_time);
PinnedIteratorsManager pinned_iters_mgr;
super_version->current->Get(
read_options, lkey, get_impl_options.value, get_impl_options.columns,
ts, &s, &merge_context, &max_covering_tombstone_seq, &pinned_iters_mgr,
/*value_found*/ nullptr,
/*key_exists*/ nullptr, /*seq*/ nullptr, &read_cb,
/*is_blob*/ nullptr,
/*do_merge=*/get_impl_options.get_value);
RecordTick(stats_, MEMTABLE_MISS);
}
{
RecordTick(stats_, NUMBER_KEYS_READ);
size_t size = 0;
if (get_impl_options.value) {
size = get_impl_options.value->size();
} else if (get_impl_options.columns) {
size = get_impl_options.columns->serialized_size();
} else if (get_impl_options.merge_operands) {
*get_impl_options.number_of_operands =
static_cast<int>(merge_context.GetNumOperands());
for (const Slice& sl : merge_context.GetOperands()) {
size += sl.size();
get_impl_options.merge_operands->PinSelf(sl);
get_impl_options.merge_operands++;
}
}
RecordTick(stats_, BYTES_READ, size);
RecordInHistogram(stats_, BYTES_PER_READ, size);
PERF_COUNTER_ADD(get_read_bytes, size);
}
return s;
}
Iterator* DBImplReadOnly::NewIterator(const ReadOptions& _read_options,
ColumnFamilyHandle* column_family) {
if (_read_options.io_activity != Env::IOActivity::kUnknown &&
@@ -270,16 +411,3 @@ Status DBImplReadOnly::OpenForReadOnlyWithoutCheck(
}
} // namespace ROCKSDB_NAMESPACE
// Generate the regular and coroutine versions of the functions defined in
// db_impl_readonly_sync_and_async.h by including it twice. The macros expand
// differently based on whether WITH_COROUTINES or WITHOUT_COROUTINES is
// defined.
// clang-format off
#define WITHOUT_COROUTINES
#include "db/db_impl/db_impl_readonly_sync_and_async.h"
#undef WITHOUT_COROUTINES
#define WITH_COROUTINES
#include "db/db_impl/db_impl_readonly_sync_and_async.h"
#undef WITH_COROUTINES
// clang-format on
+2 -3
View File
@@ -24,9 +24,8 @@ class DBImplReadOnly : public DBImpl {
// Implementations of the DB interface
using DBImpl::GetImpl;
DECLARE_SYNC_AND_ASYNC_OVERRIDE(Status, GetImpl, const ReadOptions& options,
const Slice& key,
GetImplOptions& get_impl_options);
Status GetImpl(const ReadOptions& options, const Slice& key,
GetImplOptions& get_impl_options) override;
// TODO: Implement ReadOnly MultiGet?
@@ -1,176 +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/coro_utils.h"
#if defined(WITHOUT_COROUTINES) || \
(defined(USE_COROUTINES) && defined(WITH_COROUTINES))
namespace ROCKSDB_NAMESPACE {
// Implementations of the DB interface
DEFINE_SYNC_AND_ASYNC(Status, DBImplReadOnly::GetImpl)
(const ReadOptions& read_options, const Slice& key,
GetImplOptions& get_impl_options) {
assert(get_impl_options.value != nullptr ||
get_impl_options.columns != nullptr ||
get_impl_options.merge_operands != nullptr);
assert(get_impl_options.column_family);
Status s;
if (read_options.timestamp) {
s = FailIfTsMismatchCf(get_impl_options.column_family,
*(read_options.timestamp));
if (!s.ok()) {
CO_RETURN s;
}
} else {
s = FailIfCfHasTs(get_impl_options.column_family);
if (!s.ok()) {
CO_RETURN s;
}
}
// Clear the timestamps for returning results so that we can distinguish
// between tombstone or key that has never been written
if (get_impl_options.timestamp) {
get_impl_options.timestamp->clear();
}
#if defined(WITHOUT_COROUTINES)
PERF_CPU_TIMER_GUARD(get_cpu_nanos, immutable_db_options_.clock);
#endif
StopWatch sw(immutable_db_options_.clock, stats_, DB_GET);
PERF_TIMER_GUARD(get_snapshot_time);
const Comparator* ucmp = get_impl_options.column_family->GetComparator();
assert(ucmp);
SequenceNumber snapshot = versions_->LastSequence();
GetWithTimestampReadCallback read_cb(snapshot);
auto cfh = static_cast_with_check<ColumnFamilyHandleImpl>(
get_impl_options.column_family);
auto cfd = cfh->cfd();
bool is_blob_index = false;
bool* is_blob_ptr = get_impl_options.is_blob_index;
std::string timestamp_storage;
std::string* ts = nullptr;
if (ucmp->timestamp_size() > 0) {
ts = get_impl_options.timestamp != nullptr
? get_impl_options.timestamp
: (get_impl_options.get_value ? &timestamp_storage : nullptr);
}
if (!is_blob_ptr && get_impl_options.get_value) {
is_blob_ptr = &is_blob_index;
}
const bool resolve_blob_backed_memtable_value =
get_impl_options.get_value && (is_blob_ptr == &is_blob_index);
if (tracer_) {
InstrumentedMutexLock lock(&trace_mutex_);
if (tracer_) {
tracer_->Get(get_impl_options.column_family, key);
}
}
// In read-only mode Get(), no super version operation is needed (i.e.
// GetAndRefSuperVersion and ReturnAndCleanupSuperVersion)
SuperVersion* super_version = cfd->GetSuperVersion();
if (read_options.timestamp && read_options.timestamp->size() > 0) {
s = FailIfReadCollapsedHistory(cfd, super_version,
*(read_options.timestamp));
if (!s.ok()) {
CO_RETURN s;
}
}
// Prepare to store a list of merge operations if merge occurs.
MergeContext merge_context;
// TODO - Large Result Optimization for Read Only DB
// (https://github.com/facebook/rocksdb/pull/10458)
SequenceNumber max_covering_tombstone_seq = 0;
LookupKey lkey(key, snapshot, read_options.timestamp);
PERF_TIMER_STOP(get_snapshot_time);
std::optional<VersionBlobFetcher> memtable_blob_fetcher;
if (cfd->ioptions().enable_blob_direct_write ||
cfd->GetLatestMutableCFOptions().enable_blob_files) {
// Recovered memtables can still contain older blob references after
// mutable blob-file settings change, so keep blob resolution available
// whenever either blob knob indicates it may be needed.
memtable_blob_fetcher.emplace(super_version->current, read_options,
cfd->blob_file_cache(),
/*allow_write_path_fallback=*/true);
}
const BlobFetcher* memtable_blob_fetcher_ptr =
memtable_blob_fetcher ? &*memtable_blob_fetcher : nullptr;
// Look up starts here
if (super_version->mem->Get(
lkey,
get_impl_options.value ? get_impl_options.value->GetSelf() : nullptr,
get_impl_options.columns, ts, &s, &merge_context,
&max_covering_tombstone_seq, read_options,
false /* immutable_memtable */, &read_cb, is_blob_ptr,
/*do_merge=*/get_impl_options.get_value, memtable_blob_fetcher_ptr)) {
s = DBImpl::PostprocessMemtableValueRead(
key, ts, resolve_blob_backed_memtable_value, memtable_blob_fetcher_ptr,
get_impl_options.value, get_impl_options.columns, std::move(s),
&is_blob_index, get_impl_options.value_found);
RecordTick(stats_, MEMTABLE_HIT);
} else {
PERF_TIMER_GUARD(get_from_output_files_time);
PinnedIteratorsManager pinned_iters_mgr;
CO_AWAIT(super_version->current->Get, read_options, lkey,
get_impl_options.value, get_impl_options.columns, ts, &s,
&merge_context, &max_covering_tombstone_seq, &pinned_iters_mgr,
/*value_found*/ nullptr,
/*key_exists*/ nullptr, /*seq*/ nullptr, &read_cb,
/*is_blob*/ nullptr,
/*do_merge=*/get_impl_options.get_value,
get_impl_options.lazy_columns_same_file_reader);
RecordTick(stats_, MEMTABLE_MISS);
}
{
RecordTick(stats_, NUMBER_KEYS_READ);
size_t size = 0;
// Mirror DBImpl::GetImpl: only produce merge-operand output and count bytes
// read on success. A non-OK status leaves outputs cleared (see
// PostprocessMemtableValueRead) and records no read throughput.
if (s.ok()) {
if (get_impl_options.value) {
size = get_impl_options.value->size();
} else if (get_impl_options.columns) {
size = get_impl_options.columns->payload_size();
} else if (get_impl_options.merge_operands) {
*get_impl_options.number_of_operands =
static_cast<int>(merge_context.GetNumOperands());
for (const Slice& sl : merge_context.GetOperands()) {
size += sl.size();
get_impl_options.merge_operands->PinSelf(sl);
get_impl_options.merge_operands++;
}
}
RecordTick(stats_, BYTES_READ, size);
RecordInHistogram(stats_, BYTES_PER_READ, size);
PERF_COUNTER_ADD(get_read_bytes, size);
}
}
if (get_impl_options.lazy_columns_pin != nullptr && s.ok()) {
// Lazy result (GetEntityLazy): hand back the Version the entity's blob
// references must be resolved against, and transfer a SuperVersion pin into
// the result so it -- and deferred blob reads -- stay valid after this call
// (as an iterator's pin does). Read-only borrows the current SuperVersion
// without a reference, so the pin takes its own.
if (get_impl_options.lazy_columns_version != nullptr) {
*get_impl_options.lazy_columns_version = super_version->current;
}
TransferSuperVersionPin(super_version, get_impl_options.lazy_columns_pin);
}
CO_RETURN s;
}
} // namespace ROCKSDB_NAMESPACE
#endif // defined(WITHOUT_COROUTINES) ||
// (defined(USE_COROUTINES) && defined(WITH_COROUTINES))
+190 -17
View File
@@ -336,6 +336,193 @@ Status DBImplSecondary::RecoverLogFiles(
return status;
}
Status DBImplSecondary::GetImpl(const ReadOptions& read_options,
const Slice& key,
GetImplOptions& get_impl_options) {
assert(get_impl_options.value != nullptr ||
get_impl_options.columns != nullptr ||
get_impl_options.merge_operands != nullptr);
assert(get_impl_options.column_family);
Status s;
if (read_options.timestamp) {
s = FailIfTsMismatchCf(get_impl_options.column_family,
*(read_options.timestamp));
if (!s.ok()) {
return s;
}
} else {
s = FailIfCfHasTs(get_impl_options.column_family);
if (!s.ok()) {
return s;
}
}
// Clear the timestamps for returning results so that we can distinguish
// between tombstone or key that has never been written
if (get_impl_options.timestamp) {
get_impl_options.timestamp->clear();
}
PERF_CPU_TIMER_GUARD(get_cpu_nanos, immutable_db_options_.clock);
StopWatch sw(immutable_db_options_.clock, stats_, DB_GET);
PERF_TIMER_GUARD(get_snapshot_time);
const Comparator* ucmp = get_impl_options.column_family->GetComparator();
assert(ucmp);
SequenceNumber snapshot = versions_->LastSequence();
GetWithTimestampReadCallback read_cb(snapshot);
auto cfh = static_cast_with_check<ColumnFamilyHandleImpl>(
get_impl_options.column_family);
auto cfd = cfh->cfd();
bool is_blob_index = false;
bool* is_blob_ptr = get_impl_options.is_blob_index;
std::string timestamp_storage;
std::string* ts = nullptr;
if (ucmp->timestamp_size() > 0) {
ts = get_impl_options.timestamp != nullptr
? get_impl_options.timestamp
: (get_impl_options.get_value ? &timestamp_storage : nullptr);
}
if (!is_blob_ptr && get_impl_options.get_value) {
is_blob_ptr = &is_blob_index;
}
const bool resolve_blob_backed_memtable_value =
get_impl_options.get_value && (is_blob_ptr == &is_blob_index);
if (tracer_) {
InstrumentedMutexLock lock(&trace_mutex_);
if (tracer_) {
tracer_->Get(get_impl_options.column_family, key);
}
}
// Acquire SuperVersion
SuperVersion* super_version = GetAndRefSuperVersion(cfd);
if (read_options.timestamp && read_options.timestamp->size() > 0) {
s = FailIfReadCollapsedHistory(cfd, super_version,
*(read_options.timestamp));
if (!s.ok()) {
ReturnAndCleanupSuperVersion(cfd, super_version);
return s;
}
}
MergeContext merge_context;
// TODO - Large Result Optimization for Secondary DB
// (https://github.com/facebook/rocksdb/pull/10458)
SequenceNumber max_covering_tombstone_seq = 0;
LookupKey lkey(key, snapshot, read_options.timestamp);
PERF_TIMER_STOP(get_snapshot_time);
bool done = false;
std::optional<BlobFetcher> memtable_blob_fetcher;
if (cfd->ioptions().enable_blob_direct_write ||
cfd->GetLatestMutableCFOptions().enable_blob_files) {
// Catch-up can rebuild older blob references into memtables after mutable
// blob-file settings change, so keep blob resolution available whenever
// either blob knob indicates it may be needed.
memtable_blob_fetcher.emplace(super_version->current, read_options,
cfd->blob_file_cache(),
/*allow_write_path_fallback=*/true);
}
const BlobFetcher* memtable_blob_fetcher_ptr =
memtable_blob_fetcher ? &*memtable_blob_fetcher : nullptr;
// Look up starts here
if (get_impl_options.get_value) {
if (super_version->mem->Get(
lkey,
get_impl_options.value ? get_impl_options.value->GetSelf()
: nullptr,
get_impl_options.columns, ts, &s, &merge_context,
&max_covering_tombstone_seq, read_options,
false /* immutable_memtable */, &read_cb, is_blob_ptr,
/*do_merge=*/true, memtable_blob_fetcher_ptr)) {
done = true;
DBImpl::PostprocessMemtableValueRead(
key, ts, resolve_blob_backed_memtable_value,
memtable_blob_fetcher_ptr, get_impl_options.value,
get_impl_options.columns, &s, &is_blob_index,
get_impl_options.value_found);
RecordTick(stats_, MEMTABLE_HIT);
} else if ((s.ok() || s.IsMergeInProgress()) &&
super_version->imm->Get(
lkey,
get_impl_options.value ? get_impl_options.value->GetSelf()
: nullptr,
get_impl_options.columns, ts, &s, &merge_context,
&max_covering_tombstone_seq, read_options, &read_cb,
is_blob_ptr, memtable_blob_fetcher_ptr)) {
done = true;
DBImpl::PostprocessMemtableValueRead(
key, ts, resolve_blob_backed_memtable_value,
memtable_blob_fetcher_ptr, get_impl_options.value,
get_impl_options.columns, &s, &is_blob_index,
get_impl_options.value_found);
RecordTick(stats_, MEMTABLE_HIT);
}
} else {
// GetMergeOperands
if (super_version->mem->Get(
lkey,
get_impl_options.value ? get_impl_options.value->GetSelf()
: nullptr,
get_impl_options.columns, ts, &s, &merge_context,
&max_covering_tombstone_seq, read_options,
false /* immutable_memtable */, &read_cb,
/*is_blob_index=*/nullptr, /*do_merge=*/false,
memtable_blob_fetcher_ptr)) {
done = true;
RecordTick(stats_, MEMTABLE_HIT);
} else if ((s.ok() || s.IsMergeInProgress()) &&
super_version->imm->GetMergeOperands(
lkey, &s, &merge_context, &max_covering_tombstone_seq,
read_options, memtable_blob_fetcher_ptr)) {
done = true;
RecordTick(stats_, MEMTABLE_HIT);
}
}
if (!s.ok() && !s.IsMergeInProgress() && !s.IsNotFound()) {
assert(done);
ReturnAndCleanupSuperVersion(cfd, super_version);
return s;
}
if (!done) {
PERF_TIMER_GUARD(get_from_output_files_time);
PinnedIteratorsManager pinned_iters_mgr;
super_version->current->Get(
read_options, lkey, get_impl_options.value, get_impl_options.columns,
ts, &s, &merge_context, &max_covering_tombstone_seq, &pinned_iters_mgr,
/*value_found*/ nullptr,
/*key_exists*/ nullptr, /*seq*/ nullptr, &read_cb, /*is_blob*/ nullptr,
/*do_merge=*/get_impl_options.get_value);
RecordTick(stats_, MEMTABLE_MISS);
}
{
PERF_TIMER_GUARD(get_post_process_time);
ReturnAndCleanupSuperVersion(cfd, super_version);
RecordTick(stats_, NUMBER_KEYS_READ);
size_t size = 0;
if (get_impl_options.value) {
size = get_impl_options.value->size();
} else if (get_impl_options.columns) {
size = get_impl_options.columns->serialized_size();
} else if (get_impl_options.merge_operands) {
*get_impl_options.number_of_operands =
static_cast<int>(merge_context.GetNumOperands());
for (const Slice& sl : merge_context.GetOperands()) {
size += sl.size();
get_impl_options.merge_operands->PinSelf(sl);
get_impl_options.merge_operands++;
}
}
RecordTick(stats_, BYTES_READ, size);
RecordTimeToHistogram(stats_, BYTES_PER_READ, size);
PERF_COUNTER_ADD(get_read_bytes, size);
}
return s;
}
Iterator* DBImplSecondary::NewIterator(const ReadOptions& _read_options,
ColumnFamilyHandle* column_family) {
if (_read_options.io_activity != Env::IOActivity::kUnknown &&
@@ -1362,6 +1549,9 @@ Status DB::OpenAndCompact(
db_options.statistics = override_options.statistics;
db_options.listeners = override_options.listeners;
db_options.compaction_service = nullptr;
// We will close the DB after the compaction anyway.
// Open as many files as needed for the compaction.
db_options.max_open_files = -1;
db_options.info_log = override_options.info_log;
// 4. Filter CFs that are needed for OpenAndCompact()
@@ -1406,13 +1596,9 @@ Status DB::OpenAndCompact(
// needs LSM state from MANIFEST, not memtable data from WAL replay)
std::unique_ptr<DB> db;
std::vector<ColumnFamilyHandle*> handles;
const uint64_t db_open_start_micros = db_options.env->NowMicros();
s = DBImplSecondary::OpenAsSecondaryImpl(db_options, name, output_directory,
column_families, &handles, &db,
/*recover_wal=*/false);
RecordTimeToHistogram(db_options.statistics.get(),
OPEN_AND_COMPACT_DB_OPEN_MICROS,
db_options.env->NowMicros() - db_open_start_micros);
if (!s.ok()) {
return s;
}
@@ -1613,16 +1799,3 @@ Status DBImplSecondary::FinalizeCompactionProgressWriter(
return Status::OK();
}
} // namespace ROCKSDB_NAMESPACE
// Generate the regular and coroutine versions of the functions defined in
// db_impl_secondary_sync_and_async.h by including it twice. The macros expand
// differently based on whether WITH_COROUTINES or WITHOUT_COROUTINES is
// defined.
// clang-format off
#define WITHOUT_COROUTINES
#include "db/db_impl/db_impl_secondary_sync_and_async.h"
#undef WITHOUT_COROUTINES
#define WITH_COROUTINES
#include "db/db_impl/db_impl_secondary_sync_and_async.h"
#undef WITH_COROUTINES
// clang-format on
+2 -3
View File
@@ -97,9 +97,8 @@ class DBImplSecondary : public DBImpl {
// it eagerly keeps all talbe files open and is able to access the contents of
// deleted files via prior open fd.
using DBImpl::GetImpl;
DECLARE_SYNC_AND_ASYNC_OVERRIDE(Status, GetImpl, const ReadOptions& options,
const Slice& key,
GetImplOptions& get_impl_options);
Status GetImpl(const ReadOptions& options, const Slice& key,
GetImplOptions& get_impl_options) override;
using DBImpl::NewIterator;
// Operations on the created iterators can return IOError due to files being
@@ -1,238 +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/coro_utils.h"
#if defined(WITHOUT_COROUTINES) || \
(defined(USE_COROUTINES) && defined(WITH_COROUTINES))
namespace ROCKSDB_NAMESPACE {
DEFINE_SYNC_AND_ASYNC(Status, DBImplSecondary::GetImpl)
(const ReadOptions& read_options, const Slice& key,
GetImplOptions& get_impl_options) {
assert(get_impl_options.value != nullptr ||
get_impl_options.columns != nullptr ||
get_impl_options.merge_operands != nullptr);
assert(get_impl_options.column_family);
Status s;
if (read_options.timestamp) {
s = FailIfTsMismatchCf(get_impl_options.column_family,
*(read_options.timestamp));
if (!s.ok()) {
CO_RETURN s;
}
} else {
s = FailIfCfHasTs(get_impl_options.column_family);
if (!s.ok()) {
CO_RETURN s;
}
}
// Clear the timestamps for returning results so that we can distinguish
// between tombstone or key that has never been written
if (get_impl_options.timestamp) {
get_impl_options.timestamp->clear();
}
#if defined(WITHOUT_COROUTINES)
PERF_CPU_TIMER_GUARD(get_cpu_nanos, immutable_db_options_.clock);
#endif
StopWatch sw(immutable_db_options_.clock, stats_, DB_GET);
PERF_TIMER_GUARD(get_snapshot_time);
const Comparator* ucmp = get_impl_options.column_family->GetComparator();
assert(ucmp);
SequenceNumber snapshot = versions_->LastSequence();
GetWithTimestampReadCallback read_cb(snapshot);
auto cfh = static_cast_with_check<ColumnFamilyHandleImpl>(
get_impl_options.column_family);
auto cfd = cfh->cfd();
bool is_blob_index = false;
bool* is_blob_ptr = get_impl_options.is_blob_index;
std::string timestamp_storage;
std::string* ts = nullptr;
if (ucmp->timestamp_size() > 0) {
ts = get_impl_options.timestamp != nullptr
? get_impl_options.timestamp
: (get_impl_options.get_value ? &timestamp_storage : nullptr);
}
if (!is_blob_ptr && get_impl_options.get_value) {
is_blob_ptr = &is_blob_index;
}
const bool resolve_blob_backed_memtable_value =
get_impl_options.get_value && (is_blob_ptr == &is_blob_index);
if (tracer_) {
InstrumentedMutexLock lock(&trace_mutex_);
if (tracer_) {
tracer_->Get(get_impl_options.column_family, key);
}
}
// Acquire SuperVersion
#if defined(WITH_COROUTINES)
SuperVersion* super_version = cfd->GetReferencedSuperVersion(this);
#else
SuperVersion* super_version = GetAndRefSuperVersion(cfd);
#endif
if (read_options.timestamp && read_options.timestamp->size() > 0) {
s = FailIfReadCollapsedHistory(cfd, super_version,
*(read_options.timestamp));
if (!s.ok()) {
#if defined(WITH_COROUTINES)
CleanupSuperVersion(super_version);
#else
ReturnAndCleanupSuperVersion(cfd, super_version);
#endif
CO_RETURN s;
}
}
MergeContext merge_context;
// TODO - Large Result Optimization for Secondary DB
// (https://github.com/facebook/rocksdb/pull/10458)
SequenceNumber max_covering_tombstone_seq = 0;
LookupKey lkey(key, snapshot, read_options.timestamp);
PERF_TIMER_STOP(get_snapshot_time);
bool done = false;
std::optional<VersionBlobFetcher> memtable_blob_fetcher;
if (cfd->ioptions().enable_blob_direct_write ||
cfd->GetLatestMutableCFOptions().enable_blob_files) {
// Catch-up can rebuild older blob references into memtables after mutable
// blob-file settings change, so keep blob resolution available whenever
// either blob knob indicates it may be needed.
memtable_blob_fetcher.emplace(super_version->current, read_options,
cfd->blob_file_cache(),
/*allow_write_path_fallback=*/true);
}
const BlobFetcher* memtable_blob_fetcher_ptr =
memtable_blob_fetcher ? &*memtable_blob_fetcher : nullptr;
// Look up starts here
if (get_impl_options.get_value) {
if (super_version->mem->Get(
lkey,
get_impl_options.value ? get_impl_options.value->GetSelf()
: nullptr,
get_impl_options.columns, ts, &s, &merge_context,
&max_covering_tombstone_seq, read_options,
false /* immutable_memtable */, &read_cb, is_blob_ptr,
/*do_merge=*/true, memtable_blob_fetcher_ptr)) {
done = true;
s = DBImpl::PostprocessMemtableValueRead(
key, ts, resolve_blob_backed_memtable_value,
memtable_blob_fetcher_ptr, get_impl_options.value,
get_impl_options.columns, std::move(s), &is_blob_index,
get_impl_options.value_found);
RecordTick(stats_, MEMTABLE_HIT);
} else if ((s.ok() || s.IsMergeInProgress()) &&
super_version->imm->Get(
lkey,
get_impl_options.value ? get_impl_options.value->GetSelf()
: nullptr,
get_impl_options.columns, ts, &s, &merge_context,
&max_covering_tombstone_seq, read_options, &read_cb,
is_blob_ptr, memtable_blob_fetcher_ptr)) {
done = true;
s = DBImpl::PostprocessMemtableValueRead(
key, ts, resolve_blob_backed_memtable_value,
memtable_blob_fetcher_ptr, get_impl_options.value,
get_impl_options.columns, std::move(s), &is_blob_index,
get_impl_options.value_found);
RecordTick(stats_, MEMTABLE_HIT);
}
} else {
// GetMergeOperands
if (super_version->mem->Get(
lkey,
get_impl_options.value ? get_impl_options.value->GetSelf()
: nullptr,
get_impl_options.columns, ts, &s, &merge_context,
&max_covering_tombstone_seq, read_options,
false /* immutable_memtable */, &read_cb,
/*is_blob_index=*/nullptr, /*do_merge=*/false,
memtable_blob_fetcher_ptr)) {
done = true;
RecordTick(stats_, MEMTABLE_HIT);
} else if ((s.ok() || s.IsMergeInProgress()) &&
super_version->imm->GetMergeOperands(
lkey, &s, &merge_context, &max_covering_tombstone_seq,
read_options, memtable_blob_fetcher_ptr)) {
done = true;
RecordTick(stats_, MEMTABLE_HIT);
}
}
if (!s.ok() && !s.IsMergeInProgress() && !s.IsNotFound()) {
assert(done);
#if defined(WITH_COROUTINES)
CleanupSuperVersion(super_version);
#else
ReturnAndCleanupSuperVersion(cfd, super_version);
#endif
CO_RETURN s;
}
if (!done) {
PERF_TIMER_GUARD(get_from_output_files_time);
PinnedIteratorsManager pinned_iters_mgr;
CO_AWAIT(super_version->current->Get, read_options, lkey,
get_impl_options.value, get_impl_options.columns, ts, &s,
&merge_context, &max_covering_tombstone_seq, &pinned_iters_mgr,
/*value_found*/ nullptr,
/*key_exists*/ nullptr, /*seq*/ nullptr, &read_cb,
/*is_blob*/ nullptr,
/*do_merge=*/get_impl_options.get_value,
get_impl_options.lazy_columns_same_file_reader);
RecordTick(stats_, MEMTABLE_MISS);
}
{
PERF_TIMER_GUARD(get_post_process_time);
if (get_impl_options.lazy_columns_pin != nullptr && s.ok()) {
// Lazy result (GetEntityLazy): hand back the resolution Version and take
// a SuperVersion pin for the result before the borrowed reference below
// is released, so the result -- and deferred blob reads -- stay valid
// after this call (as an iterator's pin does).
if (get_impl_options.lazy_columns_version != nullptr) {
*get_impl_options.lazy_columns_version = super_version->current;
}
TransferSuperVersionPin(super_version, get_impl_options.lazy_columns_pin);
}
#if defined(WITH_COROUTINES)
CleanupSuperVersion(super_version);
#else
ReturnAndCleanupSuperVersion(cfd, super_version);
#endif
RecordTick(stats_, NUMBER_KEYS_READ);
size_t size = 0;
// Mirror DBImpl::GetImpl: only produce merge-operand output and count bytes
// read on success. A non-OK status leaves outputs cleared (see
// PostprocessMemtableValueRead) and records no read throughput.
if (s.ok()) {
if (get_impl_options.value) {
size = get_impl_options.value->size();
} else if (get_impl_options.columns) {
size = get_impl_options.columns->payload_size();
} else if (get_impl_options.merge_operands) {
*get_impl_options.number_of_operands =
static_cast<int>(merge_context.GetNumOperands());
for (const Slice& sl : merge_context.GetOperands()) {
size += sl.size();
get_impl_options.merge_operands->PinSelf(sl);
get_impl_options.merge_operands++;
}
}
RecordTick(stats_, BYTES_READ, size);
RecordTimeToHistogram(stats_, BYTES_PER_READ, size);
PERF_COUNTER_ADD(get_read_bytes, size);
}
}
CO_RETURN s;
}
} // namespace ROCKSDB_NAMESPACE
#endif // defined(WITHOUT_COROUTINES) ||
// (defined(USE_COROUTINES) && defined(WITH_COROUTINES))
-832
View File
@@ -1,832 +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/coro_utils.h"
#if defined(USE_COROUTINES) && defined(WITH_COROUTINES)
#include "util/coro_stats_util.h"
#endif // USE_COROUTINES && WITH_COROUTINES
#if defined(WITHOUT_COROUTINES) || \
(defined(USE_COROUTINES) && defined(WITH_COROUTINES))
namespace ROCKSDB_NAMESPACE {
DEFINE_SYNC_AND_ASYNC(Status, DBImpl::GetImpl)
(const ReadOptions& read_options, ColumnFamilyHandle* column_family,
const Slice& key, PinnableSlice* value) {
CO_RETURN CO_AWAIT(GetImpl, read_options, column_family, key, value,
/*timestamp=*/nullptr);
}
DEFINE_SYNC_AND_ASYNC(Status, DBImpl::Get)
(const ReadOptions& _read_options, ColumnFamilyHandle* column_family,
const Slice& key, PinnableSlice* value, std::string* timestamp) {
#ifdef WITH_COROUTINES
INSTALL_COROUTINE_STATS_CONTEXT_SCOPE(
immutable_db_options_.fs->GetReadExecutor(), immutable_db_options_.env);
#endif
assert(value != nullptr);
value->Reset();
if (_read_options.io_activity != Env::IOActivity::kUnknown &&
_read_options.io_activity != Env::IOActivity::kGet) {
CO_RETURN Status::InvalidArgument(
"Can only call Get with `ReadOptions::io_activity` is "
"`Env::IOActivity::kUnknown` or `Env::IOActivity::kGet`");
}
ReadOptions read_options(_read_options);
if (read_options.io_activity == Env::IOActivity::kUnknown) {
read_options.io_activity = Env::IOActivity::kGet;
}
CO_RETURN CO_AWAIT(GetImpl, read_options, column_family, key, value,
timestamp);
}
DEFINE_SYNC_AND_ASYNC(Status, DBImpl::GetImpl)
(const ReadOptions& read_options, ColumnFamilyHandle* column_family,
const Slice& key, PinnableSlice* value, std::string* timestamp) {
GetImplOptions get_impl_options;
get_impl_options.column_family = column_family;
get_impl_options.value = value;
get_impl_options.timestamp = timestamp;
Status s = CO_AWAIT(GetImpl, read_options, key, get_impl_options);
CO_RETURN s;
}
DEFINE_SYNC_AND_ASYNC(Status, DBImpl::GetImpl)
(const ReadOptions& read_options, const Slice& key,
GetImplOptions& get_impl_options) {
assert(get_impl_options.value != nullptr ||
get_impl_options.merge_operands != nullptr ||
get_impl_options.columns != nullptr);
assert(get_impl_options.column_family);
if (read_options.timestamp) {
const Status s = FailIfTsMismatchCf(get_impl_options.column_family,
*(read_options.timestamp));
if (!s.ok()) {
CO_RETURN s;
}
} else {
const Status s = FailIfCfHasTs(get_impl_options.column_family);
if (!s.ok()) {
CO_RETURN s;
}
}
// Clear the timestamps for returning results so that we can distinguish
// between tombstone or key that has never been written
if (get_impl_options.timestamp) {
get_impl_options.timestamp->clear();
}
GetWithTimestampReadCallback read_cb(0); // Will call Refresh
#if defined(WITHOUT_COROUTINES)
PERF_CPU_TIMER_GUARD(get_cpu_nanos, immutable_db_options_.clock);
#endif
StopWatch sw(immutable_db_options_.clock, stats_, DB_GET);
PERF_TIMER_GUARD(get_snapshot_time);
auto cfh = static_cast_with_check<ColumnFamilyHandleImpl>(
get_impl_options.column_family);
auto cfd = cfh->cfd();
if (tracer_) {
// TODO: This mutex should be removed later, to improve performance when
// tracing is enabled.
InstrumentedMutexLock lock(&trace_mutex_);
if (tracer_) {
// TODO: maybe handle the tracing status?
tracer_->Get(get_impl_options.column_family, key).PermitUncheckedError();
}
}
if (get_impl_options.get_merge_operands_options != nullptr) {
for (int i = 0; i < get_impl_options.get_merge_operands_options
->expected_max_number_of_operands;
++i) {
get_impl_options.merge_operands[i].Reset();
}
}
// Acquire SuperVersion
#if defined(WITH_COROUTINES)
SuperVersion* sv = cfd->GetReferencedSuperVersion(this);
Defer sv_cleanup([&] { CleanupSuperVersion(sv); });
#else
SuperVersion* sv = GetAndRefSuperVersion(cfd);
Defer sv_cleanup([&] { ReturnAndCleanupSuperVersion(cfd, sv); });
#endif
if (read_options.timestamp && read_options.timestamp->size() > 0) {
const Status s =
FailIfReadCollapsedHistory(cfd, sv, *(read_options.timestamp));
if (!s.ok()) {
CO_RETURN s;
}
}
TEST_SYNC_POINT_CALLBACK("DBImpl::GetImpl:AfterAcquireSv", nullptr);
TEST_SYNC_POINT("DBImpl::GetImpl:1");
TEST_SYNC_POINT("DBImpl::GetImpl:2");
SequenceNumber snapshot;
if (read_options.snapshot != nullptr) {
if (get_impl_options.callback) {
// Already calculated based on read_options.snapshot
snapshot = get_impl_options.callback->max_visible_seq();
} else {
snapshot =
static_cast<const SnapshotImpl*>(read_options.snapshot)->number_;
}
} else {
// Note that the snapshot is assigned AFTER referencing the super
// version because otherwise a flush happening in between may compact away
// data for the snapshot, so the reader would see neither data that was be
// visible to the snapshot before compaction nor the newer data inserted
// afterwards.
snapshot = GetLastPublishedSequence();
if (get_impl_options.callback) {
// The unprep_seqs are not published for write unprepared, so it could be
// that max_visible_seq is larger. Seek to the std::max of the two.
// However, we still want our callback to contain the actual snapshot so
// that it can do the correct visibility filtering.
get_impl_options.callback->Refresh(snapshot);
// Internally, WriteUnpreparedTxnReadCallback::Refresh would set
// max_visible_seq = max(max_visible_seq, snapshot)
//
// Currently, the commented out assert is broken by
// InvalidSnapshotReadCallback, but if write unprepared recovery followed
// the regular transaction flow, then this special read callback would not
// be needed.
//
// assert(callback->max_visible_seq() >= snapshot);
snapshot = get_impl_options.callback->max_visible_seq();
}
}
// If timestamp is used, we use read callback to ensure <key,t,s> is returned
// only if t <= read_opts.timestamp and s <= snapshot.
// HACK: temporarily overwrite input struct field but restore
SaveAndRestore<ReadCallback*> restore_callback(&get_impl_options.callback);
const Comparator* ucmp = get_impl_options.column_family->GetComparator();
assert(ucmp);
if (ucmp->timestamp_size() > 0) {
assert(!get_impl_options
.callback); // timestamp with callback is not supported
read_cb.Refresh(snapshot);
get_impl_options.callback = &read_cb;
}
TEST_SYNC_POINT("DBImpl::GetImpl:3");
TEST_SYNC_POINT("DBImpl::GetImpl:4");
// Prepare to store a list of merge operations if merge occurs.
MergeContext merge_context;
merge_context.get_merge_operands_options =
get_impl_options.get_merge_operands_options;
SequenceNumber max_covering_tombstone_seq = 0;
Status s;
// First look in the memtable, then in the immutable memtable (if any).
// s is both in/out. When in, s could either be OK or MergeInProgress.
// merge_operands will contain the sequence of merges in the latter case.
LookupKey lkey(key, snapshot, read_options.timestamp);
PERF_TIMER_STOP(get_snapshot_time);
bool skip_memtable = (read_options.read_tier == kPersistedTier &&
has_unpersisted_data_.load(std::memory_order_relaxed));
bool done = false;
bool is_blob_index = false;
bool* is_blob_ptr = get_impl_options.is_blob_index;
auto* partition_mgr = cfd->blob_partition_manager();
std::string timestamp_storage;
std::string* timestamp = nullptr;
if (ucmp->timestamp_size() > 0) {
timestamp = get_impl_options.timestamp != nullptr
? get_impl_options.timestamp
: (partition_mgr != nullptr ? &timestamp_storage : nullptr);
}
if (partition_mgr != nullptr && !is_blob_ptr && get_impl_options.get_value) {
is_blob_ptr = &is_blob_index;
}
const bool resolve_direct_write_value =
partition_mgr != nullptr && (is_blob_ptr == &is_blob_index);
std::optional<VersionBlobFetcher> memtable_blob_fetcher;
if (partition_mgr != nullptr) {
memtable_blob_fetcher.emplace(sv->current, read_options,
cfd->blob_file_cache(),
/*allow_write_path_fallback=*/true);
}
const BlobFetcher* memtable_blob_fetcher_ptr =
memtable_blob_fetcher ? &*memtable_blob_fetcher : nullptr;
if (!skip_memtable) {
// Get value associated with key
if (get_impl_options.get_value) {
if (sv->mem->Get(lkey,
get_impl_options.value
? get_impl_options.value->GetSelf()
: nullptr,
get_impl_options.columns, timestamp, &s, &merge_context,
&max_covering_tombstone_seq, read_options,
false /* immutable_memtable */,
get_impl_options.callback, is_blob_ptr,
/*do_merge=*/true, memtable_blob_fetcher_ptr)) {
done = true;
PostprocessDirectWriteValueRead(
read_options, key, timestamp, resolve_direct_write_value,
memtable_blob_fetcher_ptr, get_impl_options.value,
get_impl_options.columns, &s, &is_blob_index,
get_impl_options.value_found);
RecordTick(stats_, MEMTABLE_HIT);
} else if ((s.ok() || s.IsMergeInProgress()) &&
sv->imm->Get(lkey,
get_impl_options.value
? get_impl_options.value->GetSelf()
: nullptr,
get_impl_options.columns, timestamp, &s,
&merge_context, &max_covering_tombstone_seq,
read_options, get_impl_options.callback,
is_blob_ptr, memtable_blob_fetcher_ptr)) {
done = true;
PostprocessDirectWriteValueRead(
read_options, key, timestamp, resolve_direct_write_value,
memtable_blob_fetcher_ptr, get_impl_options.value,
get_impl_options.columns, &s, &is_blob_index,
get_impl_options.value_found);
RecordTick(stats_, MEMTABLE_HIT);
}
} else {
// Get Merge Operands associated with key, Merge Operands should not be
// merged and raw values should be returned to the user.
if (sv->mem->Get(lkey, /*value=*/nullptr, /*columns=*/nullptr,
/*timestamp=*/nullptr, &s, &merge_context,
&max_covering_tombstone_seq, read_options,
false /* immutable_memtable */, nullptr, nullptr, false,
memtable_blob_fetcher_ptr)) {
done = true;
RecordTick(stats_, MEMTABLE_HIT);
} else if ((s.ok() || s.IsMergeInProgress()) &&
sv->imm->GetMergeOperands(
lkey, &s, &merge_context, &max_covering_tombstone_seq,
read_options, memtable_blob_fetcher_ptr)) {
done = true;
RecordTick(stats_, MEMTABLE_HIT);
}
}
if (!s.ok() && !s.IsMergeInProgress() && !s.IsNotFound()) {
assert(done);
CO_RETURN s;
}
}
TEST_SYNC_POINT("DBImpl::GetImpl:PostMemTableGet:0");
TEST_SYNC_POINT("DBImpl::GetImpl:PostMemTableGet:1");
PinnedIteratorsManager pinned_iters_mgr;
if (!done) {
PERF_TIMER_GUARD(get_from_output_files_time);
CO_AWAIT(
sv->current->Get, read_options, lkey, get_impl_options.value,
get_impl_options.columns, timestamp, &s, &merge_context,
&max_covering_tombstone_seq, &pinned_iters_mgr,
get_impl_options.get_value ? get_impl_options.value_found : nullptr,
nullptr, nullptr,
get_impl_options.get_value ? get_impl_options.callback : nullptr,
get_impl_options.get_value ? is_blob_ptr : nullptr,
get_impl_options.get_value,
get_impl_options.lazy_columns_same_file_reader);
if (get_impl_options.get_value && resolve_direct_write_value) {
assert(memtable_blob_fetcher_ptr != nullptr);
std::string blob_lookup_key_storage;
MaybeResolveDirectWriteValue(
read_options,
GetBlobLookupUserKey(key, timestamp, &blob_lookup_key_storage),
resolve_direct_write_value, *memtable_blob_fetcher_ptr,
get_impl_options.value, get_impl_options.columns, &s, &is_blob_index,
get_impl_options.value_found);
}
RecordTick(stats_, MEMTABLE_MISS);
}
{
PERF_TIMER_GUARD(get_post_process_time);
RecordTick(stats_, NUMBER_KEYS_READ);
size_t size = 0;
if (s.ok()) {
const auto& merge_threshold = read_options.merge_operand_count_threshold;
if (merge_threshold.has_value() &&
merge_context.GetNumOperands() > merge_threshold.value()) {
s = Status::OkMergeOperandThresholdExceeded();
}
if (get_impl_options.get_value) {
if (get_impl_options.value) {
size = get_impl_options.value->size();
} else if (get_impl_options.columns) {
size = get_impl_options.columns->payload_size();
}
} else {
// Return all merge operands for get_impl_options.key
*get_impl_options.number_of_operands =
static_cast<int>(merge_context.GetNumOperands());
// OK status is returned, some merge operand is found.
assert(*get_impl_options.number_of_operands > 0);
if (*get_impl_options.number_of_operands >
get_impl_options.get_merge_operands_options
->expected_max_number_of_operands) {
s = Status::Incomplete(
Status::SubCode::KMergeOperandsInsufficientCapacity);
} else {
// Each operand depends on one of the following resources: `sv`,
// `pinned_iters_mgr`, or `merge_context`. It would be crazy expensive
// to reference `sv` for each operand relying on it because `sv` is
// (un)ref'd in all threads using the DB. Furthermore, we do not track
// on which resource each operand depends.
//
// To solve this, we bundle the resources in a `GetMergeOperandsState`
// and manage them with a `SharedCleanablePtr` shared among the
// `PinnableSlice`s we return. This bundle includes one `sv` reference
// and ownership of the `merge_context` and `pinned_iters_mgr`
// objects.
bool ref_sv = ShouldReferenceSuperVersion(merge_context);
if (ref_sv) {
assert(!merge_context.GetOperands().empty());
SharedCleanablePtr shared_cleanable;
GetMergeOperandsState* state = new GetMergeOperandsState(
std::move(merge_context), std::move(pinned_iters_mgr));
sv->Ref();
state->sv_handle = new SuperVersionHandle(
this, &mutex_, sv,
immutable_db_options_.avoid_unnecessary_blocking_io);
shared_cleanable.Allocate();
shared_cleanable->RegisterCleanup(CleanupGetMergeOperandsState,
state /* arg1 */,
nullptr /* arg2 */);
for (size_t i = 0; i < state->merge_context.GetOperands().size();
++i) {
const Slice& sl = state->merge_context.GetOperands()[i];
size += sl.size();
get_impl_options.merge_operands->PinSlice(
sl, nullptr /* cleanable */);
if (i == state->merge_context.GetOperands().size() - 1) {
shared_cleanable.MoveAsCleanupTo(
get_impl_options.merge_operands);
} else {
shared_cleanable.RegisterCopyWith(
get_impl_options.merge_operands);
}
get_impl_options.merge_operands++;
}
} else {
for (const Slice& sl : merge_context.GetOperands()) {
size += sl.size();
get_impl_options.merge_operands->PinSelf(sl);
get_impl_options.merge_operands++;
}
}
}
}
RecordTick(stats_, BYTES_READ, size);
PERF_COUNTER_ADD(get_read_bytes, size);
}
if (get_impl_options.lazy_columns_pin != nullptr && s.ok()) {
// Lazy result (GetEntityLazy): the entity's blob references were left
// unresolved. Hand back the Version they must be resolved against and
// transfer an extra SuperVersion reference into the result's pin, so the
// result -- and thus deferred blob reads -- stay valid after this call
// returns (as an iterator's SuperVersion pin does). The reference is
// released when the pin's cleanup runs (result destruction); the
// borrowed reference for this call is dropped by the sv_cleanup Defer.
if (get_impl_options.lazy_columns_version != nullptr) {
*get_impl_options.lazy_columns_version = sv->current;
}
TransferSuperVersionPin(sv, get_impl_options.lazy_columns_pin);
}
RecordInHistogram(stats_, BYTES_PER_READ, size);
}
CO_RETURN s;
}
// The actual implementation of batched MultiGet. Parameters -
// start_key - Index in the sorted_keys vector to start processing from
// num_keys - Number of keys to lookup, starting with sorted_keys[start_key]
// sorted_keys - The entire batch of sorted keys for this CF
//
// The per key status is returned in the KeyContext structures pointed to by
// sorted_keys. An overall Status is also returned, with the only possible
// values being Status::OK() and Status::TimedOut(). The latter indicates
// that the call exceeded read_options.deadline
DEFINE_SYNC_AND_ASYNC(Status, DBImpl::MultiGetImpl)
(const ReadOptions& read_options, size_t start_key, size_t num_keys,
autovector<KeyContext*, MultiGetContext::MAX_BATCH_SIZE>* sorted_keys,
SuperVersion* super_version, SequenceNumber snapshot, ReadCallback* callback) {
#if defined(WITHOUT_COROUTINES)
PERF_CPU_TIMER_GUARD(get_cpu_nanos, immutable_db_options_.clock);
#endif // defined(WITHOUT_COROUTINES)
StopWatch sw(immutable_db_options_.clock, stats_, DB_MULTIGET);
assert(sorted_keys);
assert(start_key + num_keys <= sorted_keys->size());
if (num_keys == 0) {
CO_RETURN Status::OK();
}
auto* cfh = static_cast_with_check<ColumnFamilyHandleImpl>(
(*sorted_keys)[start_key]->column_family);
ColumnFamilyData* cfd = cfh->cfd();
auto* partition_mgr = cfd->blob_partition_manager();
std::optional<VersionBlobFetcher> memtable_blob_fetcher;
if (partition_mgr != nullptr) {
memtable_blob_fetcher.emplace(super_version->current, read_options,
cfd->blob_file_cache(),
/*allow_write_path_fallback=*/true);
}
const BlobFetcher* memtable_blob_fetcher_ptr =
memtable_blob_fetcher ? &*memtable_blob_fetcher : nullptr;
#ifdef WITH_COROUTINES
constexpr bool kUseCoroRead = true;
#else
constexpr bool kUseCoroRead = false;
#endif
// Clear the timestamps for returning results so that we can distinguish
// between tombstone or key that has never been written
for (size_t i = start_key; i < start_key + num_keys; ++i) {
KeyContext* kctx = (*sorted_keys)[i];
if (kctx->timestamp) {
kctx->timestamp->clear();
}
}
// For each of the given keys, apply the entire "get" process as follows:
// First look in the memtable, then in the immutable memtable (if any).
// s is both in/out. When in, s could either be OK or MergeInProgress.
// merge_operands will contain the sequence of merges in the latter case.
size_t keys_left = num_keys;
Status s;
uint64_t curr_value_size = 0;
while (keys_left) {
if (read_options.deadline.count() &&
immutable_db_options_.clock->NowMicros() >
static_cast<uint64_t>(read_options.deadline.count())) {
s = Status::TimedOut();
break;
}
size_t batch_size = (keys_left > MultiGetContext::MAX_BATCH_SIZE)
? MultiGetContext::MAX_BATCH_SIZE
: keys_left;
MultiGetContext ctx(sorted_keys, start_key + num_keys - keys_left,
batch_size, snapshot, read_options, GetFileSystem(),
stats_, kUseCoroRead);
MultiGetRange range = ctx.GetMultiGetRange();
range.AddValueSize(curr_value_size);
bool lookup_current = true;
keys_left -= batch_size;
for (auto mget_iter = range.begin(); mget_iter != range.end();
++mget_iter) {
mget_iter->merge_context.Clear();
*mget_iter->s = Status::OK();
}
bool skip_memtable =
(read_options.read_tier == kPersistedTier &&
has_unpersisted_data_.load(std::memory_order_relaxed));
if (!skip_memtable) {
super_version->mem->MultiGet(read_options, &range, callback,
false /* immutable_memtable */,
memtable_blob_fetcher_ptr);
if (!range.empty()) {
super_version->imm->MultiGet(read_options, &range, callback,
memtable_blob_fetcher_ptr);
}
if (!range.empty()) {
uint64_t left = range.KeysLeft();
RecordTick(stats_, MEMTABLE_MISS, left);
} else {
lookup_current = false;
}
}
if (lookup_current) {
PERF_TIMER_GUARD(get_from_output_files_time);
CO_AWAIT(super_version->current->MultiGet, read_options, &range,
callback);
}
curr_value_size = range.GetValueSize();
if (curr_value_size > read_options.value_size_soft_limit) {
s = Status::Aborted();
break;
}
// This could be a long-running operation
bool aborted = ROCKSDB_THREAD_YIELD_CHECK_ABORT();
if (aborted) {
s = Status::Aborted("Query abort.");
break;
}
}
// Post processing (decrement reference counts and record statistics)
PERF_TIMER_GUARD(get_post_process_time);
size_t num_found = 0;
uint64_t bytes_read = 0;
// value_size_soft_limit was enforced above (and inside per-file MultiGet) on
// pre-resolution sizes. Direct-write blob references, though, are resolved
// below -- after that check counted only their encoded blob-index bytes.
// Enforce the limit on them here too, but only abort a key once the bytes
// already returned by this MultiGet exceed the limit. That way at least one
// key is always read even if it alone exceeds the limit ("always make
// progress"), so a caller retrying aborted keys cannot loop forever on a
// single oversized value.
const bool enforce_direct_write_soft_limit =
partition_mgr != nullptr &&
read_options.value_size_soft_limit !=
std::numeric_limits<uint64_t>::max() &&
read_options.read_tier != kBlockCacheTier;
for (size_t i = start_key; i < start_key + num_keys - keys_left; ++i) {
KeyContext* key = (*sorted_keys)[i];
assert(key);
assert(key->s);
if (partition_mgr != nullptr && key->s->ok()) {
const bool has_unresolved_direct_write =
key->is_blob_index ||
(key->columns != nullptr &&
!PinnableWideColumnsHelper::GetUnresolvedBlobColumnIndices(
*key->columns)
.empty());
if (enforce_direct_write_soft_limit && has_unresolved_direct_write &&
bytes_read > read_options.value_size_soft_limit) {
// Prior keys in this MultiGet have already returned more than the soft
// limit, so skip fetching this key's (possibly large) blob value(s).
if (key->value != nullptr) {
key->value->Reset();
}
if (key->columns != nullptr) {
key->columns->Reset();
}
key->is_blob_index = false;
*key->s = Status::Aborted();
} else {
assert(memtable_blob_fetcher_ptr != nullptr);
std::string blob_lookup_key_storage;
MaybeResolveDirectWriteValue(
read_options,
GetBlobLookupUserKey(*key->key, key->timestamp,
&blob_lookup_key_storage),
/*resolve_direct_write_value=*/true, *memtable_blob_fetcher_ptr,
key->value, key->columns, key->s, &key->is_blob_index);
}
}
if (key->s->ok()) {
const auto& merge_threshold = read_options.merge_operand_count_threshold;
if (merge_threshold.has_value() &&
key->merge_context.GetNumOperands() > merge_threshold) {
*(key->s) = Status::OkMergeOperandThresholdExceeded();
}
if (key->value) {
bytes_read += key->value->size();
} else {
assert(key->columns);
bytes_read += key->columns->payload_size();
}
num_found++;
}
}
if (keys_left) {
assert(s.IsTimedOut() || s.IsAborted());
for (size_t i = start_key + num_keys - keys_left; i < start_key + num_keys;
++i) {
KeyContext* key = (*sorted_keys)[i];
*key->s = s;
}
}
RecordTick(stats_, NUMBER_MULTIGET_CALLS);
RecordTick(stats_, NUMBER_MULTIGET_KEYS_READ, num_keys);
RecordTick(stats_, NUMBER_MULTIGET_KEYS_FOUND, num_found);
RecordTick(stats_, NUMBER_MULTIGET_BYTES_READ, bytes_read);
RecordInHistogram(stats_, BYTES_PER_MULTIGET, bytes_read);
PERF_COUNTER_ADD(multiget_read_bytes, bytes_read);
PERF_TIMER_STOP(get_post_process_time);
CO_RETURN s;
}
DEFINE_SYNC_AND_ASYNC(void, DBImpl::MultiGetCommon)
(const ReadOptions& read_options, const size_t num_keys,
ColumnFamilyHandle** column_families, const Slice* keys, PinnableSlice* values,
PinnableWideColumns* columns, std::string* timestamps, Status* statuses,
const bool sorted_input) {
if (num_keys == 0) {
CO_RETURN;
}
bool should_fail = false;
for (size_t i = 0; i < num_keys; ++i) {
ColumnFamilyHandle* cfh = column_families[i];
if (read_options.timestamp) {
statuses[i] = FailIfTsMismatchCf(cfh, *(read_options.timestamp));
if (!statuses[i].ok()) {
should_fail = true;
}
} else {
statuses[i] = FailIfCfHasTs(cfh);
if (!statuses[i].ok()) {
should_fail = true;
}
}
}
if (should_fail) {
for (size_t i = 0; i < num_keys; ++i) {
if (statuses[i].ok()) {
statuses[i] = Status::Incomplete(
"DB not queried due to invalid argument(s) in the same MultiGet");
}
}
CO_RETURN;
}
if (tracer_) {
// TODO: This mutex should be removed later, to improve performance when
// tracing is enabled.
InstrumentedMutexLock lock(&trace_mutex_);
if (tracer_) {
// TODO: maybe handle the tracing status?
tracer_->MultiGet(num_keys, column_families, keys).PermitUncheckedError();
}
}
autovector<KeyContext, MultiGetContext::MAX_BATCH_SIZE> key_context;
key_context.reserve(num_keys);
autovector<KeyContext*, MultiGetContext::MAX_BATCH_SIZE> sorted_keys;
sorted_keys.resize(num_keys);
for (size_t i = 0; i < num_keys; ++i) {
PinnableSlice* val = nullptr;
PinnableWideColumns* col = nullptr;
if (values) {
val = &values[i];
val->Reset();
} else {
assert(columns);
col = &columns[i];
col->Reset();
}
key_context.emplace_back(column_families[i], keys[i], val, col,
timestamps ? &timestamps[i] : nullptr,
&statuses[i]);
}
for (size_t i = 0; i < num_keys; ++i) {
sorted_keys[i] = &key_context[i];
}
PrepareMultiGetKeys(num_keys, sorted_input, &sorted_keys);
autovector<MultiGetKeyRangePerCf, MultiGetContext::MAX_BATCH_SIZE>
key_range_per_cf;
autovector<ColumnFamilySuperVersionPair, MultiGetContext::MAX_BATCH_SIZE>
cf_sv_pairs;
size_t cf_start = 0;
ColumnFamilyHandle* cf = sorted_keys[0]->column_family;
for (size_t i = 0; i < num_keys; ++i) {
KeyContext* key_ctx = sorted_keys[i];
if (key_ctx->column_family != cf) {
key_range_per_cf.emplace_back(cf_start, i - cf_start);
cf_sv_pairs.emplace_back(cf, nullptr);
cf_start = i;
cf = key_ctx->column_family;
}
}
key_range_per_cf.emplace_back(cf_start, num_keys - cf_start);
cf_sv_pairs.emplace_back(cf, nullptr);
SequenceNumber consistent_seqnum = kMaxSequenceNumber;
bool sv_from_thread_local = false;
#ifdef WITH_COROUTINES
// The coroutine read path may suspend mid-MultiGet and resume on a shared
// executor thread, which is incompatible with the thread-local SuperVersion
// cache: it marks the thread's slot kSVInUse for the duration of the read, so
// a second coroutine resuming on the same thread would trip the kSVInUse
// assertion. Take an independent reference instead, which releases the
// thread-local slot before any suspension point.
constexpr bool kExtraSvRef = true;
#else
constexpr bool kExtraSvRef = false;
#endif
Status s = MultiCFSnapshot<autovector<ColumnFamilySuperVersionPair,
MultiGetContext::MAX_BATCH_SIZE>>(
read_options, nullptr,
[](autovector<ColumnFamilySuperVersionPair,
MultiGetContext::MAX_BATCH_SIZE>::iterator& cf_iter) {
return &(*cf_iter);
},
&cf_sv_pairs, kExtraSvRef, &consistent_seqnum, &sv_from_thread_local);
if (!s.ok()) {
for (size_t i = 0; i < num_keys; ++i) {
if (statuses[i].ok()) {
statuses[i] = s;
}
}
CO_RETURN;
}
GetWithTimestampReadCallback timestamp_read_callback(0);
ReadCallback* read_callback = nullptr;
if (read_options.timestamp && read_options.timestamp->size() > 0) {
timestamp_read_callback.Refresh(consistent_seqnum);
read_callback = &timestamp_read_callback;
}
assert(key_range_per_cf.size() == cf_sv_pairs.size());
auto key_range_per_cf_iter = key_range_per_cf.begin();
auto cf_sv_pair_iter = cf_sv_pairs.begin();
while (key_range_per_cf_iter != key_range_per_cf.end() &&
cf_sv_pair_iter != cf_sv_pairs.end()) {
s = CO_AWAIT(MultiGetImpl, read_options, key_range_per_cf_iter->start,
key_range_per_cf_iter->num_keys, &sorted_keys,
cf_sv_pair_iter->super_version, consistent_seqnum,
read_callback);
if (!s.ok()) {
break;
}
++key_range_per_cf_iter;
++cf_sv_pair_iter;
}
if (!s.ok()) {
assert(s.IsTimedOut() || s.IsAborted());
for (++key_range_per_cf_iter;
key_range_per_cf_iter != key_range_per_cf.end();
++key_range_per_cf_iter) {
for (size_t i = key_range_per_cf_iter->start;
i < key_range_per_cf_iter->start + key_range_per_cf_iter->num_keys;
++i) {
*sorted_keys[i]->s = s;
}
}
}
for (const auto& cf_sv_pair : cf_sv_pairs) {
if (sv_from_thread_local && !kExtraSvRef) {
ReturnAndCleanupSuperVersion(cf_sv_pair.cfd, cf_sv_pair.super_version);
} else {
TEST_SYNC_POINT("DBImpl::MultiCFSnapshot::BeforeLastTryUnRefSV");
CleanupSuperVersion(cf_sv_pair.super_version);
}
}
}
DEFINE_SYNC_AND_ASYNC(void, DBImpl::MultiGet)
(const ReadOptions& _read_options, const size_t num_keys,
ColumnFamilyHandle** column_families, const Slice* keys, PinnableSlice* values,
std::string* timestamps, Status* statuses, const bool sorted_input) {
#ifdef WITH_COROUTINES
INSTALL_COROUTINE_STATS_CONTEXT_SCOPE(
immutable_db_options_.fs->GetReadExecutor(), immutable_db_options_.env);
#endif
if (_read_options.io_activity != Env::IOActivity::kUnknown &&
_read_options.io_activity != Env::IOActivity::kMultiGet) {
Status s = Status::InvalidArgument(
"Can only call MultiGet with `ReadOptions::io_activity` is "
"`Env::IOActivity::kUnknown` or `Env::IOActivity::kMultiGet`");
for (size_t i = 0; i < num_keys; ++i) {
if (statuses[i].ok()) {
statuses[i] = s;
}
}
CO_RETURN;
}
ReadOptions read_options(_read_options);
if (read_options.io_activity == Env::IOActivity::kUnknown) {
read_options.io_activity = Env::IOActivity::kMultiGet;
}
CO_AWAIT(MultiGetCommon, read_options, num_keys, column_families, keys,
values,
/* columns */ nullptr, timestamps, statuses, sorted_input);
CO_RETURN;
}
} // namespace ROCKSDB_NAMESPACE
#endif
Loaded 100 of 370 files, more files were not shown because too many files have changed in this diff. Show more