mirror of
https://github.com/facebook/rocksdb.git
synced 2026-11-07 03:22:34 -05:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ef3dd12e9a | ||
|
|
dec67990f0 | ||
|
|
9b4c5422f0 | ||
|
|
7292adcc9a | ||
|
|
6b15f1643e | ||
|
|
a38cd3a439 | ||
|
|
45203a867f | ||
|
|
0561153b73 | ||
|
|
1c490a4a4d | ||
|
|
60f090647d | ||
|
|
5b77e34985 | ||
|
|
3ea1ec56df | ||
|
|
f16157cfc5 | ||
|
|
c83a84e98c | ||
|
|
c0512c4c34 | ||
|
|
5f1132b884 | ||
|
|
c2b86f3ec0 | ||
|
|
8585299552 | ||
|
|
866e8e9f06 | ||
|
|
19b6f85266 | ||
|
|
4cd0450f31 | ||
|
|
b58cbcf13c | ||
|
|
4d180247ae | ||
|
|
ded3cb72a5 | ||
|
|
aeebcbded4 | ||
|
|
11516577ab | ||
|
|
9d358e63d6 | ||
|
|
31675ca6d0 | ||
|
|
ff29163e47 | ||
|
|
176d7c7ea1 | ||
|
|
b4e068e1ed | ||
|
|
eed2f96676 | ||
|
|
5fa16200aa | ||
|
|
7510773057 | ||
|
|
5eed79a0e1 | ||
|
|
3d381e1bd4 | ||
|
|
f8d3141e5c | ||
|
|
4052fccde9 | ||
|
|
ac30c4d738 | ||
|
|
dbc2db5228 | ||
|
|
07cbacadb4 | ||
|
|
662cdbc9ec | ||
|
|
ffd4ac31af | ||
|
|
0675830967 | ||
|
|
14a82121d4 | ||
|
|
507206e46b | ||
|
|
3c30d43baf | ||
|
|
96e7ef0269 | ||
|
|
5d6f321b70 | ||
|
|
256a699be3 | ||
|
|
7530287bde | ||
|
|
b03a058d61 | ||
|
|
8108b49e0c | ||
|
|
dd54c5abc9 | ||
|
|
7d721f398b | ||
|
|
bcf8711165 | ||
|
|
34d5074bfa | ||
|
|
79b58b0dd6 | ||
|
|
613a642b5c | ||
|
|
e231c1826c | ||
|
|
1419ae41b1 | ||
|
|
db114777b1 | ||
|
|
7a90dc5ba8 | ||
|
|
a4e298b8c4 | ||
|
|
576dc39899 | ||
|
|
4c2a977aa5 | ||
|
|
88a8fdf849 | ||
|
|
a844cbf5b7 | ||
|
|
3d8e4be2f5 | ||
|
|
7d3150ffce | ||
|
|
91b96f41cf | ||
|
|
dfde6a60b0 | ||
|
|
bcda8c4b1a | ||
|
|
37234200b5 | ||
|
|
ac0f4ae69f | ||
|
|
bec9dcec7c | ||
|
|
897162a6bc | ||
|
|
1ca38e1442 | ||
|
|
da3a0961fa | ||
|
|
96ed085402 | ||
|
|
2c1c7ea2f1 | ||
|
|
fe6406f7b2 | ||
|
|
0df7ed563b | ||
|
|
068aeda9d8 | ||
|
|
a0966fd94e | ||
|
|
fe5123681e | ||
|
|
f9c117e203 | ||
|
|
82dfd6a510 | ||
|
|
80a5a6e4b2 | ||
|
|
d699ffbd5c | ||
|
|
e4a7136d3e | ||
|
|
f7b791b213 | ||
|
|
6dbb6f30e6 | ||
|
|
bd16531142 | ||
|
|
e6a2ee0bd2 | ||
|
|
ad81b654a4 | ||
|
|
8f492b2f47 | ||
|
|
e8554f1b11 | ||
|
|
330ded5129 | ||
|
|
4b41ccd2a7 | ||
|
|
2846163d9e | ||
|
|
03b8d1afa0 | ||
|
|
42fca1bb39 | ||
|
|
d3a82f28ce | ||
|
|
d8536d3274 | ||
|
|
136d0d1fa1 | ||
|
|
49faa51e11 | ||
|
|
7d18ffe316 | ||
|
|
db1adf47bb | ||
|
|
bbdcd2825f | ||
|
|
495c21dc5c | ||
|
|
575b6df1b8 | ||
|
|
f0c1e3d7d9 | ||
|
|
b616b203b8 | ||
|
|
92a6308300 | ||
|
|
021374c62c | ||
|
|
9475798205 | ||
|
|
323d915dbc | ||
|
|
2dc6bc51b4 | ||
|
|
7217bf34a7 | ||
|
|
58d835d951 | ||
|
|
276495843d | ||
|
|
ec5106b3b8 | ||
|
|
f9e4c5c51f | ||
|
|
fcf382c95c | ||
|
|
66d7035708 | ||
|
|
9381544cd9 | ||
|
|
f8c601b91c | ||
|
|
5dfde1c262 | ||
|
|
44e0294c1d | ||
|
|
3f4d840e1a | ||
|
|
3949208acf | ||
|
|
88752298ff | ||
|
|
1dfa729793 | ||
|
|
8e1569b351 | ||
|
|
5fe225357a | ||
|
|
e8bbe08760 | ||
|
|
fd7399004f | ||
|
|
d1fbdffdae | ||
|
|
dc4006480b | ||
|
|
af0eae4de3 | ||
|
|
dbf9328c71 | ||
|
|
751bde0f7f | ||
|
|
14ecf7f13c | ||
|
|
b1b50fe102 | ||
|
|
cda4a73a19 | ||
|
|
00e73b99a2 | ||
|
|
460aea1523 | ||
|
|
4b35e9966c | ||
|
|
b7b6d7c8c0 | ||
|
|
afc922bf5f | ||
|
|
6e73763b8a | ||
|
|
f9df618e4d | ||
|
|
026f63de6c | ||
|
|
e2ccb78cf2 | ||
|
|
c64f682946 | ||
|
|
359d57be96 | ||
|
|
ba81144d8d | ||
|
|
4b9070bccb |
No files matched your search
@@ -20,9 +20,15 @@ runs:
|
||||
echo "GTEST_COLOR=1" >> "$GITHUB_ENV"
|
||||
echo "CTEST_OUTPUT_ON_FAILURE=1" >> "$GITHUB_ENV"
|
||||
echo "CTEST_TEST_TIMEOUT=300" >> "$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"
|
||||
# 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"
|
||||
shell: bash
|
||||
@@ -5,23 +5,40 @@
|
||||
// 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}) {
|
||||
return [
|
||||
`## ${icon} ${headerTitle}`,
|
||||
'',
|
||||
triggerLine,
|
||||
'',
|
||||
'---',
|
||||
'',
|
||||
responseBody,
|
||||
'',
|
||||
'---',
|
||||
'',
|
||||
'<details>',
|
||||
'<summary>ℹ️ About this response</summary>',
|
||||
'',
|
||||
...footerLines,
|
||||
'</details>',
|
||||
const assemble = (body) => [`## ${icon} ${headerTitle}`,
|
||||
'',
|
||||
triggerLine,
|
||||
'',
|
||||
'---',
|
||||
'',
|
||||
body,
|
||||
'',
|
||||
'---',
|
||||
'',
|
||||
'<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);
|
||||
};
|
||||
@@ -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/code_review.md`',
|
||||
'Review methodology: `claude_md/ci_review_prompt.md`',
|
||||
'',
|
||||
'**Limitations:**',
|
||||
'- Claude may miss context from files not in the diff',
|
||||
|
||||
@@ -83,7 +83,7 @@ module.exports = function parseCodex(
|
||||
responseBody,
|
||||
footerLines: [
|
||||
'Generated by Codex CLI.',
|
||||
'Review methodology: `claude_md/code_review.md`',
|
||||
'Review methodology: `claude_md/ci_review_prompt.md`',
|
||||
'',
|
||||
'**Limitations:**',
|
||||
'- Codex may miss context from files not in the diff',
|
||||
|
||||
@@ -12,6 +12,7 @@ jobs:
|
||||
labels: 4-core-ubuntu
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:24.1
|
||||
options: --shm-size=8gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
with:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
name: facebook/rocksdb/nightly
|
||||
name: facebook/rocksdb/nightly-candidate
|
||||
on: workflow_dispatch
|
||||
permissions: {}
|
||||
jobs:
|
||||
@@ -10,7 +10,7 @@ jobs:
|
||||
labels: arm64large
|
||||
container:
|
||||
image: ubuntu-2004:202111-02
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=8gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
- uses: "./.github/actions/pre-steps"
|
||||
|
||||
@@ -11,7 +11,7 @@ jobs:
|
||||
labels: 16-core-ubuntu
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:22.1
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=32gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
with:
|
||||
@@ -33,7 +33,7 @@ jobs:
|
||||
labels: 16-core-ubuntu
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:22.1
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=32gb
|
||||
env:
|
||||
TEST_TMPDIR: "/tmp/rocksdb_test_tmp"
|
||||
steps:
|
||||
@@ -47,7 +47,7 @@ jobs:
|
||||
labels: 16-core-ubuntu
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:24.1
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=32gb
|
||||
env:
|
||||
CC: clang-21
|
||||
CXX: clang++-21
|
||||
@@ -84,7 +84,7 @@ jobs:
|
||||
labels: 16-core-ubuntu
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:22.1
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=32gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
- uses: "./.github/actions/pre-steps"
|
||||
@@ -103,7 +103,7 @@ jobs:
|
||||
labels: 16-core-ubuntu
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:22.1
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=32gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
- uses: "./.github/actions/pre-steps"
|
||||
@@ -140,7 +140,17 @@ 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
|
||||
- run: sudo dd bs=1048576 count=4096 if=/dev/zero of=/swapfile && sudo chmod 600 /swapfile && sudo mkswap /swapfile && sudo swapon /swapfile
|
||||
- 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: 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
|
||||
@@ -151,7 +161,7 @@ jobs:
|
||||
labels: 4-core-ubuntu
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:22.1
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=8gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
- uses: "./.github/actions/pre-steps"
|
||||
@@ -164,7 +174,7 @@ jobs:
|
||||
labels: 4-core-ubuntu
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:24.1
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=8gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
- uses: "./.github/actions/pre-steps"
|
||||
@@ -179,7 +189,7 @@ jobs:
|
||||
labels: 16-core-ubuntu
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:22.1
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=32gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
- uses: "./.github/actions/pre-steps"
|
||||
|
||||
@@ -65,7 +65,9 @@ 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
|
||||
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
|
||||
# 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
|
||||
- name: Check format
|
||||
run: VERBOSE_CHECK=1 make check-format
|
||||
- name: Compare buckify output
|
||||
@@ -90,7 +92,7 @@ jobs:
|
||||
labels: 16-core-ubuntu
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:22.1
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=32gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
- uses: "./.github/actions/pre-steps"
|
||||
@@ -108,7 +110,7 @@ jobs:
|
||||
labels: 4-core-ubuntu
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:24.1
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=8gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
- uses: "./.github/actions/pre-steps"
|
||||
@@ -133,7 +135,7 @@ jobs:
|
||||
labels: 32-core-ubuntu
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:22.1
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=64gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
- uses: "./.github/actions/pre-steps"
|
||||
@@ -158,7 +160,7 @@ jobs:
|
||||
labels: 16-core-ubuntu
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:22.1
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=32gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
- uses: "./.github/actions/pre-steps"
|
||||
@@ -178,7 +180,7 @@ jobs:
|
||||
labels: 32-core-ubuntu
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:22.1
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=64gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
- uses: "./.github/actions/pre-steps"
|
||||
@@ -207,7 +209,7 @@ jobs:
|
||||
shard: [0, 1, 2, 3]
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:22.1
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=32gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
- uses: "./.github/actions/pre-steps"
|
||||
@@ -230,7 +232,7 @@ jobs:
|
||||
labels: 16-core-ubuntu
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:22.1
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=32gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
- uses: "./.github/actions/pre-steps"
|
||||
@@ -250,7 +252,7 @@ jobs:
|
||||
labels: 16-core-ubuntu
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:22.1
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=32gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
- uses: "./.github/actions/setup-ccache"
|
||||
@@ -304,7 +306,7 @@ jobs:
|
||||
labels: 16-core-ubuntu
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:24.1
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=32gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
- uses: "./.github/actions/pre-steps"
|
||||
@@ -320,16 +322,46 @@ 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 '*'
|
||||
git fetch --no-tags --depth=1 origin main
|
||||
|
||||
# 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
|
||||
|
||||
CXX=clang++-21 make check-c-api-gen \
|
||||
CHECK_C_API_GEN_STRICT=1 \
|
||||
API_COMPAT_REF=FETCH_HEAD \
|
||||
API_COMPAT_REF="$api_compat_ref" \
|
||||
CLANG_FORMAT_BINARY=clang-format-21
|
||||
- uses: "./.github/actions/teardown-ccache"
|
||||
if: always()
|
||||
@@ -341,7 +373,7 @@ jobs:
|
||||
labels: 16-core-ubuntu
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:24.1
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=32gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
- uses: "./.github/actions/pre-steps"
|
||||
@@ -362,7 +394,7 @@ jobs:
|
||||
labels: 4-core-ubuntu
|
||||
container:
|
||||
image: gcc:latest
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=8gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
- run: apt-get update -y && apt-get install -y libgflags-dev
|
||||
@@ -390,17 +422,24 @@ jobs:
|
||||
crash_duration: 240
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:22.1
|
||||
options: --shm-size=16gb --ulimit nofile=1048576:1048576
|
||||
options: --shm-size=8gb --ulimit nofile=1048576:1048576
|
||||
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)"
|
||||
make V=1 -j8 CRASH_TEST_EXT_ARGS='--duration=${{ matrix.crash_duration }} --max_key=2500000' ${{ matrix.crash_test_target }}
|
||||
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 }}
|
||||
- uses: "./.github/actions/teardown-ccache"
|
||||
if: always()
|
||||
- uses: "./.github/actions/post-steps"
|
||||
@@ -418,7 +457,7 @@ jobs:
|
||||
shard: [0, 1, 2]
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:24.1
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=64gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
- uses: "./.github/actions/pre-steps"
|
||||
@@ -445,7 +484,7 @@ jobs:
|
||||
shard: [0, 1, 2]
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:24.1
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=64gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
- uses: "./.github/actions/pre-steps"
|
||||
@@ -468,7 +507,7 @@ jobs:
|
||||
labels: 16-core-ubuntu
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:22.1
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=32gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
- uses: "./.github/actions/pre-steps"
|
||||
@@ -575,7 +614,7 @@ jobs:
|
||||
labels: 4-core-ubuntu
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:22.1
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=8gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
- uses: "./.github/actions/pre-steps"
|
||||
@@ -598,7 +637,7 @@ jobs:
|
||||
labels: 4-core-ubuntu
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:22.1
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=8gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
- uses: "./.github/actions/pre-steps"
|
||||
@@ -701,7 +740,7 @@ jobs:
|
||||
labels: 4-core-ubuntu
|
||||
container:
|
||||
image: evolvedbinary/rocksjava:alpine3_x64-be
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=8gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
- uses: "./.github/actions/install-maven"
|
||||
|
||||
@@ -12,7 +12,7 @@ jobs:
|
||||
timeout-minutes: 840
|
||||
container:
|
||||
image: ghcr.io/facebook/rocksdb_ubuntu:22.1
|
||||
options: --shm-size=16gb
|
||||
options: --shm-size=32gb
|
||||
steps:
|
||||
- uses: actions/checkout@v4.1.0
|
||||
- uses: "./.github/actions/pre-steps"
|
||||
|
||||
@@ -59,6 +59,7 @@ 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",
|
||||
@@ -95,6 +96,7 @@ cpp_library_wrapper(name="rocksdb_lib", srcs=[
|
||||
"db/merge_operator.cc",
|
||||
"db/multi_scan.cc",
|
||||
"db/output_validator.cc",
|
||||
"db/periodic_compaction_phaser.cc",
|
||||
"db/periodic_task_scheduler.cc",
|
||||
"db/range_del_aggregator.cc",
|
||||
"db/range_tombstone_fragmenter.cc",
|
||||
@@ -103,7 +105,6 @@ 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,7 +112,9 @@ 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",
|
||||
@@ -203,6 +206,7 @@ cpp_library_wrapper(name="rocksdb_lib", srcs=[
|
||||
"table/block_based/block_cache.cc",
|
||||
"table/block_based/block_prefetcher.cc",
|
||||
"table/block_based/block_prefix_index.cc",
|
||||
"table/block_based/builtin_index_factory.cc",
|
||||
"table/block_based/data_block_footer.cc",
|
||||
"table/block_based/data_block_hash_index.cc",
|
||||
"table/block_based/filter_block_reader_common.cc",
|
||||
@@ -237,6 +241,7 @@ cpp_library_wrapper(name="rocksdb_lib", srcs=[
|
||||
"table/plain/plain_table_index.cc",
|
||||
"table/plain/plain_table_key_coding.cc",
|
||||
"table/plain/plain_table_reader.cc",
|
||||
"table/range_del_block.cc",
|
||||
"table/sst_file_dumper.cc",
|
||||
"table/sst_file_reader.cc",
|
||||
"table/sst_file_writer.cc",
|
||||
@@ -411,13 +416,27 @@ cpp_library_wrapper(name="rocksdb_test_lib", srcs=[
|
||||
"table/mock_table.cc",
|
||||
"test_util/mock_time_env.cc",
|
||||
"test_util/secondary_cache_test_util.cc",
|
||||
"test_util/simple_external_table_factory.cc",
|
||||
"test_util/testharness.cc",
|
||||
"test_util/testutil.cc",
|
||||
"tools/block_cache_analyzer/block_cache_trace_analyzer.cc",
|
||||
"tools/trace_analyzer_tool.cc",
|
||||
"utilities/agg_merge/test_agg_merge.cc",
|
||||
"utilities/cassandra/test_utils.cc",
|
||||
], deps=[":rocksdb_lib"], headers=[], link_whole=False, extra_test_libs=True)
|
||||
], deps=[":rocksdb_lib"], headers=[
|
||||
"db/db_test_util.h",
|
||||
"db/db_with_timestamp_test_util.h",
|
||||
"table/mock_table.h",
|
||||
"test_util/mock_time_env.h",
|
||||
"test_util/secondary_cache_test_util.h",
|
||||
"test_util/simple_external_table_factory.h",
|
||||
"test_util/testharness.h",
|
||||
"test_util/testutil.h",
|
||||
"tools/block_cache_analyzer/block_cache_trace_analyzer.h",
|
||||
"tools/trace_analyzer_tool.h",
|
||||
"utilities/agg_merge/test_agg_merge.h",
|
||||
"utilities/cassandra/test_utils.h",
|
||||
], link_whole=False, extra_test_libs=True)
|
||||
|
||||
cpp_library_wrapper(name="rocksdb_with_faiss_test_lib", srcs=[
|
||||
"db/db_test_util.cc",
|
||||
@@ -425,13 +444,27 @@ cpp_library_wrapper(name="rocksdb_with_faiss_test_lib", srcs=[
|
||||
"table/mock_table.cc",
|
||||
"test_util/mock_time_env.cc",
|
||||
"test_util/secondary_cache_test_util.cc",
|
||||
"test_util/simple_external_table_factory.cc",
|
||||
"test_util/testharness.cc",
|
||||
"test_util/testutil.cc",
|
||||
"tools/block_cache_analyzer/block_cache_trace_analyzer.cc",
|
||||
"tools/trace_analyzer_tool.cc",
|
||||
"utilities/agg_merge/test_agg_merge.cc",
|
||||
"utilities/cassandra/test_utils.cc",
|
||||
], deps=[":rocksdb_with_faiss_lib"], headers=[], link_whole=False, extra_test_libs=True)
|
||||
], deps=[":rocksdb_with_faiss_lib"], headers=[
|
||||
"db/db_test_util.h",
|
||||
"db/db_with_timestamp_test_util.h",
|
||||
"table/mock_table.h",
|
||||
"test_util/mock_time_env.h",
|
||||
"test_util/secondary_cache_test_util.h",
|
||||
"test_util/simple_external_table_factory.h",
|
||||
"test_util/testharness.h",
|
||||
"test_util/testutil.h",
|
||||
"tools/block_cache_analyzer/block_cache_trace_analyzer.h",
|
||||
"tools/trace_analyzer_tool.h",
|
||||
"utilities/agg_merge/test_agg_merge.h",
|
||||
"utilities/cassandra/test_utils.h",
|
||||
], link_whole=False, extra_test_libs=True)
|
||||
|
||||
cpp_library_wrapper(name="rocksdb_tools_lib", srcs=[
|
||||
"test_util/testutil.cc",
|
||||
@@ -440,7 +473,12 @@ cpp_library_wrapper(name="rocksdb_tools_lib", srcs=[
|
||||
"tools/simulated_hybrid_file_system.cc",
|
||||
"tools/tool_hooks.cc",
|
||||
"tools/trace_analyzer_tool.cc",
|
||||
], deps=[":rocksdb_lib"], headers=[], link_whole=False, extra_test_libs=False)
|
||||
], deps=[":rocksdb_lib"], headers=[
|
||||
"test_util/testutil.h",
|
||||
"tools/block_cache_analyzer/block_cache_trace_analyzer.h",
|
||||
"tools/simulated_hybrid_file_system.h",
|
||||
"tools/trace_analyzer_tool.h",
|
||||
], link_whole=False, extra_test_libs=False)
|
||||
|
||||
cpp_library_wrapper(name="rocksdb_cache_bench_tools_lib", srcs=["cache/cache_bench_tool.cc"], deps=[":rocksdb_lib"], headers=[], link_whole=False, extra_test_libs=False)
|
||||
|
||||
@@ -464,10 +502,28 @@ rocks_cpp_library_wrapper(name="rocksdb_stress_lib", srcs=[
|
||||
"db_stress_tool/expected_value.cc",
|
||||
"db_stress_tool/multi_ops_txns_stress.cc",
|
||||
"db_stress_tool/no_batched_ops_stress.cc",
|
||||
"test_util/simple_external_table_factory.cc",
|
||||
"test_util/testutil.cc",
|
||||
"tools/block_cache_analyzer/block_cache_trace_analyzer.cc",
|
||||
"tools/trace_analyzer_tool.cc",
|
||||
], headers=[])
|
||||
], headers=[
|
||||
"db_stress_tool/db_stress_common.h",
|
||||
"db_stress_tool/db_stress_compaction_service.h",
|
||||
"db_stress_tool/db_stress_compression_manager.h",
|
||||
"db_stress_tool/db_stress_driver.h",
|
||||
"db_stress_tool/db_stress_filters.h",
|
||||
"db_stress_tool/db_stress_listener.h",
|
||||
"db_stress_tool/db_stress_shared_state.h",
|
||||
"db_stress_tool/db_stress_test_base.h",
|
||||
"db_stress_tool/db_stress_wide_merge_operator.h",
|
||||
"db_stress_tool/expected_state.h",
|
||||
"db_stress_tool/expected_value.h",
|
||||
"db_stress_tool/multi_ops_txns_stress.h",
|
||||
"test_util/simple_external_table_factory.h",
|
||||
"test_util/testutil.h",
|
||||
"tools/block_cache_analyzer/block_cache_trace_analyzer.h",
|
||||
"tools/trace_analyzer_tool.h",
|
||||
])
|
||||
|
||||
|
||||
cpp_binary_wrapper(name="ldb", srcs=["tools/ldb.cc"], deps=[":rocksdb_tools_lib"], extra_preprocessor_flags=[], extra_bench_libs=False)
|
||||
@@ -4611,6 +4667,12 @@ cpp_unittest_wrapper(name="bloom_test",
|
||||
extra_compiler_flags=[])
|
||||
|
||||
|
||||
cpp_unittest_wrapper(name="builtin_index_factory_test",
|
||||
srcs=["table/block_based/builtin_index_factory_test.cc"],
|
||||
deps=[":rocksdb_test_lib"],
|
||||
extra_compiler_flags=[])
|
||||
|
||||
|
||||
cpp_unittest_wrapper(name="cache_reservation_manager_test",
|
||||
srcs=["cache/cache_reservation_manager_test.cc"],
|
||||
deps=[":rocksdb_test_lib"],
|
||||
@@ -4751,6 +4813,7 @@ cpp_unittest_wrapper(name="compression_test",
|
||||
|
||||
cpp_unittest_wrapper(name="configurable_test",
|
||||
srcs=["options/configurable_test.cc"],
|
||||
source_headers=["options/configurable_test.h"],
|
||||
deps=[":rocksdb_test_lib"],
|
||||
extra_compiler_flags=[])
|
||||
|
||||
@@ -4947,6 +5010,12 @@ 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"],
|
||||
@@ -5449,6 +5518,7 @@ cpp_unittest_wrapper(name="periodic_task_scheduler_test",
|
||||
|
||||
cpp_unittest_wrapper(name="persistent_cache_test",
|
||||
srcs=["utilities/persistent_cache/persistent_cache_test.cc"],
|
||||
source_headers=["utilities/persistent_cache/persistent_cache_test.h"],
|
||||
deps=[":rocksdb_test_lib"],
|
||||
extra_compiler_flags=[])
|
||||
|
||||
@@ -5467,6 +5537,7 @@ cpp_unittest_wrapper(name="point_lock_manager_stress_test",
|
||||
|
||||
cpp_unittest_wrapper(name="point_lock_manager_test",
|
||||
srcs=["utilities/transactions/lock/point/point_lock_manager_test.cc"],
|
||||
source_headers=["utilities/transactions/lock/point/point_lock_manager_test.h"],
|
||||
deps=[":rocksdb_test_lib"],
|
||||
extra_compiler_flags=[])
|
||||
|
||||
@@ -5677,6 +5748,7 @@ cpp_unittest_wrapper(name="trace_analyzer_test",
|
||||
|
||||
cpp_unittest_wrapper(name="transaction_test",
|
||||
srcs=["utilities/transactions/transaction_test.cc"],
|
||||
source_headers=["utilities/transactions/transaction_test.h"],
|
||||
deps=[":rocksdb_test_lib"],
|
||||
extra_compiler_flags=[])
|
||||
|
||||
|
||||
@@ -8,12 +8,18 @@ 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.
|
||||
|
||||
**Error Handling:** Ensure robust error handling throughout the codebase. Use RocksDB's `Status` type consistently, propagate errors appropriately, and avoid silently ignoring failures. Reviewers pay close attention to edge cases and failure modes.
|
||||
|
||||
**Refactoring traps:** At least in production code, avoid constructs that could allow existing code to unexpectedly, quietly change meaning.
|
||||
Specifically:
|
||||
* Avoid new defaulted parameters. This is the #1 trap on refactoring!
|
||||
* Avoid static_cast, reinterpret_cast, and C-style casts; static_cast_with_check, up_cast, and lossless_cast from cast_util.h are preferred.
|
||||
* Avoid declared type `auto` (`auto&`, `auto*` OK).
|
||||
|
||||
### Testing Philosophy
|
||||
|
||||
**Comprehensive Coverage:** Every change should include appropriate test coverage. This includes unit tests for isolated functionality, integration tests for component interactions, and stress tests for concurrency and performance validation. Reviewers will ask for additional tests if coverage is insufficient.
|
||||
@@ -32,7 +38,7 @@ This document provides guidance for generating and reviewing code in the RocksDB
|
||||
|
||||
**Memory Copy:** Avoid unnecessary memory copies. Use move semantics, `std::string_view`, `Slice`, and pass-by-reference where appropriate. Be aware of implicit copies in STL containers and function returns. Prefer in-place operations over copy-and-modify patterns.
|
||||
|
||||
**CPU Cache Efficiency:** Design data structures and access patterns to be cache-friendly. Keep frequently accessed data together (data locality). Prefer sequential memory access over random access. Be mindful of cache line sizes (typically 64 bytes) and avoid false sharing in concurrent code. Consider struct packing and field ordering to improve cache utilization.
|
||||
**CPU Cache Efficiency:** Design data structures and access patterns to be cache-friendly. Keep frequently accessed data together (data locality). Prefer sequential memory access over random access. Be mindful of cache line sizes (CACHE_LINE_SIZE, typically 64 bytes) and avoid false sharing in concurrent code (see CacheAlignedWrapper). Especially when adding new data members, be mindful of ordering within structs and classes to reduce unnecessary padding (special care with bool members) and avoid larger-than-necessary types (e.g. prefer OptSlice to std::optional<Slice>).
|
||||
|
||||
**Loop Optimization:** Look for opportunities to collapse nested loops, reduce loop overhead, and minimize branch mispredictions. Hoist invariant computations out of loops. Consider loop unrolling for tight inner loops. Batch operations when possible to amortize per-operation overhead.
|
||||
|
||||
@@ -47,15 +53,17 @@ This document provides guidance for generating and reviewing code in the RocksDB
|
||||
- **Cold path** (executed rarely, e.g., DB open, configuration parsing, error handling): Maintainability and clarity are more important. Prefer readable code over micro-optimizations. Complex optimizations here add maintenance burden with negligible performance benefit.
|
||||
- **Warm path** (moderate frequency): Balance both concerns. Use profiling data to guide optimization decisions.
|
||||
|
||||
**Avoid Premature Optimization:** While performance is critical, focus on correctness first, then optimize based on profiling data. However, be performance-aware from the start—choosing the right algorithm and data structure upfront is not premature optimization. Use the hot path analysis above to decide how much optimization effort is warranted.
|
||||
**Avoid Premature Optimization:** Performance is known critical in places like inner loops of compaction, read path and write path. Elsewhere, try to find a "holy trinity" solution of *correct, simple, and reasonably efficient*. More complex solutions are only appropriate when profiling/benchmarking data shows a measurable payoff.
|
||||
|
||||
### API Design and Compatibility
|
||||
|
||||
**Backwards Compatibility:** RocksDB maintains strong backwards compatibility guarantees. Breaking changes are rare and require extensive justification. When deprecating features, follow the project's deprecation policy (typically spanning multiple releases).
|
||||
|
||||
**Behavioral Compatibility:** Behavior changes are human judgment calls that must be intentional, well-documented (including release notes), and well researched for potential downstream production impact. Agents and reviewers must call out potential gaps, ambiguity, or adverse impacts in intentionality, documentation, and production impact. For an existing accepted input—including an undocumented, discouraged, or historically ignored value—the analysis should compare old and new observable behavior, including performance and resource impact, identify known direct callers and stored configurations, and add or update regression coverage as appropriate.
|
||||
|
||||
**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. Include usage examples, parameter descriptions, and notes on thread safety, performance characteristics, and compatibility considerations.
|
||||
**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.
|
||||
|
||||
---
|
||||
|
||||
@@ -73,7 +81,7 @@ The database core handles write-ahead logging (WAL), memtables, compaction, and
|
||||
|
||||
**Testing:** Database core changes require extensive testing, including unit tests, integration tests, and stress tests. Test with various configurations, compaction styles, and concurrent workloads.
|
||||
|
||||
### Public Headers (`include`)
|
||||
### Public Headers / "Public API" (`include/rocksdb/`)
|
||||
|
||||
Public headers define RocksDB's API surface. Changes here have the highest compatibility impact.
|
||||
|
||||
@@ -236,6 +244,11 @@ from an implementation detail instead of an explicit option.
|
||||
|
||||
## Important tips
|
||||
|
||||
### Pull request and diff summaries
|
||||
* Before writing or updating an external RocksDB pull request summary or its
|
||||
corresponding internal Phabricator diff summary, read and follow
|
||||
`claude_md/pull_request_summary_guideline.md`.
|
||||
|
||||
### Build system
|
||||
* There are 3 build system. Make for git clones, BUCK (meta internal) for hg
|
||||
clones, and CMake for some special cases.
|
||||
@@ -259,6 +272,10 @@ 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
|
||||
@@ -298,6 +315,7 @@ 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 |
|
||||
@@ -312,6 +330,12 @@ 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
|
||||
@@ -362,6 +386,9 @@ rather than relying on libstdc++ transitive includes.
|
||||
### Adding new public API
|
||||
Refer to claude_md/add_public_api.md
|
||||
|
||||
### Changing existing public API behavior
|
||||
Follow the Behavioral Compatibility requirements above.
|
||||
|
||||
### Adding new option
|
||||
Refer to claude_md/add_option.md
|
||||
|
||||
@@ -389,6 +416,11 @@ rather than relying on libstdc++ transitive includes.
|
||||
|
||||
### 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
|
||||
tried 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.
|
||||
|
||||
@@ -402,7 +434,9 @@ rather than relying on libstdc++ transitive includes.
|
||||
multiple minutes.
|
||||
* Run `AUTO_CLEAN=1 ASSERT_STATUS_CHECKED=1 make check` to verify all Status
|
||||
objects are properly checked. This catches missing error handling that can
|
||||
lead to silent data corruption.
|
||||
lead to silent data corruption. Merely building with ASSERT_STATUS_CHECKED=1
|
||||
accomplishes nothing; it enables a runtime check. New unit tests missing
|
||||
Status checks is a common failure point, even from agents.
|
||||
|
||||
### Monitoring make check progress
|
||||
* Use `make check-progress` to get machine-parseable JSON progress while
|
||||
|
||||
+9
-1
@@ -801,6 +801,7 @@ 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
|
||||
@@ -837,6 +838,7 @@ set(SOURCES
|
||||
db/merge_operator.cc
|
||||
db/multi_scan.cc
|
||||
db/output_validator.cc
|
||||
db/periodic_compaction_phaser.cc
|
||||
db/periodic_task_scheduler.cc
|
||||
db/range_del_aggregator.cc
|
||||
db/range_tombstone_fragmenter.cc
|
||||
@@ -845,7 +847,6 @@ 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,7 +854,9 @@ 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
|
||||
@@ -935,6 +938,7 @@ set(SOURCES
|
||||
table/block_based/block_cache.cc
|
||||
table/block_based/block_prefetcher.cc
|
||||
table/block_based/block_prefix_index.cc
|
||||
table/block_based/builtin_index_factory.cc
|
||||
table/block_based/data_block_hash_index.cc
|
||||
table/block_based/data_block_footer.cc
|
||||
table/block_based/filter_block_reader_common.cc
|
||||
@@ -968,6 +972,7 @@ set(SOURCES
|
||||
table/plain/plain_table_index.cc
|
||||
table/plain/plain_table_key_coding.cc
|
||||
table/plain/plain_table_reader.cc
|
||||
table/range_del_block.cc
|
||||
table/sst_file_dumper.cc
|
||||
table/sst_file_reader.cc
|
||||
table/sst_file_writer.cc
|
||||
@@ -1560,6 +1565,7 @@ 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
|
||||
@@ -1591,6 +1597,7 @@ if(WITH_TESTS)
|
||||
options/options_test.cc
|
||||
table/block_based/block_based_table_reader_test.cc
|
||||
table/block_based/block_test.cc
|
||||
table/block_based/builtin_index_factory_test.cc
|
||||
table/block_based/data_block_hash_index_test.cc
|
||||
table/block_based/full_filter_block_test.cc
|
||||
table/block_based/partitioned_filter_block_test.cc
|
||||
@@ -1682,6 +1689,7 @@ if(WITH_TESTS)
|
||||
db/db_with_timestamp_test_util.cc
|
||||
monitoring/thread_status_updater_debug.cc
|
||||
table/mock_table.cc
|
||||
test_util/simple_external_table_factory.cc
|
||||
utilities/agg_merge/test_agg_merge.cc
|
||||
utilities/cassandra/test_utils.cc
|
||||
)
|
||||
|
||||
+126
@@ -1,6 +1,132 @@
|
||||
# Rocksdb Change Log
|
||||
> NOTE: Entries for next release do not go here. Follow instructions in `unreleased_history/README.txt`
|
||||
|
||||
## 11.12.0 (10/07/2026)
|
||||
### New Features
|
||||
* Added `FullExternalTableFactory` and related full-mode external table APIs that preserve RocksDB internal keys, enabling external tables to support nonzero sequence numbers, point and single deletions, merge operands, blob indexes, wide-column entities, snapshots, live DB writes, and multi-level compactions.
|
||||
|
||||
### Public API Changes
|
||||
* Added experimental coroutine capability interfaces for basic and full `ExternalTableReader` implementations. Coroutine-capable external readers can initiate file reads through `FSRandomAccessFile::SubmitReadAsync()`.
|
||||
* `ExternalTableFactory::NewTableReader()` now receives an already-opened `FSRandomAccessFile` and its file size instead of requiring implementations to reopen `file_path`. The supplied file preserves RocksDB's direct-I/O alignment handling, rate limiting, read statistics and listener notifications, prefetching, and synchronous, asynchronous, and batched reads.
|
||||
* Added `PutRangeDeletionBlock()`, `GetRangeDeletionBlock()`, and `IsDeleteRangeSupported()` to the external table interfaces so formats can opt in to range deletions using RocksDB's raw range-deletion metadata block.
|
||||
* Opaque `PreparedFileInfo` metadata can now be serialized to a checksummed representation with `SerializePreparedFileInfo()` and restored with `DeserializePreparedFileInfo()` for reuse across processes.
|
||||
* Removed the deprecated `IngestExternalFileOptions::write_global_seqno` option and its C, Java, and `ldb` APIs, `TableProperties::external_sst_file_global_seqno_offset`, and the `file_offset` output from `ExternalTableReader::GetPropertiesBlock()`. Existing external SST files whose global sequence number was rewritten without updating the properties-block checksum remain readable.
|
||||
* `TablePropertiesNames` has no apparent use in the public API so has been deprecated there.
|
||||
* `TableProperties::creation_time` is renamed to `oldest_ancestor_time`, which better describes its meaning, along with `TablePropertiesNames::kCreationTime` to `kOldestAncestorTime`. The misspelled `SstFileMetaData::oldest_ancester_time` is renamed to `oldest_ancestor_time`. The old names remain available as deprecated aliases and will be removed in a future release.
|
||||
* Added `WriteBufferFlushPolicy` and `WriteBufferManager` policy selection for flushing the oldest or largest column family, including configurable batched flushing of the largest column families across DBs sharing a manager, with C and Java bindings.
|
||||
|
||||
### Behavior Changes
|
||||
* When `ExternalTableBuilderBase::PutPropertiesBlock()` returns `NotSupported`, RocksDB now overrides `num_entries`, `raw_key_size`, and `raw_value_size` from `ExternalTableBuilderBase::GetTableProperties()` with the logical totals tracked by the external-table adapter. Format-specific properties such as `data_size` remain unchanged.
|
||||
* The `FSWritableFile` passed to `ExternalTableFactory::NewTableBuilder()` now reports logical file size including RocksDB-buffered data and exposes the underlying file's direct-I/O mode and required buffer alignment.
|
||||
* `Iterator::Refresh()` now returns `NotSupported` on iterators from a secondary DB's `DB::NewIterators()` only, because those iterators are pinned to one cross-column-family read view. Iterators from `DB::NewIterator()` are unaffected; to advance a batch, call `DB::NewIterators()` again after `TryCatchUpWithPrimary()`.
|
||||
* `SstFileReader` now reports standard SST read statistics and file I/O listener notifications, and honors the configured read rate limiter.
|
||||
|
||||
### Bug Fixes
|
||||
* Fixed full recovery from retryable background errors to atomically advance WAL replay boundaries for all column families, preventing partial recovery of multi-column-family write batches after a failed recovery flush.
|
||||
* Fixed RocksDB builds on big-endian architectures such as s390x by disabling the optional persistent fault-injection log, whose binary format is little-endian-only.
|
||||
* Fixed `DB::ClipColumnFamily()` deleting a non-L0 SST file whose largest key equals `begin_key`, which lost keys at the start of the kept range.
|
||||
* Fixed swapped `oldest_key_time` and `newest_key_time` values in the `table_file_creation` event log entry.
|
||||
* Fixed `ExternalTableReader::VerifyChecksum()` results not being honored by the external table adapter.
|
||||
* Fixed a bug in manifest handling that could lead to a hang or memory corruption in the case of LSM sanity checks being fatally violated (exceptional; see `force_consistency_checks`).
|
||||
* Fixed `MultiGet()` with `ReadOptions::read_tier == kBlockCacheTier` reading data blocks from disk when `allow_mmap_reads` is false. Keys whose data block is not in the block cache now return `Status::Incomplete()`, the same as `Get()`.
|
||||
* Fixed trace replay (`DB::NewDefaultReplayer()`, db_bench `replay`) failing every read record (Get, MultiGet, iterator seek) on the default column family with `Corruption: Invalid Column Family ID` when the default column family handle was not passed, which is always the case in db_bench with `--num_column_families=1`.
|
||||
* Fixed multi-threaded `Replayer::Replay()` ignoring errors from executing trace records and returning OK. It now stops and returns the error, including `Status::NotSupported()` from executing a record, as single-threaded replay does.
|
||||
* Fixed secondary DB `NewIterators()` returning iterators from different database states or blocking for `TryCatchUpWithPrimary()` by serving the last completed catch-up view.
|
||||
|
||||
### Performance Improvements
|
||||
* Single Get coroutine reads using non-mmap, non-direct I/O on a `kFSBuffer`-capable `FileSystem` now use `FSRandomAccessFile::SubmitReadAsync()` instead of falling back to synchronous `Read()`. When rate-limited, these reads acquire their full token budget before submission to preserve a single filesystem-owned buffer, which can make physical I/O burstier than reads using caller-provided buffers.
|
||||
|
||||
## 11.11.0 (09/21/2026)
|
||||
### New Features
|
||||
* External tables now support DB-assigned global sequence numbers when `IngestExternalFileOptions::allow_global_seqno` is enabled, allowing overlapping external tables to be ingested across multiple levels when compactions are disabled. This includes the deprecated `write_global_seqno` path when the reader supplies the properties block's file offset.
|
||||
* Added checksum handoff support for SST file writes when `BlockBasedTableOptions::checksum` is `kCRC32c`, allowing block and trailer CRC32C checksums to be passed from the table builder to the file writer for buffered-data validation and filesystem in-flight write protection.
|
||||
* Enhanced `sst_dump --command=recompress` to be more powerful for benchmarking, including through automation with a new `--json` option for machine-readable output.
|
||||
|
||||
### Public API Changes
|
||||
* Changed the experimental async read statistics API by removing `DB::AsyncCallback::EnableStats()` and changing `OnComplete(const PerfContext*, const IOStatsContext*)` to `OnComplete()`. Callers must configure TLS statistics before each async or coroutine read. `DB::GetAsync()` and `DB::MultiGetAsync()` callbacks must copy per-operation statistics from TLS during `OnComplete()`; coroutine users must copy them from inside a `CoroStackableDB` hook before suspending again. Each operation leaves TLS statistics collection disabled.
|
||||
* Added `Compressor::MaybeOverrideCompressionOptions()` (EXPERIMENTAL), an omnibus hook letting a custom compressor adjust the subset of `CompressionOptions` that the SST builder applies rather than the compressor itself: `parallel_threads`, `max_compressed_bytes_per_kb`, `auto_skip`, and `auto_skip_min_sample_every` (and potentially more in the future). This deprecates `Compressor::GetRecommendedParallelThreads()`, which it subsumes; the default implementation still honors an overridden `GetRecommendedParallelThreads()` for compatibility.
|
||||
* Added experimental `CoroDB::CoGet()` and `CoroDB::CoMultiGet()` overloads for point reads from an `SstFileReader`.
|
||||
* Added experimental `DB::GetWithMetadata()` and `DB::MultiGetWithMetadata()` APIs with opt-in output metadata for key timestamps and explicit-snapshot newer-version detection.
|
||||
* Added a `DB::NewIterators()` overload that accepts parallel vectors of `ReadOptions` and column family handles, allowing each returned iterator to use independent read settings while sharing a consistent database state. The vectors must have the same size, all snapshots must be null or identical, and all `tailing` settings must match.
|
||||
* Added `ReadOptions::custom_context`, an opaque, non-owning pointer passed through table reads so external table implementations can consume application-defined read options.
|
||||
|
||||
### Behavior Changes
|
||||
* `ExternalTableReader::MultiGet()` is now used by RocksDB's `DB::MultiGet()` path. Previously, the external table adapter used `TableReader`'s fallback, which called `ExternalTableReader::Get()` separately for each key.
|
||||
* `DB::OpenAndCompact()` now requires `output_directory` to be a simple name for a new subdirectory when the new `use_session_tmp_dir_for_remote_compaction` DB option is enabled. The option places that subdirectory under the canonical `<dbname>/session_tmp/` root, and `DB::Open()` deletes stale contents under the root after recovery. The disabled default preserves the existing `<dbname>/<output_directory>` layout without automatic cleanup. Previously, remote-compaction output directories were created directly under `<dbname>`, which made it challenging to safely identify and delete obsolete files.
|
||||
* Several block-based SST table properties now better support compression benchmarking and optimization: `uncompressed_data_size` is now persisted in the file (previously it was computed only at write time and read back as 0); a new `lsm_info_at_creation` property records the LSM level and "bottommost" status at the file's creation, distinguishing "not applicable" (e.g. SstFileWriter files) from "unknown" (older files); and the `compression_options` property now records the full compression manager configuration instead of only its name.
|
||||
|
||||
### Bug Fixes
|
||||
* Fixed a usually-minor performance bug where `Cache::ApplyToAllEntries()` used single-entry batches instead of the intended 256-entry default for `ApplyToAllEntriesOptions::average_entries_per_lock`. All of the Cache implementations (LRU and HCC) benefit from the fix, but the disfavored LRU cache was especially impacted by repeated mutex acquisition and release.
|
||||
* Fixed stats-disabled coroutine and asynchronous reads inheriting enabled TLS statistics state when interleaved with stats-enabled reads on the same executor. Each read now uses its captured per-call configuration, while enabled request counters remain isolated across suspensions.
|
||||
* Fixed a bug where a remote compaction (`CompactionService` / `DB::OpenAndCompact`) requested with `OpenAndCompactOptions::allow_resumption=true` but for which resumption was internally disabled (incompatible with `paranoid_file_checks` or output-iteration verification) could fail a retried attempt, because the output directory was not cleaned before starting fresh and output files left by a previously interrupted attempt collided with the reused file numbers.
|
||||
* Fixed a bug where a remote compaction (`CompactionService` / `DB::OpenAndCompact`) could fail when the primary rotated its MANIFEST while the worker was opening the primary's directory read-only. The open reads `CURRENT`, and the primary publishes a new MANIFEST by renaming a freshly written `CURRENT` over the old one; on file systems without POSIX read-after-unlink semantics (remote/object stores) the replaced object is then reported as gone (`PathNotFound`/`NotFound`, or `TryAgain` for the MANIFEST equivalent) instead of remaining readable. `DB::OpenAndCompact()` now retries the secondary open a bounded, configurable number of times for those transient statuses, so a concurrent rotation no longer fails the compaction (which, for a `CompactionService` that does not fall back to a local compaction, became a background error on the primary).
|
||||
* Fixed secondary DB `NewIterators()` returning iterators from different database states when `TryCatchUpWithPrimary()` runs concurrently.
|
||||
* Fixed a bug where a `SeekToFirst()` on an iterator previously used for a `Seek()` could end the scan early and silently omit keys with `ReadOptions::async_io`, or otherwise run with readahead effectively disabled. Affects scans using `ReadOptions::prefix_same_as_start` together with `ReadOptions::auto_readahead_size` (enabled by default); memory-mapped reads are unaffected.
|
||||
|
||||
### Performance Improvements
|
||||
* `DB::MultiGetEntityLazy()` now reads all keys of a batch under a single shared per-column-family SuperVersion pin, and a single `LazyWideColumnsBatch::MultiResolve()` coalesces the resulting blob reads across keys: one read per blob file (and one per SST for embedded blobs), for whole-column and byte-range reads alike, instead of reading each key's blobs separately.
|
||||
|
||||
|
||||
## 11.10.0 (08/28/2026)
|
||||
### New Features
|
||||
* Added `BlockBasedTableOptions::optimize_key_common_prefix` as part of new `format_version=8`. When enabled, each data block and index block stores the common user-key prefix of its keys once instead of at every restart point, reducing block size and block-cache footprint for prefix-heavy data and speeding up Seek for bytewise-ordered keys.
|
||||
* A new experimental feature spreads out periodic (time-based) compaction trigger times across a fleet of similarly-configured DBs to avoid recurring "thundering herd" triggers, especially with remote compaction. See the new experimental DB option `periodic_compaction_phase_recovery_percent`.
|
||||
|
||||
### Public API Changes
|
||||
* `IngestExternalFileArg::atomic_replace_range` now supports a range that only partially overlaps existing files, instead of failing. Requires universal compaction and a table factory that supports range deletion; other configurations still fail on partial overlap. The range is also now specified as half-open (`start` inclusive, `limit` exclusive), resolving a previously documented ambiguity in the upper bound.
|
||||
* Added an immutable `external_table_config` option that is persisted in OPTIONS files and passed to external table factories during bootstrap.
|
||||
|
||||
### Bug Fixes
|
||||
* Fixed a liveness bug where RocksDB could remain indefinitely in recovery from a soft background error when concurrent writes continuously generated normal flush requests.
|
||||
* Fixed a race in online error recovery where a concurrent higher-severity I/O error could leave a stale retry-flush plan active, prevent the required WAL switch, and create duplicate internal WAL history detected on DB reopen.
|
||||
* Fix "bottommost files" infinite compaction loops (`kBottommostFiles`). This happens with the unsupported combination of leveled compaction and `preserve_internal_time_seconds` / `preclude_last_level_data_seconds`, and in an edge case with user-defined timestamps when `full_history_ts_low` is unset. The underlying logic is now more unified to reduce risk of a similar divergence in logic in the future.
|
||||
* Fixed `reuse_manifest_on_open` to create a fresh MANIFEST instead of appending after recovery sees an incomplete atomic group at the MANIFEST tail.
|
||||
* Starting remote compaction (`CompactionService` / `DB::OpenAndCompact`) is now more efficient and more reliable, by avoiding unnecessary file operations (latency) while using more accurate consistency / precondition checks, both avoiding some spurious failures and rejecting more legitimate inconsistencies. New DBOption `remote_compaction_manifest_floor` can be disabled in case of unexpected problems with the change.
|
||||
* Fixed unbounded retention of recovered transaction state by a long-lived secondary opened with `allow_2pc`.
|
||||
* Fixed stale reads on secondary instances, where entries replayed from a WAL that the primary had already flushed could shadow the newer values in the flushed files indefinitely. Also fixed a case where a secondary could stop returning such a key altogether while the primary's flushed file holding it was unreadable.
|
||||
* Fixed subset checkpoints to discard tolerated MANIFEST tail corruption before appending column-family drop records.
|
||||
|
||||
### Performance Improvements
|
||||
* Improved compaction CPU efficiency for column families using an `SstPartitioner` (such as the built-in `SstPartitionerFixedPrefix`): when the partitioner can express its next boundary as a key prefix via the new `SstPartitioner::ShouldPartitionByPrefix()` API, compaction now checks that cached prefix inline instead of copying every user key and making a virtual `ShouldPartition()` call for each key-value written to an SST.
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -86,11 +86,20 @@ else
|
||||
LIB_MODE?=shared
|
||||
endif
|
||||
|
||||
$(info $$DEBUG_LEVEL is $(DEBUG_LEVEL), $$LIB_MODE is $(LIB_MODE))
|
||||
# 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)))
|
||||
|
||||
# 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)"; \
|
||||
@@ -104,8 +113,9 @@ 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"))
|
||||
# this file is generated by the previous line to set build flags and sources
|
||||
"$(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
|
||||
include make_config.mk
|
||||
|
||||
# Figure out optimize level.
|
||||
@@ -181,7 +191,7 @@ ifeq ($(filter -DROCKSDB_ASSERT_STATUS_CHECKED,$(OPT)),)
|
||||
endif
|
||||
endif
|
||||
|
||||
$(warning Warning: Compiling in debug mode. Don't use the resulting binary in production)
|
||||
$(if $(ROCKSDB_RECURSIVE_MAKE_SAME_CONFIG),,$(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
|
||||
@@ -579,9 +589,13 @@ 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/coro_external_table.h \
|
||||
include/rocksdb/utilities/coro_stackable_db.h
|
||||
# Some headers like in port/ are platform-specific
|
||||
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')
|
||||
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'))
|
||||
else
|
||||
DEV_HEADERS_TO_CHECK :=
|
||||
PUBLIC_HEADERS_TO_CHECK :=
|
||||
@@ -949,6 +963,57 @@ 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
|
||||
@@ -976,7 +1041,8 @@ gen_parallel_tests:
|
||||
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.*$$
|
||||
^.*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.*$$
|
||||
prioritize_long_running_tests = \
|
||||
perl -pe 's,($(slow_test_regexp)),100 $$1,' \
|
||||
| sort -k1,1gr \
|
||||
@@ -1108,27 +1174,17 @@ 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)
|
||||
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
|
||||
# NOTE: ^^^^^^^^ don't add new auxiliary checks here, but instead to
|
||||
# CHECK_EXTRA_TARGETS
|
||||
|
||||
# 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
|
||||
@@ -1149,8 +1205,8 @@ endif
|
||||
# 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; locally it falls back to main /
|
||||
# origin/main and is skipped if neither resolves.
|
||||
# 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.
|
||||
API_COMPAT_REF ?= main
|
||||
CHECK_C_API_GEN_STRICT ?=
|
||||
check-c-api-gen:
|
||||
@@ -1235,6 +1291,14 @@ 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
|
||||
@@ -1670,6 +1734,9 @@ 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)
|
||||
|
||||
@@ -1952,6 +2019,9 @@ block_fetcher_test: table/block_fetcher_test.o $(TEST_LIBRARY) $(LIBRARY)
|
||||
block_test: $(OBJ_DIR)/table/block_based/block_test.o $(TEST_LIBRARY) $(LIBRARY)
|
||||
$(AM_LINK)
|
||||
|
||||
builtin_index_factory_test: $(OBJ_DIR)/table/block_based/builtin_index_factory_test.o $(TEST_LIBRARY) $(LIBRARY)
|
||||
$(AM_LINK)
|
||||
|
||||
data_block_hash_index_test: $(OBJ_DIR)/table/block_based/data_block_hash_index_test.o $(TEST_LIBRARY) $(LIBRARY)
|
||||
$(AM_LINK)
|
||||
|
||||
@@ -2374,22 +2444,27 @@ 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_BASE ?= http://zlib.net
|
||||
ZLIB_DOWNLOAD_PREFIX ?= http://zlib.net/zlib-
|
||||
BZIP2_VER ?= 1.0.8
|
||||
BZIP2_SHA256 ?= ab5a03176ee106d3f0fa90e381da478ddae405918153cca248e682cd0c4a2269
|
||||
BZIP2_DOWNLOAD_BASE ?= http://sourceware.org/pub/bzip2
|
||||
BZIP2_DOWNLOAD_PREFIX ?= http://sourceware.org/pub/bzip2/bzip2-
|
||||
SNAPPY_VER ?= 1.2.2
|
||||
SNAPPY_SHA256 ?= 90f74bc1fbf78a6c56b3c4a082a05103b3a56bb17bca1a27e052ea11723292dc
|
||||
SNAPPY_DOWNLOAD_BASE ?= https://github.com/google/snappy/archive
|
||||
SNAPPY_DOWNLOAD_PREFIX ?= https://github.com/google/snappy/archive/
|
||||
LZ4_VER ?= 1.10.0
|
||||
LZ4_SHA256 ?= 537512904744b35e232912055ccf8ec66d768639ff3abe5788d90d792ec5f48b
|
||||
LZ4_DOWNLOAD_BASE ?= https://github.com/lz4/lz4/archive
|
||||
LZ4_DOWNLOAD_PREFIX ?= https://github.com/lz4/lz4/archive/v
|
||||
ZSTD_VER ?= 1.5.7
|
||||
ZSTD_SHA256 ?= 37d7284556b20954e56e1ca85b80226768902e2edabd3b649e9e72c0c9012ee3
|
||||
ZSTD_DOWNLOAD_BASE ?= https://github.com/facebook/zstd/archive
|
||||
CURL_SSL_OPTS ?= --tlsv1
|
||||
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
|
||||
|
||||
ifeq ($(PLATFORM), OS_MACOSX)
|
||||
ifeq (,$(findstring librocksdbjni-osx,$(ROCKSDBJNILIB)))
|
||||
@@ -2468,7 +2543,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 check-c-api-gen \
|
||||
gen_parallel_tests gen_check_scripts check-c-api-gen check-all-python \
|
||||
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
|
||||
@@ -2530,7 +2605,7 @@ endif
|
||||
endif
|
||||
|
||||
zlib-$(ZLIB_VER).tar.gz:
|
||||
curl --fail --output zlib-$(ZLIB_VER).tar.gz --location ${ZLIB_DOWNLOAD_BASE}/zlib-$(ZLIB_VER).tar.gz
|
||||
$(CURL_DOWNLOAD) --output zlib-$(ZLIB_VER).tar.gz ${ZLIB_DOWNLOAD_PREFIX}$(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\"; \
|
||||
@@ -2548,7 +2623,7 @@ libz.a: zlib-$(ZLIB_VER).tar.gz
|
||||
cp zlib-$(ZLIB_VER)/libz.a .
|
||||
|
||||
bzip2-$(BZIP2_VER).tar.gz:
|
||||
curl --fail --output bzip2-$(BZIP2_VER).tar.gz --location ${CURL_SSL_OPTS} ${BZIP2_DOWNLOAD_BASE}/bzip2-$(BZIP2_VER).tar.gz
|
||||
$(CURL_DOWNLOAD) --output bzip2-$(BZIP2_VER).tar.gz ${BZIP2_DOWNLOAD_PREFIX}$(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\"; \
|
||||
@@ -2562,7 +2637,7 @@ libbz2.a: bzip2-$(BZIP2_VER).tar.gz
|
||||
cp bzip2-$(BZIP2_VER)/libbz2.a .
|
||||
|
||||
snappy-$(SNAPPY_VER).tar.gz:
|
||||
curl --fail --output snappy-$(SNAPPY_VER).tar.gz --location ${CURL_SSL_OPTS} ${SNAPPY_DOWNLOAD_BASE}/$(SNAPPY_VER).tar.gz
|
||||
$(CURL_DOWNLOAD) --output snappy-$(SNAPPY_VER).tar.gz ${SNAPPY_DOWNLOAD_PREFIX}$(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\"; \
|
||||
@@ -2577,7 +2652,7 @@ libsnappy.a: snappy-$(SNAPPY_VER).tar.gz
|
||||
cp snappy-$(SNAPPY_VER)/build/libsnappy.a .
|
||||
|
||||
lz4-$(LZ4_VER).tar.gz:
|
||||
curl --fail --output lz4-$(LZ4_VER).tar.gz --location ${CURL_SSL_OPTS} ${LZ4_DOWNLOAD_BASE}/v$(LZ4_VER).tar.gz
|
||||
$(CURL_DOWNLOAD) --output lz4-$(LZ4_VER).tar.gz ${LZ4_DOWNLOAD_PREFIX}$(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\"; \
|
||||
@@ -2591,7 +2666,7 @@ liblz4.a: lz4-$(LZ4_VER).tar.gz
|
||||
cp lz4-$(LZ4_VER)/lib/liblz4.a .
|
||||
|
||||
zstd-$(ZSTD_VER).tar.gz:
|
||||
curl --fail --output zstd-$(ZSTD_VER).tar.gz --location ${CURL_SSL_OPTS} ${ZSTD_DOWNLOAD_BASE}/v$(ZSTD_VER).tar.gz
|
||||
$(CURL_DOWNLOAD) --output zstd-$(ZSTD_VER).tar.gz ${ZSTD_DOWNLOAD_PREFIX}$(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\"; \
|
||||
|
||||
@@ -35,6 +35,49 @@ from util import ColorString
|
||||
# tests to export as libraries for inclusion in other projects
|
||||
_EXPORTED_TEST_LIBS = ["env_basic_test"]
|
||||
|
||||
_TEST_LIB_HEADERS = [
|
||||
"db/db_test_util.h",
|
||||
"db/db_with_timestamp_test_util.h",
|
||||
"table/mock_table.h",
|
||||
"test_util/mock_time_env.h",
|
||||
"test_util/secondary_cache_test_util.h",
|
||||
"test_util/simple_external_table_factory.h",
|
||||
"test_util/testharness.h",
|
||||
"test_util/testutil.h",
|
||||
"tools/block_cache_analyzer/block_cache_trace_analyzer.h",
|
||||
"tools/trace_analyzer_tool.h",
|
||||
"utilities/agg_merge/test_agg_merge.h",
|
||||
"utilities/cassandra/test_utils.h",
|
||||
]
|
||||
|
||||
_TEST_HEADERS = {
|
||||
"configurable_test": ["options/configurable_test.h"],
|
||||
"persistent_cache_test": ["utilities/persistent_cache/persistent_cache_test.h"],
|
||||
"point_lock_manager_test": [
|
||||
"utilities/transactions/lock/point/point_lock_manager_test.h",
|
||||
],
|
||||
"transaction_test": ["utilities/transactions/transaction_test.h"],
|
||||
}
|
||||
|
||||
_STRESS_LIB_HEADERS = [
|
||||
"db_stress_tool/db_stress_common.h",
|
||||
"db_stress_tool/db_stress_compaction_service.h",
|
||||
"db_stress_tool/db_stress_compression_manager.h",
|
||||
"db_stress_tool/db_stress_driver.h",
|
||||
"db_stress_tool/db_stress_filters.h",
|
||||
"db_stress_tool/db_stress_listener.h",
|
||||
"db_stress_tool/db_stress_shared_state.h",
|
||||
"db_stress_tool/db_stress_test_base.h",
|
||||
"db_stress_tool/db_stress_wide_merge_operator.h",
|
||||
"db_stress_tool/expected_state.h",
|
||||
"db_stress_tool/expected_value.h",
|
||||
"db_stress_tool/multi_ops_txns_stress.h",
|
||||
"test_util/simple_external_table_factory.h",
|
||||
"test_util/testutil.h",
|
||||
"tools/block_cache_analyzer/block_cache_trace_analyzer.h",
|
||||
"tools/trace_analyzer_tool.h"
|
||||
]
|
||||
|
||||
# Parse src.mk files as a Dictionary of
|
||||
# VAR_NAME => list of files
|
||||
def parse_src_mk(repo_path):
|
||||
@@ -183,27 +226,34 @@ def generate_buck(repo_path, deps_map):
|
||||
":rocksdb_lib",
|
||||
],
|
||||
)
|
||||
# rocksdb_test_lib
|
||||
BUCK.add_library(
|
||||
"rocksdb_test_lib",
|
||||
test_lib_sources = (
|
||||
src_mk.get("MOCK_LIB_SOURCES", [])
|
||||
+ src_mk.get("TEST_LIB_SOURCES", [])
|
||||
+ src_mk.get("EXP_LIB_SOURCES", [])
|
||||
+ src_mk.get("ANALYZER_LIB_SOURCES", []),
|
||||
+ src_mk.get("ANALYZER_LIB_SOURCES", [])
|
||||
)
|
||||
# Older release source lists may not compile every test helper yet.
|
||||
test_lib_headers = [
|
||||
header for header in _TEST_LIB_HEADERS
|
||||
if header[:-2] + ".cc" in test_lib_sources
|
||||
]
|
||||
# rocksdb_test_lib
|
||||
BUCK.add_library(
|
||||
"rocksdb_test_lib",
|
||||
test_lib_sources,
|
||||
[":rocksdb_lib"],
|
||||
extra_test_libs=True,
|
||||
headers=test_lib_headers,
|
||||
)
|
||||
# rocksdb_with_faiss_test_lib
|
||||
BUCK.add_library(
|
||||
"rocksdb_with_faiss_test_lib",
|
||||
src_mk.get("MOCK_LIB_SOURCES", [])
|
||||
+ src_mk.get("TEST_LIB_SOURCES", [])
|
||||
+ src_mk.get("EXP_LIB_SOURCES", [])
|
||||
+ src_mk.get("ANALYZER_LIB_SOURCES", []),
|
||||
test_lib_sources,
|
||||
deps=[
|
||||
":rocksdb_with_faiss_lib",
|
||||
],
|
||||
extra_test_libs=True,
|
||||
headers=test_lib_headers,
|
||||
)
|
||||
# rocksdb_tools_lib
|
||||
BUCK.add_library(
|
||||
@@ -212,6 +262,12 @@ def generate_buck(repo_path, deps_map):
|
||||
+ src_mk.get("ANALYZER_LIB_SOURCES", [])
|
||||
+ ["test_util/testutil.cc"],
|
||||
[":rocksdb_lib"],
|
||||
headers=[
|
||||
"test_util/testutil.h",
|
||||
"tools/block_cache_analyzer/block_cache_trace_analyzer.h",
|
||||
"tools/simulated_hybrid_file_system.h",
|
||||
"tools/trace_analyzer_tool.h",
|
||||
],
|
||||
)
|
||||
# rocksdb_cache_bench_tools_lib
|
||||
BUCK.add_library(
|
||||
@@ -225,12 +281,19 @@ def generate_buck(repo_path, deps_map):
|
||||
src_mk.get("POINT_LOCK_BENCH_LIB_SOURCES", []),
|
||||
[":rocksdb_lib"],
|
||||
)
|
||||
stress_sources = (
|
||||
src_mk.get("ANALYZER_LIB_SOURCES", [])
|
||||
+ src_mk.get("STRESS_LIB_SOURCES", [])
|
||||
+ ["test_util/testutil.cc"]
|
||||
)
|
||||
# rocksdb_stress_lib
|
||||
BUCK.add_rocksdb_library(
|
||||
"rocksdb_stress_lib",
|
||||
src_mk.get("ANALYZER_LIB_SOURCES", [])
|
||||
+ src_mk.get("STRESS_LIB_SOURCES", [])
|
||||
+ ["test_util/testutil.cc"],
|
||||
stress_sources,
|
||||
headers=[
|
||||
header for header in _STRESS_LIB_HEADERS
|
||||
if header[:-2] + ".cc" in stress_sources
|
||||
],
|
||||
)
|
||||
# ldb binary
|
||||
BUCK.add_binary(
|
||||
@@ -353,6 +416,7 @@ def generate_buck(repo_path, deps_map):
|
||||
test_src,
|
||||
deps=json.dumps(deps["extra_deps"] + [":" + test_library]),
|
||||
extra_compiler_flags=json.dumps(deps["extra_compiler_flags"]),
|
||||
source_headers=_TEST_HEADERS.get(test, []),
|
||||
)
|
||||
else:
|
||||
if with_faiss:
|
||||
@@ -361,6 +425,7 @@ def generate_buck(repo_path, deps_map):
|
||||
test_src,
|
||||
deps=json.dumps(deps["extra_deps"] + [":rocksdb_with_faiss_test_lib"]),
|
||||
extra_compiler_flags=json.dumps(deps["extra_compiler_flags"]),
|
||||
source_headers=_TEST_HEADERS.get(test, []),
|
||||
)
|
||||
else:
|
||||
BUCK.register_test(
|
||||
@@ -368,6 +433,7 @@ def generate_buck(repo_path, deps_map):
|
||||
test_src,
|
||||
deps=json.dumps(deps["extra_deps"] + [":rocksdb_test_lib"]),
|
||||
extra_compiler_flags=json.dumps(deps["extra_compiler_flags"]),
|
||||
source_headers=_TEST_HEADERS.get(test, []),
|
||||
)
|
||||
BUCK.export_file("tools/db_crashtest.py")
|
||||
BUCK.export_file("tools/fault_injection_log_parser.py")
|
||||
|
||||
@@ -162,12 +162,17 @@ add_c_test_wrapper()
|
||||
).encode("utf-8")
|
||||
)
|
||||
|
||||
def register_test(self, test_name, src, deps, extra_compiler_flags):
|
||||
def register_test(self, test_name, src, deps, extra_compiler_flags, source_headers):
|
||||
with open(self.path, "ab") as targets_file:
|
||||
targets_file.write(
|
||||
targets_cfg.unittests_template.format(
|
||||
test_name=test_name,
|
||||
test_cc=str(src),
|
||||
source_headers=(
|
||||
f" source_headers=[{pretty_list(source_headers, 16)}],\n"
|
||||
if source_headers
|
||||
else ""
|
||||
),
|
||||
deps=deps,
|
||||
extra_compiler_flags=extra_compiler_flags,
|
||||
).encode("utf-8")
|
||||
|
||||
@@ -30,7 +30,7 @@ cpp_binary_wrapper(name="{name}", srcs=[{srcs}], deps=[{deps}], extra_preprocess
|
||||
unittests_template = """
|
||||
cpp_unittest_wrapper(name="{test_name}",
|
||||
srcs=["{test_cc}"],
|
||||
deps={deps},
|
||||
{source_headers} deps={deps},
|
||||
extra_compiler_flags={extra_compiler_flags})
|
||||
|
||||
"""
|
||||
|
||||
@@ -142,6 +142,11 @@ uint64_t rocksdb_table_properties_column_family_id(
|
||||
return props->rep.column_family_id;
|
||||
}
|
||||
|
||||
uint64_t rocksdb_table_properties_oldest_ancestor_time(
|
||||
const rocksdb_table_properties_t* props) {
|
||||
return props->rep.oldest_ancestor_time;
|
||||
}
|
||||
|
||||
uint64_t rocksdb_table_properties_creation_time(
|
||||
const rocksdb_table_properties_t* props) {
|
||||
return props->rep.creation_time;
|
||||
@@ -172,11 +177,6 @@ uint64_t rocksdb_table_properties_fast_compression_estimated_data_size(
|
||||
return props->rep.fast_compression_estimated_data_size;
|
||||
}
|
||||
|
||||
uint64_t rocksdb_table_properties_external_sst_file_global_seqno_offset(
|
||||
const rocksdb_table_properties_t* props) {
|
||||
return props->rep.external_sst_file_global_seqno_offset;
|
||||
}
|
||||
|
||||
uint64_t rocksdb_table_properties_tail_start_offset(
|
||||
const rocksdb_table_properties_t* props) {
|
||||
return props->rep.tail_start_offset;
|
||||
@@ -212,6 +212,11 @@ uint64_t rocksdb_table_properties_separate_key_value_in_data_block(
|
||||
return props->rep.separate_key_value_in_data_block;
|
||||
}
|
||||
|
||||
uint64_t rocksdb_table_properties_lsm_info_at_creation(
|
||||
const rocksdb_table_properties_t* props) {
|
||||
return props->rep.lsm_info_at_creation;
|
||||
}
|
||||
|
||||
const char* rocksdb_table_properties_db_id(
|
||||
const rocksdb_table_properties_t* props, size_t* size) {
|
||||
*size = props->rep.db_id.size();
|
||||
|
||||
@@ -102,6 +102,10 @@ rocksdb_table_properties_fixed_key_len(const rocksdb_table_properties_t* props);
|
||||
extern ROCKSDB_LIBRARY_API uint64_t rocksdb_table_properties_column_family_id(
|
||||
const rocksdb_table_properties_t* props);
|
||||
|
||||
extern ROCKSDB_LIBRARY_API uint64_t
|
||||
rocksdb_table_properties_oldest_ancestor_time(
|
||||
const rocksdb_table_properties_t* props);
|
||||
|
||||
extern ROCKSDB_LIBRARY_API uint64_t
|
||||
rocksdb_table_properties_creation_time(const rocksdb_table_properties_t* props);
|
||||
|
||||
@@ -122,10 +126,6 @@ extern ROCKSDB_LIBRARY_API uint64_t
|
||||
rocksdb_table_properties_fast_compression_estimated_data_size(
|
||||
const rocksdb_table_properties_t* props);
|
||||
|
||||
extern ROCKSDB_LIBRARY_API uint64_t
|
||||
rocksdb_table_properties_external_sst_file_global_seqno_offset(
|
||||
const rocksdb_table_properties_t* props);
|
||||
|
||||
extern ROCKSDB_LIBRARY_API uint64_t rocksdb_table_properties_tail_start_offset(
|
||||
const rocksdb_table_properties_t* props);
|
||||
|
||||
@@ -151,6 +151,10 @@ extern ROCKSDB_LIBRARY_API uint64_t
|
||||
rocksdb_table_properties_separate_key_value_in_data_block(
|
||||
const rocksdb_table_properties_t* props);
|
||||
|
||||
extern ROCKSDB_LIBRARY_API uint64_t
|
||||
rocksdb_table_properties_lsm_info_at_creation(
|
||||
const rocksdb_table_properties_t* props);
|
||||
|
||||
extern ROCKSDB_LIBRARY_API const char* rocksdb_table_properties_db_id(
|
||||
const rocksdb_table_properties_t* props, size_t* size);
|
||||
|
||||
|
||||
@@ -141,6 +141,15 @@ 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;
|
||||
@@ -807,6 +816,26 @@ const char* rocksdb_options_get_db_host_id(rocksdb_options_t* opt,
|
||||
return opt->rep.db_host_id.data();
|
||||
}
|
||||
|
||||
void rocksdb_options_set_remote_compaction_manifest_floor(
|
||||
rocksdb_options_t* opt, unsigned char v) {
|
||||
opt->rep.remote_compaction_manifest_floor = v;
|
||||
}
|
||||
|
||||
unsigned char rocksdb_options_get_remote_compaction_manifest_floor(
|
||||
rocksdb_options_t* opt) {
|
||||
return opt->rep.remote_compaction_manifest_floor;
|
||||
}
|
||||
|
||||
void rocksdb_options_set_use_session_tmp_dir_for_remote_compaction(
|
||||
rocksdb_options_t* opt, unsigned char v) {
|
||||
opt->rep.use_session_tmp_dir_for_remote_compaction = v;
|
||||
}
|
||||
|
||||
unsigned char rocksdb_options_get_use_session_tmp_dir_for_remote_compaction(
|
||||
rocksdb_options_t* opt) {
|
||||
return opt->rep.use_session_tmp_dir_for_remote_compaction;
|
||||
}
|
||||
|
||||
void rocksdb_options_set_lowest_used_cache_tier(rocksdb_options_t* opt, int v) {
|
||||
opt->rep.lowest_used_cache_tier =
|
||||
static_cast<decltype(opt->rep.lowest_used_cache_tier)>(v);
|
||||
@@ -847,6 +876,16 @@ uint64_t rocksdb_options_get_max_compaction_trigger_wakeup_seconds(
|
||||
return opt->rep.max_compaction_trigger_wakeup_seconds;
|
||||
}
|
||||
|
||||
void rocksdb_options_set_periodic_compaction_phase_recovery_percent(
|
||||
rocksdb_options_t* opt, int v) {
|
||||
opt->rep.periodic_compaction_phase_recovery_percent = v;
|
||||
}
|
||||
|
||||
int rocksdb_options_get_periodic_compaction_phase_recovery_percent(
|
||||
rocksdb_options_t* opt) {
|
||||
return opt->rep.periodic_compaction_phase_recovery_percent;
|
||||
}
|
||||
|
||||
void rocksdb_options_set_follower_refresh_catchup_period_ms(
|
||||
rocksdb_options_t* opt, uint64_t v) {
|
||||
opt->rep.follower_refresh_catchup_period_ms = v;
|
||||
@@ -1296,6 +1335,16 @@ 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);
|
||||
@@ -2008,16 +2057,6 @@ unsigned char rocksdb_ingestexternalfileoptions_get_ingest_behind(
|
||||
return opt->rep.ingest_behind;
|
||||
}
|
||||
|
||||
void rocksdb_ingestexternalfileoptions_set_write_global_seqno(
|
||||
rocksdb_ingestexternalfileoptions_t* opt, unsigned char v) {
|
||||
opt->rep.write_global_seqno = v;
|
||||
}
|
||||
|
||||
unsigned char rocksdb_ingestexternalfileoptions_get_write_global_seqno(
|
||||
rocksdb_ingestexternalfileoptions_t* opt) {
|
||||
return opt->rep.write_global_seqno;
|
||||
}
|
||||
|
||||
void rocksdb_ingestexternalfileoptions_set_verify_checksums_before_ingest(
|
||||
rocksdb_ingestexternalfileoptions_t* opt, unsigned char v) {
|
||||
opt->rep.verify_checksums_before_ingest = v;
|
||||
@@ -2098,6 +2137,16 @@ int rocksdb_ingestexternalfileoptions_get_file_opening_threads(
|
||||
|
||||
/* OpenAndCompactOptions */
|
||||
|
||||
void rocksdb_open_and_compact_options_set_max_secondary_open_retries(
|
||||
rocksdb_open_and_compact_options_t* opt, uint32_t v) {
|
||||
opt->rep.max_secondary_open_retries = v;
|
||||
}
|
||||
|
||||
uint32_t rocksdb_open_and_compact_options_get_max_secondary_open_retries(
|
||||
rocksdb_open_and_compact_options_t* opt) {
|
||||
return opt->rep.max_secondary_open_retries;
|
||||
}
|
||||
|
||||
unsigned char rocksdb_open_and_compact_options_get_allow_resumption(
|
||||
rocksdb_open_and_compact_options_t* opt) {
|
||||
return opt->rep.allow_resumption;
|
||||
@@ -2495,6 +2544,17 @@ double rocksdb_block_based_options_get_uniform_cv_threshold(
|
||||
return opt->rep.uniform_cv_threshold;
|
||||
}
|
||||
|
||||
void rocksdb_block_based_options_set_optimize_key_common_prefix(
|
||||
rocksdb_block_based_table_options_t* opt, int v) {
|
||||
opt->rep.optimize_key_common_prefix =
|
||||
static_cast<decltype(opt->rep.optimize_key_common_prefix)>(v);
|
||||
}
|
||||
|
||||
int rocksdb_block_based_options_get_optimize_key_common_prefix(
|
||||
rocksdb_block_based_table_options_t* opt) {
|
||||
return static_cast<int>(opt->rep.optimize_key_common_prefix);
|
||||
}
|
||||
|
||||
void rocksdb_block_based_options_set_enable_index_compression(
|
||||
rocksdb_block_based_table_options_t* opt, unsigned char v) {
|
||||
opt->rep.enable_index_compression = v;
|
||||
|
||||
@@ -55,6 +55,12 @@ 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);
|
||||
|
||||
@@ -241,6 +247,21 @@ extern ROCKSDB_LIBRARY_API void rocksdb_options_set_db_host_id(
|
||||
extern ROCKSDB_LIBRARY_API const char* rocksdb_options_get_db_host_id(
|
||||
rocksdb_options_t* opt, size_t* size);
|
||||
|
||||
extern ROCKSDB_LIBRARY_API void
|
||||
rocksdb_options_set_remote_compaction_manifest_floor(rocksdb_options_t* opt,
|
||||
unsigned char v);
|
||||
|
||||
extern ROCKSDB_LIBRARY_API unsigned char
|
||||
rocksdb_options_get_remote_compaction_manifest_floor(rocksdb_options_t* opt);
|
||||
|
||||
extern ROCKSDB_LIBRARY_API void
|
||||
rocksdb_options_set_use_session_tmp_dir_for_remote_compaction(
|
||||
rocksdb_options_t* opt, unsigned char v);
|
||||
|
||||
extern ROCKSDB_LIBRARY_API unsigned char
|
||||
rocksdb_options_get_use_session_tmp_dir_for_remote_compaction(
|
||||
rocksdb_options_t* opt);
|
||||
|
||||
extern ROCKSDB_LIBRARY_API void rocksdb_options_set_lowest_used_cache_tier(
|
||||
rocksdb_options_t* opt, int v);
|
||||
|
||||
@@ -261,6 +282,14 @@ extern ROCKSDB_LIBRARY_API const char*
|
||||
rocksdb_options_get_daily_offpeak_time_utc(rocksdb_options_t* opt,
|
||||
size_t* size);
|
||||
|
||||
extern ROCKSDB_LIBRARY_API void
|
||||
rocksdb_options_set_periodic_compaction_phase_recovery_percent(
|
||||
rocksdb_options_t* opt, int v);
|
||||
|
||||
extern ROCKSDB_LIBRARY_API int
|
||||
rocksdb_options_get_periodic_compaction_phase_recovery_percent(
|
||||
rocksdb_options_t* opt);
|
||||
|
||||
extern ROCKSDB_LIBRARY_API void
|
||||
rocksdb_options_set_follower_refresh_catchup_period_ms(rocksdb_options_t* opt,
|
||||
uint64_t v);
|
||||
@@ -381,6 +410,14 @@ 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);
|
||||
|
||||
@@ -779,14 +816,6 @@ extern ROCKSDB_LIBRARY_API unsigned char
|
||||
rocksdb_ingestexternalfileoptions_get_ingest_behind(
|
||||
rocksdb_ingestexternalfileoptions_t* opt);
|
||||
|
||||
extern ROCKSDB_LIBRARY_API void
|
||||
rocksdb_ingestexternalfileoptions_set_write_global_seqno(
|
||||
rocksdb_ingestexternalfileoptions_t* opt, unsigned char v);
|
||||
|
||||
extern ROCKSDB_LIBRARY_API unsigned char
|
||||
rocksdb_ingestexternalfileoptions_get_write_global_seqno(
|
||||
rocksdb_ingestexternalfileoptions_t* opt);
|
||||
|
||||
extern ROCKSDB_LIBRARY_API void
|
||||
rocksdb_ingestexternalfileoptions_set_verify_checksums_before_ingest(
|
||||
rocksdb_ingestexternalfileoptions_t* opt, unsigned char v);
|
||||
@@ -849,6 +878,14 @@ rocksdb_ingestexternalfileoptions_get_file_opening_threads(
|
||||
|
||||
/* OpenAndCompactOptions */
|
||||
|
||||
extern ROCKSDB_LIBRARY_API void
|
||||
rocksdb_open_and_compact_options_set_max_secondary_open_retries(
|
||||
rocksdb_open_and_compact_options_t* opt, uint32_t v);
|
||||
|
||||
extern ROCKSDB_LIBRARY_API uint32_t
|
||||
rocksdb_open_and_compact_options_get_max_secondary_open_retries(
|
||||
rocksdb_open_and_compact_options_t* opt);
|
||||
|
||||
extern ROCKSDB_LIBRARY_API unsigned char
|
||||
rocksdb_open_and_compact_options_get_allow_resumption(
|
||||
rocksdb_open_and_compact_options_t* opt);
|
||||
@@ -1156,6 +1193,14 @@ extern ROCKSDB_LIBRARY_API double
|
||||
rocksdb_block_based_options_get_uniform_cv_threshold(
|
||||
rocksdb_block_based_table_options_t* opt);
|
||||
|
||||
extern ROCKSDB_LIBRARY_API void
|
||||
rocksdb_block_based_options_set_optimize_key_common_prefix(
|
||||
rocksdb_block_based_table_options_t* opt, int v);
|
||||
|
||||
extern ROCKSDB_LIBRARY_API int
|
||||
rocksdb_block_based_options_get_optimize_key_common_prefix(
|
||||
rocksdb_block_based_table_options_t* opt);
|
||||
|
||||
extern ROCKSDB_LIBRARY_API void
|
||||
rocksdb_block_based_options_set_enable_index_compression(
|
||||
rocksdb_block_based_table_options_t* opt, unsigned char v);
|
||||
|
||||
@@ -151,6 +151,12 @@ static void rocksdb_roundtrip_test_rocksdb_block_based_options(void) {
|
||||
rocksdb_block_based_options_set_optimize_filters_for_memory(obj, 0);
|
||||
CheckCondition(
|
||||
rocksdb_block_based_options_get_optimize_filters_for_memory(obj) == 0);
|
||||
rocksdb_block_based_options_set_optimize_key_common_prefix(obj, 1);
|
||||
CheckCondition(
|
||||
rocksdb_block_based_options_get_optimize_key_common_prefix(obj) == 1);
|
||||
rocksdb_block_based_options_set_optimize_key_common_prefix(obj, 0);
|
||||
CheckCondition(
|
||||
rocksdb_block_based_options_get_optimize_key_common_prefix(obj) == 0);
|
||||
rocksdb_block_based_options_set_partition_filters(obj, 1);
|
||||
CheckCondition(rocksdb_block_based_options_get_partition_filters(obj) == 1);
|
||||
rocksdb_block_based_options_set_partition_filters(obj, 0);
|
||||
@@ -550,12 +556,6 @@ static void rocksdb_roundtrip_test_rocksdb_ingestexternalfileoptions(void) {
|
||||
rocksdb_ingestexternalfileoptions_set_verify_file_checksum(obj, 0);
|
||||
CheckCondition(
|
||||
rocksdb_ingestexternalfileoptions_get_verify_file_checksum(obj) == 0);
|
||||
rocksdb_ingestexternalfileoptions_set_write_global_seqno(obj, 1);
|
||||
CheckCondition(
|
||||
rocksdb_ingestexternalfileoptions_get_write_global_seqno(obj) == 1);
|
||||
rocksdb_ingestexternalfileoptions_set_write_global_seqno(obj, 0);
|
||||
CheckCondition(
|
||||
rocksdb_ingestexternalfileoptions_get_write_global_seqno(obj) == 0);
|
||||
rocksdb_ingestexternalfileoptions_destroy(obj);
|
||||
}
|
||||
|
||||
@@ -586,6 +586,20 @@ static void rocksdb_roundtrip_test_rocksdb_livefiles_storage_info_options(
|
||||
rocksdb_livefiles_storage_info_options_destroy(obj);
|
||||
}
|
||||
|
||||
static void rocksdb_roundtrip_test_rocksdb_open_and_compact_options(void) {
|
||||
rocksdb_open_and_compact_options_t* obj =
|
||||
rocksdb_open_and_compact_options_create();
|
||||
rocksdb_open_and_compact_options_set_max_secondary_open_retries(obj, 1);
|
||||
CheckCondition(
|
||||
rocksdb_open_and_compact_options_get_max_secondary_open_retries(obj) ==
|
||||
1);
|
||||
rocksdb_open_and_compact_options_set_max_secondary_open_retries(obj, 0);
|
||||
CheckCondition(
|
||||
rocksdb_open_and_compact_options_get_max_secondary_open_retries(obj) ==
|
||||
0);
|
||||
rocksdb_open_and_compact_options_destroy(obj);
|
||||
}
|
||||
|
||||
static void rocksdb_roundtrip_test_rocksdb_optimistictransactiondb_options(
|
||||
void) {
|
||||
rocksdb_optimistictransactiondb_options_t* obj =
|
||||
@@ -647,6 +661,12 @@ 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);
|
||||
@@ -827,6 +847,12 @@ static void rocksdb_roundtrip_test_rocksdb_options(void) {
|
||||
CheckCondition(rocksdb_options_get_paranoid_memory_checks(obj) == 1);
|
||||
rocksdb_options_set_paranoid_memory_checks(obj, 0);
|
||||
CheckCondition(rocksdb_options_get_paranoid_memory_checks(obj) == 0);
|
||||
rocksdb_options_set_periodic_compaction_phase_recovery_percent(obj, 1);
|
||||
CheckCondition(
|
||||
rocksdb_options_get_periodic_compaction_phase_recovery_percent(obj) == 1);
|
||||
rocksdb_options_set_periodic_compaction_phase_recovery_percent(obj, 0);
|
||||
CheckCondition(
|
||||
rocksdb_options_get_periodic_compaction_phase_recovery_percent(obj) == 0);
|
||||
rocksdb_options_set_persist_stats_to_disk(obj, 1);
|
||||
CheckCondition(rocksdb_options_get_persist_stats_to_disk(obj) == 1);
|
||||
rocksdb_options_set_persist_stats_to_disk(obj, 0);
|
||||
@@ -849,6 +875,16 @@ 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_remote_compaction_manifest_floor(obj, 1);
|
||||
CheckCondition(rocksdb_options_get_remote_compaction_manifest_floor(obj) ==
|
||||
1);
|
||||
rocksdb_options_set_remote_compaction_manifest_floor(obj, 0);
|
||||
CheckCondition(rocksdb_options_get_remote_compaction_manifest_floor(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);
|
||||
@@ -895,6 +931,12 @@ static void rocksdb_roundtrip_test_rocksdb_options(void) {
|
||||
CheckCondition(rocksdb_options_get_use_fsync(obj) == 1);
|
||||
rocksdb_options_set_use_fsync(obj, 0);
|
||||
CheckCondition(rocksdb_options_get_use_fsync(obj) == 0);
|
||||
rocksdb_options_set_use_session_tmp_dir_for_remote_compaction(obj, 1);
|
||||
CheckCondition(
|
||||
rocksdb_options_get_use_session_tmp_dir_for_remote_compaction(obj) == 1);
|
||||
rocksdb_options_set_use_session_tmp_dir_for_remote_compaction(obj, 0);
|
||||
CheckCondition(
|
||||
rocksdb_options_get_use_session_tmp_dir_for_remote_compaction(obj) == 0);
|
||||
rocksdb_options_set_verify_manifest_content_on_close(obj, 1);
|
||||
CheckCondition(rocksdb_options_get_verify_manifest_content_on_close(obj) ==
|
||||
1);
|
||||
@@ -1353,6 +1395,7 @@ static void rocksdb_run_generated_roundtrip_tests(void) {
|
||||
rocksdb_roundtrip_test_rocksdb_flushwaloptions();
|
||||
rocksdb_roundtrip_test_rocksdb_ingestexternalfileoptions();
|
||||
rocksdb_roundtrip_test_rocksdb_livefiles_storage_info_options();
|
||||
rocksdb_roundtrip_test_rocksdb_open_and_compact_options();
|
||||
rocksdb_roundtrip_test_rocksdb_optimistictransactiondb_options();
|
||||
rocksdb_roundtrip_test_rocksdb_options();
|
||||
rocksdb_roundtrip_test_rocksdb_readoptions();
|
||||
|
||||
Vendored
+1
-1
@@ -245,7 +245,7 @@ class ShardedCache : public ShardedCacheBase {
|
||||
std::unique_ptr<size_t[]> states(new size_t[num_shards]{});
|
||||
|
||||
size_t aepl = opts.average_entries_per_lock;
|
||||
aepl = std::min(aepl, size_t{1});
|
||||
aepl = std::max(aepl, size_t{1});
|
||||
|
||||
bool remaining_work;
|
||||
do {
|
||||
|
||||
+161
-15
@@ -4,12 +4,135 @@
|
||||
Thorough multi-agent code review for RocksDB commits following CLAUDE.md guidelines,
|
||||
with structured codebase exploration, inter-agent debate, and verification.
|
||||
|
||||
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.
|
||||
## Behavioral Compatibility Review Perspective
|
||||
|
||||
Behavior changes are human judgment calls. They must be intentional,
|
||||
well-documented (including release notes), and researched for potential
|
||||
downstream production impact. Agents and reviewers must call out concrete gaps,
|
||||
ambiguity, or adverse impacts in the change's intent, documentation, and
|
||||
production-impact analysis.
|
||||
|
||||
When a diff changes how an existing accepted public or serialized input is
|
||||
interpreted—including an undocumented, discouraged, or historically ignored
|
||||
value—reviewers must:
|
||||
- Compare the old and new observable behavior, including performance and
|
||||
resource impact.
|
||||
- Check that the rationale and user-facing documentation clearly describe the
|
||||
change.
|
||||
- Identify known direct callers and stored configurations that may depend on
|
||||
the previous behavior.
|
||||
- Check for appropriate regression coverage, or a documented reason why such
|
||||
coverage is not practical.
|
||||
|
||||
A behavior change is not automatically a defect. Report a finding when the
|
||||
intent, documentation, downstream-impact analysis, or mitigation has a concrete
|
||||
gap or ambiguity that could lead to an unintended compatibility regression.
|
||||
|
||||
## DB Mutex Review Perspective
|
||||
|
||||
For every non-trivial change, determine whether the changed code, or any
|
||||
transitive callee it adds or changes, can run while `DBImpl::mutex_` is held.
|
||||
State the result explicitly, including when the DB mutex is not affected.
|
||||
|
||||
`DBImpl::mutex_` is the DB-wide metadata and coordination mutex. It protects
|
||||
cross-object invariants involving `ColumnFamilyData`, memtable and
|
||||
`SuperVersion` publication, `VersionSet`, snapshots, flush/compaction queues,
|
||||
background-job state, and file lifetime. It is shared by all column families
|
||||
and can be a hot lock. It is not the filesystem `db_lock_`, and it should not
|
||||
replace data-path synchronization already provided by `WriteThread`,
|
||||
`wal_write_mutex_`, atomics, referenced `SuperVersion`s, or component-local
|
||||
synchronization.
|
||||
|
||||
When a DB-mutex critical section is affected:
|
||||
|
||||
### Locking and correctness
|
||||
|
||||
- Trace the full call path and mark the exact lock and unlock boundaries. Do
|
||||
not inspect only the lines that directly acquire the mutex.
|
||||
- State the locking contract. Helpers that require the lock should document it
|
||||
and normally use `mutex_.AssertHeld()`. Check whether each caller expects the
|
||||
lock to be held on return.
|
||||
- Treat calls that can release and re-acquire the mutex as concurrency
|
||||
boundaries. Examples include `VersionSet::LogAndApply()`, condition-variable
|
||||
waits, write-thread coordination, and notification helpers. Revalidate state
|
||||
inspected before such a call.
|
||||
- Keep atomic metadata transitions under the mutex. Examples include moving a
|
||||
memtable between mutable and immutable state, reserving compaction inputs,
|
||||
installing a `Version` or `SuperVersion`, updating scheduling counters and
|
||||
queues, and changing file-lifetime protection.
|
||||
- For expensive work, prefer a prepare/run/install structure: reserve and pin
|
||||
the required state while locked, do CPU or I/O work while unlocked, then
|
||||
re-lock, validate, and publish. Before unlocking, copy mutable options and
|
||||
acquire every required object reference or lifetime reservation.
|
||||
- Check object lifetime across every unlocked region. Do not use a raw
|
||||
`ColumnFamilyData*`, `Version*`, memtable, file metadata pointer, or DB-owned
|
||||
container element after unlocking unless an explicit reference,
|
||||
`SuperVersion`, job object, or pending-output reservation keeps it alive.
|
||||
- Preserve the snapshot/input-selection boundary. Flush and compaction must not
|
||||
miss a snapshot whose visible key versions they may remove. Missing a newly
|
||||
created snapshot is a correctness bug; retaining a recently released
|
||||
snapshot is conservative but safe.
|
||||
- Never invoke untrusted or re-entrant code while holding the mutex. The mutex
|
||||
is non-reentrant, so a callback into RocksDB can self-deadlock.
|
||||
- Check lock ordering. `options_mutex_` is acquired before the DB mutex. When
|
||||
both the DB mutex and `wal_write_mutex_` are needed, the DB mutex is acquired
|
||||
first. Establish and document the order for other locks.
|
||||
- Keep cleanup outside the critical section when possible. File deletion,
|
||||
`JobContext::Clean()`, expensive `SuperVersion` destruction, logging, and
|
||||
listener callbacks should normally run after protected state is detached or
|
||||
snapshotted.
|
||||
- Do not add the DB mutex to steady-state point reads or the normal write data
|
||||
phase without strong justification. Reads normally use a referenced
|
||||
`SuperVersion`; writes use `WriteThread` and component-specific
|
||||
synchronization.
|
||||
|
||||
### Critical-section performance
|
||||
|
||||
- Compare the CPU and I/O performed under the mutex before and after the
|
||||
change. Include call frequency, loop bounds, input-size scaling, hidden work
|
||||
in callees, and worst-case cost.
|
||||
- Account for filesystem or network I/O, waits, callbacks, logging and
|
||||
formatting, allocation, container growth, copies, sorting, scans, reference
|
||||
release and destructors, cache misses, and repeated metadata lookups.
|
||||
- Do not allow a significant regression in mutex-held work without clear
|
||||
justification, hold-time or contention measurements, and representative
|
||||
benchmarks.
|
||||
- Treat unavoidable work under the mutex as hot-path code and keep it highly
|
||||
optimized. Precompute, allocate, copy, and perform I/O outside the lock;
|
||||
remove repeated scans and lookups; cache or batch work where practical; and
|
||||
keep locked operations O(1) or tightly bounded when possible.
|
||||
- Treat new blocking I/O, waits, callbacks into user or plugin code, unbounded
|
||||
loops, or work that scales with DB size, files, column families, snapshots,
|
||||
or pending jobs as a blocker unless it is unavoidable and supported by strong
|
||||
measurements and explicit design justification.
|
||||
|
||||
### Validation and evidence
|
||||
|
||||
- Test unlock windows with sync points rather than sleeps. Cover relevant races
|
||||
with memtable switches, snapshot create/release, column-family drop,
|
||||
flush/compaction install, shutdown, and background errors. Run TSAN where
|
||||
appropriate.
|
||||
- Distinguish wait time from hold time. `PerfContext::db_mutex_lock_nanos` and
|
||||
`DB_MUTEX_WAIT_MICROS` primarily expose acquisition wait; use contention
|
||||
profiles or scoped instrumentation to find long critical sections.
|
||||
- Report affected critical sections, before/after cost, workload assumptions,
|
||||
optimization choices, and remaining risk. If exact measurement is not
|
||||
practical, provide a conservative static bound and do not claim no regression
|
||||
without evidence.
|
||||
|
||||
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.
|
||||
|
||||
## Workflow Steps
|
||||
|
||||
@@ -276,6 +399,9 @@ in isolation may be a critical bug when you consider the full call chain.
|
||||
- **Callee side effects**: Does the change call functions that mutate shared
|
||||
state (counters, seqnos, metadata)? Are the mutations correct for the new
|
||||
calling context? (Use the callee-chain analysis from context.md)
|
||||
- Apply the DB Mutex Review Perspective above to locking contracts, unlocked
|
||||
object lifetimes, stale-state validation, lock ordering, and snapshot
|
||||
boundaries.
|
||||
|
||||
#### Agent: Cross-Component & Adversarial Reviewer
|
||||
|
||||
@@ -379,6 +505,9 @@ Write findings to `findings-caller-audit.md`.
|
||||
- Loop optimization opportunities
|
||||
- Branch prediction (LIKELY/UNLIKELY)
|
||||
- Zero-overhead design verification
|
||||
- Apply the DB Mutex Review Perspective above, with special focus on transitive
|
||||
CPU and I/O, before/after cost, critical-section hold time, and benchmark
|
||||
evidence
|
||||
|
||||
#### Agent: API & Compatibility Reviewer
|
||||
- Public API backwards compatibility
|
||||
@@ -386,8 +515,8 @@ Write findings to `findings-caller-audit.md`.
|
||||
- Documentation completeness
|
||||
- Deprecation policy compliance
|
||||
- Forward compatibility (struct extensibility)
|
||||
- **Behavioral compatibility**: Do changed semantics (e.g., kOutOfBound vs
|
||||
kUnknown) break implicit contracts with callers?
|
||||
- Apply the Behavioral Compatibility Review Perspective above to changes in
|
||||
observable semantics and implicit caller contracts.
|
||||
|
||||
#### Agent: Serialization & Deserialization Reviewer
|
||||
- Format correctness and versioning
|
||||
@@ -466,7 +595,9 @@ 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
|
||||
- Write the complete review to review-findings.md and output as response
|
||||
- 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
|
||||
|
||||
**Final report quality rules:**
|
||||
- The final report must be CLEAN and POLISHED. No stream-of-consciousness,
|
||||
@@ -483,9 +614,10 @@ Team lead synthesizes the debate into a consensus document:
|
||||
|
||||
**REQUIRED output structure (so the PR page stays scrollable):**
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
```markdown
|
||||
## Summary
|
||||
@@ -533,6 +665,9 @@ 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.
|
||||
|
||||
@@ -556,6 +691,8 @@ Rules for this structure:
|
||||
- [ ] Multi-component interactions (compaction, recovery, snapshots, iterators)
|
||||
- [ ] Configuration dependencies and unexpected option combinations
|
||||
- [ ] Potential pitfalls from caller-chain analysis
|
||||
- [ ] DB-mutex reachability checked through transitive callees; affected lock
|
||||
and unlock boundaries documented
|
||||
|
||||
### Review Phase (verified by agents)
|
||||
- [ ] Database semantics preserved (snapshot isolation, key ordering)
|
||||
@@ -569,11 +706,20 @@ Rules for this structure:
|
||||
- [ ] Code follows RocksDB style conventions
|
||||
- [ ] Behavioral contracts with upstream callers preserved
|
||||
- [ ] All callers enumerated with parameter range table
|
||||
- [ ] Before/after CPU and I/O under the DB mutex compared, with call frequency,
|
||||
scaling, hidden callee work, and worst-case cost included
|
||||
- [ ] No significant DB-mutex-held work regression; unavoidable work is highly
|
||||
optimized, bounded, and supported by measurements when material
|
||||
|
||||
## Output Structure
|
||||
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
|
||||
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.
|
||||
- `context.md` — Codebase context (call chains, invariants)
|
||||
- `findings-*.md` — Per-agent findings (design, correctness, cross-component,
|
||||
invariant-adversary, caller-audit, performance, api, serialization, tests)
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,67 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,106 @@
|
||||
# RocksDB Diff and Pull Request Summary Guidance
|
||||
|
||||
This guidance applies to both internal Phabricator diff summaries and external
|
||||
GitHub pull request summaries for changes under `fbcode/internal_repo_rocksdb/`.
|
||||
|
||||
## Goal
|
||||
|
||||
Write each diff or pull request summary for a reviewer who has not read the
|
||||
patch. The summary must explain the behavioral story and the evidence for it,
|
||||
not merely inventory the edited files or symbols.
|
||||
|
||||
Every new or updated diff or pull request summary must clearly cover:
|
||||
|
||||
1. Why the change is required.
|
||||
2. What the previous behavior was, including the failure mode or limitation.
|
||||
3. What the new behavior is.
|
||||
4. What changed in the implementation.
|
||||
5. Safety boundaries, compatibility, and unsupported or intentionally deferred
|
||||
cases.
|
||||
6. Tests performed and known limitations of the validation.
|
||||
|
||||
Use explicit headings for a broad, subtle, or high-risk change. A small,
|
||||
focused change may combine these points into a few paragraphs, but none may be
|
||||
left implicit when it affects a review decision.
|
||||
|
||||
## What Good RocksDB Summaries Make Concrete
|
||||
|
||||
- Name the exact conditions that activate a bug or behavior: relevant options,
|
||||
call ordering, storage mode, concurrency mode, file format, platform, or
|
||||
workload shape. Also state important cases that are not affected.
|
||||
- Explain the causal chain from the old behavior to its externally observable
|
||||
result. For correctness fixes, distinguish a symptom from the underlying
|
||||
invariant violation.
|
||||
- Describe the new contract before implementation mechanics. Then identify the
|
||||
essential implementation choices and why they are sufficient.
|
||||
- Call out API, ABI, serialized-format, behavioral, and performance
|
||||
compatibility where relevant. For additive persisted fields, state how older
|
||||
data is interpreted and whether older readers remain supported.
|
||||
- State safety boundaries precisely: defaults, feature gates, fallback paths,
|
||||
ownership and lifetime constraints, memory-ordering assumptions, and cases
|
||||
deliberately postponed to a follow-up.
|
||||
- Support performance claims with a baseline, workload and configuration,
|
||||
measurement method, and results. Report meaningful tradeoffs, not only the
|
||||
winning metric.
|
||||
- Make the test plan evidence-based. Name the tests and configurations, say
|
||||
what behavior each proves, and report failures, timeouts, untested platforms,
|
||||
or stale pre-rebase results honestly. For a regression test, say how it fails
|
||||
without the fix when that was verified.
|
||||
- Separate incidental cleanup or a pre-existing test fix from the primary
|
||||
change, and explain why it belongs in the diff.
|
||||
|
||||
Avoid vague claims such as "improves performance," "fixes an issue," or "tests
|
||||
pass." Avoid copying the patch into prose, exhaustive file-by-file narration,
|
||||
raw command output, and claims broader than the evidence.
|
||||
|
||||
## Suggested Structure
|
||||
|
||||
Adapt this structure to the change; do not keep empty or irrelevant sections.
|
||||
|
||||
```text
|
||||
Summary:
|
||||
|
||||
Why the change is required:
|
||||
<User or system impact, and why the current behavior is inadequate.>
|
||||
|
||||
Previous behavior:
|
||||
<Old contract or mechanism, triggering conditions, and observable result.>
|
||||
|
||||
New behavior:
|
||||
<New contract and externally visible effect.>
|
||||
|
||||
Implementation:
|
||||
<Essential design and code changes; omit routine edit-by-edit narration.>
|
||||
|
||||
Safety, compatibility, and limitations:
|
||||
<Defaults, unaffected paths, compatibility, unsupported cases, and follow-ups.>
|
||||
|
||||
Test Plan:
|
||||
<Exact tests/benchmarks, configurations, what they demonstrate, and gaps.>
|
||||
```
|
||||
|
||||
For a focused bug fix, a cohesive narrative can be clearer than six headings:
|
||||
problem and root cause, trigger and unaffected cases, fix, then quantified or
|
||||
counterfactual validation. For a multi-part change, labeled bullets such as
|
||||
`Fix`, `Add`, and `Change` can make the implementation and review surface easy
|
||||
to scan.
|
||||
|
||||
## Reference Pull Request Summaries
|
||||
|
||||
- [PR #15216](https://github.com/facebook/rocksdb/pull/15216) is a strong
|
||||
focused bug-fix example. It traces stale iterator state to readahead behavior
|
||||
and dropped keys, identifies the exact prerequisites and unaffected mmap
|
||||
case, gives before/after measurements, and explains how the regression test
|
||||
fails when the fix is reverted.
|
||||
- [PR #15218](https://github.com/facebook/rocksdb/pull/15218) is a concise
|
||||
example of explicit `Why`, `Previous behavior`, `New behavior`,
|
||||
`Implementation`, and `Safety boundaries and unsupported cases` sections.
|
||||
- Peter Dillinger's [PR #15231](https://github.com/facebook/rocksdb/pull/15231)
|
||||
is a strong recent multi-part example. Its `Fix`/`Add`/`Change` bullets
|
||||
separate the behaviors, its compatibility sentence explains how old files
|
||||
read back, and its test plan maps each new persisted property to concrete
|
||||
coverage while explaining an adjacent test adjustment.
|
||||
|
||||
Use these pull requests as models for reasoning, specificity, and evidence. Do
|
||||
not copy their length or headings mechanically; scale the summary to the risk
|
||||
and complexity of the change.
|
||||
@@ -25,6 +25,8 @@ CRASHTEST_PY=$(PYTHON) -u tools/db_crashtest.py --stress_cmd=$(DB_STRESS_CMD) --
|
||||
crash_test_with_multiops_wup_txn \
|
||||
crash_test_with_optimistic_txn \
|
||||
crash_test_with_tiered_storage \
|
||||
crash_test_with_full_external_table \
|
||||
liveness_crash_test \
|
||||
blackbox_crash_test blackbox_crash_test_with_atomic_flush \
|
||||
blackbox_crash_test_with_wc_txn blackbox_crash_test_with_wp_txn \
|
||||
blackbox_crash_test_with_wup_txn \
|
||||
@@ -35,6 +37,7 @@ CRASHTEST_PY=$(PYTHON) -u tools/db_crashtest.py --stress_cmd=$(DB_STRESS_CMD) --
|
||||
blackbox_crash_test_with_multiops_wup_txn \
|
||||
blackbox_crash_test_with_optimistic_txn \
|
||||
blackbox_crash_test_with_tiered_storage \
|
||||
blackbox_crash_test_with_full_external_table \
|
||||
whitebox_crash_test whitebox_crash_test_with_atomic_flush \
|
||||
whitebox_crash_test_with_wc_txn whitebox_crash_test_with_wp_txn \
|
||||
whitebox_crash_test_with_wup_txn \
|
||||
@@ -85,6 +88,8 @@ crash_test_with_tiered_storage: $(DB_STRESS_CMD)
|
||||
$(CRASHTEST_MAKE) whitebox_crash_test_with_tiered_storage
|
||||
$(CRASHTEST_MAKE) blackbox_crash_test_with_tiered_storage
|
||||
|
||||
crash_test_with_full_external_table: blackbox_crash_test_with_full_external_table
|
||||
|
||||
crash_test_with_multiops_wc_txn: $(DB_STRESS_CMD)
|
||||
$(CRASHTEST_MAKE) blackbox_crash_test_with_multiops_wc_txn
|
||||
|
||||
@@ -94,6 +99,9 @@ crash_test_with_multiops_wp_txn: $(DB_STRESS_CMD)
|
||||
crash_test_with_multiops_wup_txn: $(DB_STRESS_CMD)
|
||||
$(CRASHTEST_MAKE) blackbox_crash_test_with_multiops_wup_txn
|
||||
|
||||
liveness_crash_test: $(DB_STRESS_CMD)
|
||||
$(CRASHTEST_PY) liveness $(CRASH_TEST_EXT_ARGS)
|
||||
|
||||
blackbox_crash_test: $(DB_STRESS_CMD)
|
||||
$(CRASHTEST_PY) --simple blackbox $(CRASH_TEST_EXT_ARGS)
|
||||
$(CRASHTEST_PY) blackbox $(CRASH_TEST_EXT_ARGS)
|
||||
@@ -128,6 +136,9 @@ blackbox_crash_test_with_multiops_wup_txn: $(DB_STRESS_CMD)
|
||||
blackbox_crash_test_with_tiered_storage: $(DB_STRESS_CMD)
|
||||
$(CRASHTEST_PY) --test_tiered_storage blackbox $(CRASH_TEST_EXT_ARGS)
|
||||
|
||||
blackbox_crash_test_with_full_external_table: $(DB_STRESS_CMD)
|
||||
$(CRASHTEST_PY) --test_full_external_table blackbox $(CRASH_TEST_EXT_ARGS)
|
||||
|
||||
blackbox_crash_test_with_optimistic_txn: $(DB_STRESS_CMD)
|
||||
$(CRASHTEST_PY) --optimistic_txn blackbox $(CRASH_TEST_EXT_ARGS)
|
||||
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
|
||||
#include "rocksdb/rocksdb_namespace.h"
|
||||
|
||||
@@ -31,4 +33,43 @@ constexpr uint64_t kInvalidBlobFileNumber = 0;
|
||||
constexpr uint64_t kCurrentFileBlobIndexFileNumber = kInvalidBlobFileNumber;
|
||||
static_assert(kCurrentFileBlobIndexFileNumber == kInvalidBlobFileNumber);
|
||||
|
||||
// Sentinel range length meaning "the whole blob value" for the unified
|
||||
// blob-read primitives, which take a range descriptor {range_offset,
|
||||
// range_length}; range_length == kWholeBlobLength selects the whole value and
|
||||
// any other value selects the strict sub-range
|
||||
// [range_offset, range_offset + range_length).
|
||||
//
|
||||
// This is the internal counterpart of the public kLazyWholeColumn
|
||||
// (include/rocksdb/lazy_wide_columns.h); both are the maximum size_t. The lazy
|
||||
// resolver does not forward the public value as a range descriptor -- it
|
||||
// normalizes a whole-column request to kWholeBlobLength -- so the two are not
|
||||
// required to be equal, but both rely on the sentinel exceeding any real
|
||||
// blob/column size so a "whole" request is never mistaken for a strict
|
||||
// sub-range. Keep them in sync.
|
||||
inline constexpr size_t kWholeBlobLength = std::numeric_limits<size_t>::max();
|
||||
|
||||
// How aggressively a blob read verifies the record's checksum. Derived once at
|
||||
// the lazy read-path boundary (ReadPathBlobResolver) from
|
||||
// (ReadOptions::verify_checksums, LazyColumnReadRequest::force_verify) and
|
||||
// threaded down through the blob-read primitives, replacing the earlier mix of
|
||||
// a verify_checksums bool and a separate force-verify method. (Not literally a
|
||||
// constant, but kept here as a small shared blob-read enum rather than its own
|
||||
// header.)
|
||||
//
|
||||
// - kVerifyIfPresent: verify the whole-record checksum whenever the format
|
||||
// provides one, even if ReadOptions::verify_checksums is off. A byte-range
|
||||
// request under this policy is escalated to a whole-record read (a strict
|
||||
// sub-range cannot cover the checksum). This is the public force_verify.
|
||||
// - kVerifyIfNoAmplification: verify when the checksummable unit is already
|
||||
// being read -- a whole-value read verifies (the check is "free"), while a
|
||||
// strict sub-range read skips verification rather than amplify the read to
|
||||
// the whole record. Corresponds to verify_checksums on, force_verify off.
|
||||
// - kSkip: never verify. Corresponds to verify_checksums off, force_verify
|
||||
// off.
|
||||
enum class BlobVerifyPolicy : uint8_t {
|
||||
kVerifyIfPresent,
|
||||
kVerifyIfNoAmplification,
|
||||
kSkip,
|
||||
};
|
||||
|
||||
} // namespace ROCKSDB_NAMESPACE
|
||||
+47
-3
@@ -44,6 +44,43 @@ Status VersionBlobFetcherBase::FetchBlob(const Slice& user_key,
|
||||
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, BlobVerifyPolicy verify_policy,
|
||||
PinnableSlice* blob_value, uint64_t* bytes_read) const {
|
||||
if (range_length == kWholeBlobLength) {
|
||||
// Whole-value read. Delegate to FetchBlob (which handles the direct-write
|
||||
// fallback). For kVerifyIfPresent, force whole-record checksum verification
|
||||
// even when ReadOptions::verify_checksums is off, via a transient fetcher
|
||||
// over a verify-enabled copy of the read options (both locals outlive the
|
||||
// borrowed-options VersionBlobFetcher).
|
||||
constexpr FilePrefetchBuffer* prefetch_buffer = nullptr;
|
||||
if (verify_policy == BlobVerifyPolicy::kVerifyIfPresent &&
|
||||
!read_options().verify_checksums) {
|
||||
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);
|
||||
}
|
||||
return FetchBlob(user_key, blob_index, prefetch_buffer, blob_value,
|
||||
bytes_read);
|
||||
}
|
||||
|
||||
// Strict sub-range read: value bytes only, no whole-record checksum, no cache
|
||||
// fill. Only ever chosen when SupportsRangeRead() holds (a Version to read
|
||||
// through, no direct-write fallback) and verification is not forced (a strict
|
||||
// sub-range cannot cover the whole-record checksum).
|
||||
assert(SupportsRangeRead());
|
||||
assert(version_);
|
||||
assert(verify_policy != BlobVerifyPolicy::kVerifyIfPresent);
|
||||
return version_->GetBlobRange(read_options(), user_key, blob_index,
|
||||
range_offset, range_length, blob_value,
|
||||
bytes_read);
|
||||
}
|
||||
|
||||
Status EmbeddedAwareBlobFetcher::FetchBlob(const Slice& user_key,
|
||||
const BlobIndex& blob_index,
|
||||
FilePrefetchBuffer* prefetch_buffer,
|
||||
@@ -55,9 +92,16 @@ Status EmbeddedAwareBlobFetcher::FetchBlob(const Slice& user_key,
|
||||
// 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);
|
||||
// account their own BLOB_DB_* stats via BlobSource). This is a whole-value
|
||||
// read; the verify policy follows read_options().verify_checksums (the
|
||||
// decorator carries no separate force-verify signal).
|
||||
const BlobVerifyPolicy verify_policy =
|
||||
read_options().verify_checksums
|
||||
? BlobVerifyPolicy::kVerifyIfNoAmplification
|
||||
: BlobVerifyPolicy::kSkip;
|
||||
return same_file_reader_->GetSameFileBlob(
|
||||
read_options(), blob_index,
|
||||
/*range_offset=*/0, kWholeBlobLength, verify_policy, blob_value);
|
||||
}
|
||||
|
||||
if (base_ == nullptr) {
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
#include <utility>
|
||||
|
||||
#include "db/blob/blob_constants.h"
|
||||
#include "rocksdb/options.h"
|
||||
#include "rocksdb/status.h"
|
||||
|
||||
@@ -63,6 +64,26 @@ class VersionBlobFetcherBase : public BlobFetcher {
|
||||
PinnableSlice* blob_value,
|
||||
uint64_t* bytes_read) const override;
|
||||
|
||||
// Fetches the value of a separate-file blob reference into *blob_value,
|
||||
// applying `verify_policy` (see BlobVerifyPolicy). range_length ==
|
||||
// kWholeBlobLength reads the whole value (delegating to FetchBlob, which also
|
||||
// handles the direct-write fallback, and forcing whole-record checksum
|
||||
// verification for kVerifyIfPresent even when ReadOptions::verify_checksums
|
||||
// is off). Any other length reads only the sub-range [range_offset,
|
||||
// range_offset + range_length) directly from the blob file, reading just
|
||||
// those bytes on a cache miss -- no record-header/key read, no whole-record
|
||||
// checksum, no cache fill (see Version::GetBlobRange /
|
||||
// BlobSource::GetBlobRange). A strict sub-range is only valid when
|
||||
// SupportsRangeRead() is true and verify_policy != kVerifyIfPresent
|
||||
// (verifying a strict sub-range would have to amplify the read to the whole
|
||||
// record); callers check that first and take the whole-value path otherwise.
|
||||
// Not routed through the same-file (embedded) decorator -- same-file
|
||||
// references are resolved by the caller through a SameFileBlobReader.
|
||||
Status FetchBlobRange(const Slice& user_key, const BlobIndex& blob_index,
|
||||
uint64_t range_offset, size_t range_length,
|
||||
BlobVerifyPolicy verify_policy,
|
||||
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
|
||||
@@ -73,6 +94,19 @@ class VersionBlobFetcherBase : public BlobFetcher {
|
||||
(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_;
|
||||
}
|
||||
|
||||
// The Version this fetcher reads separate-file blob references through (may
|
||||
// be null for a direct-write-fallback-only fetcher). Used by the cross-key
|
||||
// lazy coalescing path to group and dispatch reads via
|
||||
// Version::MultiGetBlobLazy.
|
||||
const Version* version() const { return version_; }
|
||||
|
||||
protected:
|
||||
VersionBlobFetcherBase(const Version* version, BlobFileCache* blob_file_cache,
|
||||
bool allow_write_path_fallback)
|
||||
|
||||
@@ -41,14 +41,14 @@ BlobFileBuilder::BlobFileBuilder(
|
||||
const std::shared_ptr<IOTracer>& io_tracer,
|
||||
BlobFileCompletionCallback* blob_callback,
|
||||
BlobFileCreationReason creation_reason,
|
||||
std::vector<std::string>* blob_file_paths,
|
||||
std::vector<std::string>* output_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,
|
||||
blob_file_paths, blob_file_additions) {}
|
||||
output_file_paths, blob_file_additions) {}
|
||||
|
||||
BlobFileBuilder::BlobFileBuilder(
|
||||
std::function<uint64_t()> file_number_generator, FileSystem* fs,
|
||||
@@ -60,13 +60,15 @@ BlobFileBuilder::BlobFileBuilder(
|
||||
const std::shared_ptr<IOTracer>& io_tracer,
|
||||
BlobFileCompletionCallback* blob_callback,
|
||||
BlobFileCreationReason creation_reason,
|
||||
std::vector<std::string>* blob_file_paths,
|
||||
std::vector<std::string>* output_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
|
||||
@@ -88,7 +90,7 @@ BlobFileBuilder::BlobFileBuilder(
|
||||
io_tracer_(io_tracer),
|
||||
blob_callback_(blob_callback),
|
||||
creation_reason_(creation_reason),
|
||||
blob_file_paths_(blob_file_paths),
|
||||
output_file_paths_(output_file_paths),
|
||||
blob_file_additions_(blob_file_additions),
|
||||
blob_count_(0),
|
||||
blob_bytes_(0) {
|
||||
@@ -97,14 +99,21 @@ BlobFileBuilder::BlobFileBuilder(
|
||||
assert(immutable_options_);
|
||||
assert(file_options_);
|
||||
assert(write_options_);
|
||||
assert(blob_file_paths_);
|
||||
assert(blob_file_paths_->empty());
|
||||
assert(output_file_paths_);
|
||||
assert(output_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);
|
||||
@@ -186,10 +195,7 @@ Status BlobFileBuilder::OpenBlobFileIfNeeded() {
|
||||
assert(file_number_generator_);
|
||||
const uint64_t blob_file_number = file_number_generator_();
|
||||
|
||||
assert(immutable_options_);
|
||||
assert(!immutable_options_->cf_paths.empty());
|
||||
std::string blob_file_path =
|
||||
BlobFileName(immutable_options_->cf_paths.front().path, blob_file_number);
|
||||
std::string blob_file_path = GetBlobFilePath(blob_file_number);
|
||||
|
||||
if (blob_callback_) {
|
||||
blob_callback_->OnBlobFileCreationStarted(
|
||||
@@ -204,6 +210,10 @@ 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(
|
||||
@@ -214,11 +224,11 @@ Status BlobFileBuilder::OpenBlobFileIfNeeded() {
|
||||
}
|
||||
}
|
||||
|
||||
// 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));
|
||||
// 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));
|
||||
|
||||
assert(file);
|
||||
file->SetIOPriority(write_options_->rate_limiter_priority);
|
||||
@@ -228,7 +238,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), blob_file_paths_->back(), *file_options_,
|
||||
std::move(file), output_file_paths_->back(), fo_copy,
|
||||
immutable_options_->clock, io_tracer_, statistics,
|
||||
Histograms::BLOB_DB_BLOB_FILE_WRITE_MICROS, immutable_options_->listeners,
|
||||
immutable_options_->file_checksum_gen_factory.get(),
|
||||
@@ -341,7 +351,7 @@ Status BlobFileBuilder::CloseBlobFile() {
|
||||
|
||||
if (blob_callback_) {
|
||||
s = blob_callback_->OnBlobFileCompleted(
|
||||
blob_file_paths_->back(), column_family_name_, job_id_,
|
||||
GetBlobFilePath(blob_file_number), column_family_name_, job_id_,
|
||||
blob_file_number, creation_reason_, s, checksum_value, checksum_method,
|
||||
blob_count_, blob_bytes_);
|
||||
}
|
||||
@@ -385,9 +395,10 @@ 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(blob_file_paths_->back(), column_family_name_,
|
||||
job_id_, writer_->get_log_number(),
|
||||
->OnBlobFileCompleted(GetBlobFilePath(blob_file_number),
|
||||
column_family_name_, job_id_, blob_file_number,
|
||||
creation_reason_, s, "", "", blob_count_,
|
||||
blob_bytes_)
|
||||
.PermitUncheckedError();
|
||||
|
||||
@@ -48,7 +48,7 @@ class BlobFileBuilder {
|
||||
const std::shared_ptr<IOTracer>& io_tracer,
|
||||
BlobFileCompletionCallback* blob_callback,
|
||||
BlobFileCreationReason creation_reason,
|
||||
std::vector<std::string>* blob_file_paths,
|
||||
std::vector<std::string>* output_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>* blob_file_paths,
|
||||
std::vector<std::string>* output_file_paths,
|
||||
std::vector<BlobFileAddition>* blob_file_additions);
|
||||
|
||||
BlobFileBuilder(const BlobFileBuilder&) = delete;
|
||||
@@ -76,6 +76,7 @@ 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,
|
||||
@@ -93,6 +94,7 @@ 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_;
|
||||
@@ -108,7 +110,7 @@ class BlobFileBuilder {
|
||||
std::shared_ptr<IOTracer> io_tracer_;
|
||||
BlobFileCompletionCallback* blob_callback_;
|
||||
BlobFileCreationReason creation_reason_;
|
||||
std::vector<std::string>* blob_file_paths_;
|
||||
std::vector<std::string>* output_file_paths_;
|
||||
std::vector<BlobFileAddition>* blob_file_additions_;
|
||||
std::unique_ptr<BlobLogWriter> writer_;
|
||||
uint64_t blob_count_;
|
||||
|
||||
+87
-23
@@ -38,12 +38,14 @@ BlobFileCache::BlobFileCache(Cache* cache,
|
||||
}
|
||||
|
||||
Status BlobFileCache::GetBlobFileReader(
|
||||
const ReadOptions& read_options, uint64_t blob_file_number,
|
||||
const ReadOptions& read_options, const BlobFileOpenInfo& blob_file,
|
||||
CacheHandleGuard<BlobFileReader>* blob_file_reader,
|
||||
bool allow_footer_skip_retry) {
|
||||
assert(blob_file_reader);
|
||||
assert(blob_file_reader->IsEmpty());
|
||||
|
||||
const uint64_t blob_file_number = blob_file.file_number;
|
||||
|
||||
// NOTE: sharing same Cache with table_cache
|
||||
const Slice key = GetSliceForKey(&blob_file_number);
|
||||
|
||||
@@ -74,18 +76,8 @@ Status BlobFileCache::GetBlobFileReader(
|
||||
std::unique_ptr<BlobFileReader> reader;
|
||||
|
||||
{
|
||||
assert(file_options_);
|
||||
Status s = BlobFileReader::Create(
|
||||
*immutable_options_, read_options, *file_options_, column_family_id_,
|
||||
blob_file_read_hist_, blob_file_number, io_tracer_,
|
||||
/*skip_footer_validation=*/false, &reader);
|
||||
if (!s.ok() && s.IsCorruption() && allow_footer_skip_retry) {
|
||||
reader.reset();
|
||||
s = BlobFileReader::Create(
|
||||
*immutable_options_, read_options, *file_options_, column_family_id_,
|
||||
blob_file_read_hist_, blob_file_number, io_tracer_,
|
||||
/*skip_footer_validation=*/true, &reader);
|
||||
}
|
||||
Status s = OpenBlobFileReader(read_options, blob_file,
|
||||
allow_footer_skip_retry, &reader);
|
||||
if (!s.ok()) {
|
||||
ROCKS_LOG_WARN(immutable_options_->logger,
|
||||
"BlobFileCache open failed for blob file %" PRIu64
|
||||
@@ -114,7 +106,7 @@ Status BlobFileCache::GetBlobFileReader(
|
||||
}
|
||||
|
||||
Status BlobFileCache::OpenBlobFileReaderUncached(
|
||||
const ReadOptions& read_options, uint64_t blob_file_number,
|
||||
const ReadOptions& read_options, const BlobFileOpenInfo& blob_file,
|
||||
std::unique_ptr<BlobFileReader>* blob_file_reader,
|
||||
bool allow_footer_skip_retry) {
|
||||
assert(blob_file_reader);
|
||||
@@ -123,21 +115,77 @@ Status BlobFileCache::OpenBlobFileReaderUncached(
|
||||
Statistics* const statistics = immutable_options_->stats;
|
||||
RecordTick(statistics, NO_FILE_OPENS);
|
||||
|
||||
Status s = OpenBlobFileReader(read_options, blob_file,
|
||||
allow_footer_skip_retry, blob_file_reader);
|
||||
if (!s.ok()) {
|
||||
RecordTick(statistics, NO_FILE_ERRORS);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
void BlobFileCache::RegisterBlobFileChecksum(
|
||||
const BlobFileOpenInfo& blob_file) {
|
||||
assert(blob_file.file_checksum.empty() ==
|
||||
blob_file.file_checksum_func_name.empty());
|
||||
if (blob_file.file_checksum.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const Slice key = GetSliceForKey(&blob_file.file_number);
|
||||
MutexLock cache_lock(&mutex_.Get(key));
|
||||
{
|
||||
MutexLock checksum_lock(&blob_file_checksums_mutex_);
|
||||
BlobFileChecksum& checksum = blob_file_checksums_[blob_file.file_number];
|
||||
checksum.value = blob_file.file_checksum.ToString();
|
||||
checksum.function_name = blob_file.file_checksum_func_name.ToString();
|
||||
}
|
||||
|
||||
// Readers opened while the file was active did not carry finalized metadata
|
||||
// and may also have observed a footer-less file size.
|
||||
cache_.get()->Erase(key);
|
||||
}
|
||||
|
||||
void BlobFileCache::UnregisterBlobFileChecksum(uint64_t blob_file_number) {
|
||||
MutexLock checksum_lock(&blob_file_checksums_mutex_);
|
||||
blob_file_checksums_.erase(blob_file_number);
|
||||
}
|
||||
|
||||
Status BlobFileCache::OpenBlobFileReader(
|
||||
const ReadOptions& read_options, const BlobFileOpenInfo& blob_file,
|
||||
bool allow_footer_skip_retry,
|
||||
std::unique_ptr<BlobFileReader>* blob_file_reader) {
|
||||
assert(file_options_);
|
||||
assert(blob_file.file_checksum.empty() ==
|
||||
blob_file.file_checksum_func_name.empty());
|
||||
|
||||
FileOptions file_options = *file_options_;
|
||||
if (!blob_file.file_checksum.empty()) {
|
||||
file_options.file_checksum = blob_file.file_checksum.ToString();
|
||||
file_options.file_checksum_func_name =
|
||||
blob_file.file_checksum_func_name.ToString();
|
||||
} else {
|
||||
MutexLock checksum_lock(&blob_file_checksums_mutex_);
|
||||
const auto it = blob_file_checksums_.find(blob_file.file_number);
|
||||
if (it != blob_file_checksums_.end()) {
|
||||
file_options.file_checksum = it->second.value;
|
||||
file_options.file_checksum_func_name = it->second.function_name;
|
||||
} else {
|
||||
file_options.file_checksum.clear();
|
||||
file_options.file_checksum_func_name.clear();
|
||||
}
|
||||
}
|
||||
|
||||
Status s = BlobFileReader::Create(
|
||||
*immutable_options_, read_options, *file_options_, column_family_id_,
|
||||
blob_file_read_hist_, blob_file_number, io_tracer_,
|
||||
*immutable_options_, read_options, file_options, column_family_id_,
|
||||
blob_file_read_hist_, blob_file.file_number, io_tracer_,
|
||||
/*skip_footer_validation=*/false, blob_file_reader);
|
||||
if (!s.ok() && s.IsCorruption() && allow_footer_skip_retry) {
|
||||
blob_file_reader->reset();
|
||||
s = BlobFileReader::Create(
|
||||
*immutable_options_, read_options, *file_options_, column_family_id_,
|
||||
blob_file_read_hist_, blob_file_number, io_tracer_,
|
||||
*immutable_options_, read_options, file_options, column_family_id_,
|
||||
blob_file_read_hist_, blob_file.file_number, io_tracer_,
|
||||
/*skip_footer_validation=*/true, blob_file_reader);
|
||||
}
|
||||
if (!s.ok()) {
|
||||
RecordTick(statistics, NO_FILE_ERRORS);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
@@ -178,7 +226,7 @@ Status BlobFileCache::InsertBlobFileReader(
|
||||
}
|
||||
|
||||
Status BlobFileCache::RefreshBlobFileReader(
|
||||
uint64_t blob_file_number,
|
||||
const BlobFileOpenInfo& blob_file,
|
||||
std::unique_ptr<BlobFileReader>* blob_file_reader,
|
||||
CacheHandleGuard<BlobFileReader>* cached_blob_file_reader) {
|
||||
assert(blob_file_reader);
|
||||
@@ -186,10 +234,26 @@ Status BlobFileCache::RefreshBlobFileReader(
|
||||
assert(cached_blob_file_reader);
|
||||
assert(cached_blob_file_reader->IsEmpty());
|
||||
|
||||
const Slice key = GetSliceForKey(&blob_file_number);
|
||||
const Slice key = GetSliceForKey(&blob_file.file_number);
|
||||
MutexLock lock(&mutex_.Get(key));
|
||||
|
||||
TypedHandle* handle = cache_.Lookup(key);
|
||||
|
||||
if (blob_file.file_checksum.empty()) {
|
||||
MutexLock checksum_lock(&blob_file_checksums_mutex_);
|
||||
if (blob_file_checksums_.find(blob_file.file_number) !=
|
||||
blob_file_checksums_.end()) {
|
||||
// This reader can have been opened just before finalization registered
|
||||
// checksum metadata. Never let such a racing refresh repopulate the
|
||||
// cache.
|
||||
if (handle) {
|
||||
*cached_blob_file_reader = cache_.Guard(handle);
|
||||
}
|
||||
blob_file_reader->reset();
|
||||
return Status::OK();
|
||||
}
|
||||
}
|
||||
|
||||
if (handle) {
|
||||
BlobFileReader* const cached_reader = cache_.Value(handle);
|
||||
assert(cached_reader != nullptr);
|
||||
|
||||
@@ -6,9 +6,12 @@
|
||||
#pragma once
|
||||
|
||||
#include <cinttypes>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "cache/typed_cache.h"
|
||||
#include "db/blob/blob_file_reader.h"
|
||||
#include "db/blob/blob_read_request.h"
|
||||
#include "rocksdb/rocksdb_namespace.h"
|
||||
#include "util/mutexlock.h"
|
||||
|
||||
@@ -32,20 +35,30 @@ class BlobFileCache {
|
||||
BlobFileCache(const BlobFileCache&) = delete;
|
||||
BlobFileCache& operator=(const BlobFileCache&) = delete;
|
||||
|
||||
// Returns a cached reader for `blob_file_number`, opening and caching it on
|
||||
// miss. If `allow_footer_skip_retry` is true, a footer-validation corruption
|
||||
// retries once without requiring a footer.
|
||||
// Returns a cached reader for `blob_file`, opening and caching it on miss.
|
||||
// Checksum metadata is forwarded to the FileSystem through FileOptions when
|
||||
// the file is opened. If `allow_footer_skip_retry` is true, a
|
||||
// footer-validation corruption retries once without requiring a footer.
|
||||
Status GetBlobFileReader(const ReadOptions& read_options,
|
||||
uint64_t blob_file_number,
|
||||
const BlobFileOpenInfo& blob_file,
|
||||
CacheHandleGuard<BlobFileReader>* blob_file_reader,
|
||||
bool allow_footer_skip_retry = false);
|
||||
|
||||
// Opens a blob file reader without inserting it into the cache.
|
||||
Status OpenBlobFileReaderUncached(
|
||||
const ReadOptions& read_options, uint64_t blob_file_number,
|
||||
const ReadOptions& read_options, const BlobFileOpenInfo& blob_file,
|
||||
std::unique_ptr<BlobFileReader>* blob_file_reader,
|
||||
bool allow_footer_skip_retry = false);
|
||||
|
||||
// Makes finalized checksum metadata available to direct-write fallback reads
|
||||
// whose pinned Version predates the blob-file addition. Any cached
|
||||
// footer-less reader is evicted as part of the same per-file transition.
|
||||
void RegisterBlobFileChecksum(const BlobFileOpenInfo& blob_file);
|
||||
|
||||
// Stops retaining checksum metadata once no direct-write fallback can refer
|
||||
// to the file. Manifest-backed callers continue to provide it directly.
|
||||
void UnregisterBlobFileChecksum(uint64_t blob_file_number);
|
||||
|
||||
// Inserts a freshly opened uncached reader unless another thread already
|
||||
// cached the same blob file.
|
||||
Status InsertBlobFileReader(
|
||||
@@ -58,7 +71,7 @@ class BlobFileCache {
|
||||
// reader instead so a racing refresh cannot reintroduce an older active-file
|
||||
// view after the blob file grows.
|
||||
Status RefreshBlobFileReader(
|
||||
uint64_t blob_file_number,
|
||||
const BlobFileOpenInfo& blob_file,
|
||||
std::unique_ptr<BlobFileReader>* blob_file_reader,
|
||||
CacheHandleGuard<BlobFileReader>* cached_blob_file_reader);
|
||||
|
||||
@@ -72,6 +85,11 @@ class BlobFileCache {
|
||||
}
|
||||
|
||||
private:
|
||||
Status OpenBlobFileReader(const ReadOptions& read_options,
|
||||
const BlobFileOpenInfo& blob_file,
|
||||
bool allow_footer_skip_retry,
|
||||
std::unique_ptr<BlobFileReader>* blob_file_reader);
|
||||
|
||||
using CacheInterface =
|
||||
BasicTypedCacheInterface<BlobFileReader, CacheEntryRole::kMisc>;
|
||||
using TypedHandle = CacheInterface::TypedHandle;
|
||||
@@ -85,6 +103,13 @@ class BlobFileCache {
|
||||
HistogramImpl* blob_file_read_hist_;
|
||||
std::shared_ptr<IOTracer> io_tracer_;
|
||||
|
||||
struct BlobFileChecksum {
|
||||
std::string value;
|
||||
std::string function_name;
|
||||
};
|
||||
std::unordered_map<uint64_t, BlobFileChecksum> blob_file_checksums_;
|
||||
mutable port::Mutex blob_file_checksums_mutex_;
|
||||
|
||||
static constexpr size_t kNumberOfMutexStripes = 1 << 7;
|
||||
};
|
||||
|
||||
|
||||
@@ -115,13 +115,13 @@ TEST_F(BlobFileCacheTest, GetBlobFileReader) {
|
||||
BlobFileCache blob_file_cache(backing_cache.get(), &immutable_options,
|
||||
&file_options, column_family_id,
|
||||
blob_file_read_hist, nullptr /*IOTracer*/);
|
||||
const BlobFileOpenInfo blob_file{blob_file_number, Slice(), Slice()};
|
||||
|
||||
// First try: reader should be opened and put in cache
|
||||
CacheHandleGuard<BlobFileReader> first;
|
||||
|
||||
const ReadOptions read_options;
|
||||
ASSERT_OK(blob_file_cache.GetBlobFileReader(read_options, blob_file_number,
|
||||
&first));
|
||||
ASSERT_OK(blob_file_cache.GetBlobFileReader(read_options, blob_file, &first));
|
||||
ASSERT_NE(first.GetValue(), nullptr);
|
||||
ASSERT_EQ(options.statistics->getTickerCount(NO_FILE_OPENS), 1);
|
||||
ASSERT_EQ(options.statistics->getTickerCount(NO_FILE_ERRORS), 0);
|
||||
@@ -129,8 +129,8 @@ TEST_F(BlobFileCacheTest, GetBlobFileReader) {
|
||||
// Second try: reader should be served from cache
|
||||
CacheHandleGuard<BlobFileReader> second;
|
||||
|
||||
ASSERT_OK(blob_file_cache.GetBlobFileReader(read_options, blob_file_number,
|
||||
&second));
|
||||
ASSERT_OK(
|
||||
blob_file_cache.GetBlobFileReader(read_options, blob_file, &second));
|
||||
ASSERT_NE(second.GetValue(), nullptr);
|
||||
ASSERT_EQ(options.statistics->getTickerCount(NO_FILE_OPENS), 1);
|
||||
ASSERT_EQ(options.statistics->getTickerCount(NO_FILE_ERRORS), 0);
|
||||
@@ -163,6 +163,7 @@ TEST_F(BlobFileCacheTest, GetBlobFileReader_Race) {
|
||||
BlobFileCache blob_file_cache(backing_cache.get(), &immutable_options,
|
||||
&file_options, column_family_id,
|
||||
blob_file_read_hist, nullptr /*IOTracer*/);
|
||||
const BlobFileOpenInfo blob_file{blob_file_number, Slice(), Slice()};
|
||||
|
||||
CacheHandleGuard<BlobFileReader> first;
|
||||
CacheHandleGuard<BlobFileReader> second;
|
||||
@@ -172,16 +173,15 @@ TEST_F(BlobFileCacheTest, GetBlobFileReader_Race) {
|
||||
"BlobFileCache::GetBlobFileReader:DoubleCheck", [&](void* /* arg */) {
|
||||
// Disabling sync points to prevent infinite recursion
|
||||
SyncPoint::GetInstance()->DisableProcessing();
|
||||
ASSERT_OK(blob_file_cache.GetBlobFileReader(read_options,
|
||||
blob_file_number, &second));
|
||||
ASSERT_OK(blob_file_cache.GetBlobFileReader(read_options, blob_file,
|
||||
&second));
|
||||
ASSERT_NE(second.GetValue(), nullptr);
|
||||
ASSERT_EQ(options.statistics->getTickerCount(NO_FILE_OPENS), 1);
|
||||
ASSERT_EQ(options.statistics->getTickerCount(NO_FILE_ERRORS), 0);
|
||||
});
|
||||
SyncPoint::GetInstance()->EnableProcessing();
|
||||
|
||||
ASSERT_OK(blob_file_cache.GetBlobFileReader(read_options, blob_file_number,
|
||||
&first));
|
||||
ASSERT_OK(blob_file_cache.GetBlobFileReader(read_options, blob_file, &first));
|
||||
ASSERT_NE(first.GetValue(), nullptr);
|
||||
ASSERT_EQ(options.statistics->getTickerCount(NO_FILE_OPENS), 1);
|
||||
ASSERT_EQ(options.statistics->getTickerCount(NO_FILE_ERRORS), 0);
|
||||
@@ -245,21 +245,22 @@ TEST_F(BlobFileCacheTest, RefreshBlobFileReaderPrefersLargestObservedFileSize) {
|
||||
BlobFileCache blob_file_cache(backing_cache.get(), &immutable_options,
|
||||
&file_options, column_family_id,
|
||||
blob_file_read_hist, nullptr /*IOTracer*/);
|
||||
const BlobFileOpenInfo blob_file{blob_file_number, Slice(), Slice()};
|
||||
|
||||
const ReadOptions read_options;
|
||||
std::unique_ptr<BlobFileReader> stale_reader;
|
||||
ASSERT_OK(blob_file_cache.OpenBlobFileReaderUncached(
|
||||
read_options, blob_file_number, &stale_reader,
|
||||
read_options, blob_file, &stale_reader,
|
||||
/*allow_footer_skip_retry=*/true));
|
||||
|
||||
std::unique_ptr<BlobFileReader> initial_cached_reader;
|
||||
ASSERT_OK(blob_file_cache.OpenBlobFileReaderUncached(
|
||||
read_options, blob_file_number, &initial_cached_reader,
|
||||
read_options, blob_file, &initial_cached_reader,
|
||||
/*allow_footer_skip_retry=*/true));
|
||||
|
||||
CacheHandleGuard<BlobFileReader> cached_reader;
|
||||
ASSERT_OK(blob_file_cache.RefreshBlobFileReader(
|
||||
blob_file_number, &initial_cached_reader, &cached_reader));
|
||||
blob_file, &initial_cached_reader, &cached_reader));
|
||||
ASSERT_NE(cached_reader.GetValue(), nullptr);
|
||||
const uint64_t initial_file_size = cached_reader.GetValue()->GetFileSize();
|
||||
|
||||
@@ -269,20 +270,20 @@ TEST_F(BlobFileCacheTest, RefreshBlobFileReaderPrefersLargestObservedFileSize) {
|
||||
|
||||
std::unique_ptr<BlobFileReader> fresh_reader;
|
||||
ASSERT_OK(blob_file_cache.OpenBlobFileReaderUncached(
|
||||
read_options, blob_file_number, &fresh_reader,
|
||||
read_options, blob_file, &fresh_reader,
|
||||
/*allow_footer_skip_retry=*/true));
|
||||
ASSERT_GT(fresh_reader->GetFileSize(), initial_file_size);
|
||||
|
||||
CacheHandleGuard<BlobFileReader> refreshed_reader;
|
||||
ASSERT_OK(blob_file_cache.RefreshBlobFileReader(
|
||||
blob_file_number, &fresh_reader, &refreshed_reader));
|
||||
ASSERT_OK(blob_file_cache.RefreshBlobFileReader(blob_file, &fresh_reader,
|
||||
&refreshed_reader));
|
||||
ASSERT_NE(refreshed_reader.GetValue(), nullptr);
|
||||
ASSERT_GT(refreshed_reader.GetValue()->GetFileSize(), initial_file_size);
|
||||
BlobFileReader* const largest_reader = refreshed_reader.GetValue();
|
||||
|
||||
CacheHandleGuard<BlobFileReader> preserved_reader;
|
||||
ASSERT_OK(blob_file_cache.RefreshBlobFileReader(
|
||||
blob_file_number, &stale_reader, &preserved_reader));
|
||||
ASSERT_OK(blob_file_cache.RefreshBlobFileReader(blob_file, &stale_reader,
|
||||
&preserved_reader));
|
||||
ASSERT_NE(preserved_reader.GetValue(), nullptr);
|
||||
ASSERT_EQ(preserved_reader.GetValue(), largest_reader);
|
||||
ASSERT_EQ(stale_reader.get(), nullptr);
|
||||
@@ -312,12 +313,13 @@ TEST_F(BlobFileCacheTest, GetBlobFileReader_IOError) {
|
||||
|
||||
// Note: there is no blob file with the below number
|
||||
constexpr uint64_t blob_file_number = 123;
|
||||
const BlobFileOpenInfo blob_file{blob_file_number, Slice(), Slice()};
|
||||
|
||||
CacheHandleGuard<BlobFileReader> reader;
|
||||
|
||||
const ReadOptions read_options;
|
||||
ASSERT_TRUE(
|
||||
blob_file_cache.GetBlobFileReader(read_options, blob_file_number, &reader)
|
||||
blob_file_cache.GetBlobFileReader(read_options, blob_file, &reader)
|
||||
.IsIOError());
|
||||
ASSERT_EQ(reader.GetValue(), nullptr);
|
||||
ASSERT_EQ(options.statistics->getTickerCount(NO_FILE_OPENS), 1);
|
||||
@@ -352,6 +354,7 @@ TEST_F(BlobFileCacheTest, GetBlobFileReader_CacheFull) {
|
||||
BlobFileCache blob_file_cache(backing_cache.get(), &immutable_options,
|
||||
&file_options, column_family_id,
|
||||
blob_file_read_hist, nullptr /*IOTracer*/);
|
||||
const BlobFileOpenInfo blob_file{blob_file_number, Slice(), Slice()};
|
||||
|
||||
// Insert into cache should fail since it has zero capacity and
|
||||
// strict_capacity_limit is set
|
||||
@@ -359,7 +362,7 @@ TEST_F(BlobFileCacheTest, GetBlobFileReader_CacheFull) {
|
||||
|
||||
const ReadOptions read_options;
|
||||
ASSERT_TRUE(
|
||||
blob_file_cache.GetBlobFileReader(read_options, blob_file_number, &reader)
|
||||
blob_file_cache.GetBlobFileReader(read_options, blob_file, &reader)
|
||||
.IsMemoryLimit());
|
||||
ASSERT_EQ(reader.GetValue(), nullptr);
|
||||
ASSERT_EQ(options.statistics->getTickerCount(NO_FILE_OPENS), 1);
|
||||
|
||||
@@ -100,7 +100,8 @@ 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, BlobFileCache* blob_file_cache,
|
||||
uint64_t blob_file_size, bool use_fsync,
|
||||
uint64_t blob_writer_max_buffer_size, BlobFileCache* blob_file_cache,
|
||||
BlobFileCompletionCallback* blob_callback,
|
||||
const std::vector<std::shared_ptr<EventListener>>& listeners,
|
||||
FileChecksumGenFactory* file_checksum_gen_factory,
|
||||
@@ -120,6 +121,7 @@ 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),
|
||||
@@ -202,6 +204,11 @@ 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);
|
||||
@@ -323,6 +330,11 @@ Status BlobFilePartitionManager::FinalizeBlobFile(
|
||||
*addition =
|
||||
BlobFileAddition(file_number, blob_count, total_blob_bytes,
|
||||
std::move(checksum_method), std::move(checksum_value));
|
||||
if (blob_file_cache_ != nullptr) {
|
||||
const BlobFileOpenInfo blob_file{file_number, addition->GetChecksumValue(),
|
||||
addition->GetChecksumMethod()};
|
||||
blob_file_cache_->RegisterBlobFileChecksum(blob_file);
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
@@ -746,6 +758,9 @@ void BlobFilePartitionManager::UnprotectSealedBlobFileNumbers(
|
||||
// manifest-visible path. Evict it here so delayed protection does not
|
||||
// leave an obsolete blob reader behind until DB close.
|
||||
blob_file_cache_->Evict(file_number);
|
||||
if (file_to_partition_.find(file_number) == file_to_partition_.end()) {
|
||||
blob_file_cache_->UnregisterBlobFileChecksum(file_number);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -765,6 +780,10 @@ void BlobFilePartitionManager::RemoveFilePartitionMappings(
|
||||
// this file before it was sealed. Drop it now so future manifest-visible
|
||||
// reads reopen against the finalized on-disk size and footer state.
|
||||
blob_file_cache_->Evict(file_number);
|
||||
if (protected_blob_file_refs_.find(file_number) ==
|
||||
protected_blob_file_refs_.end()) {
|
||||
blob_file_cache_->UnregisterBlobFileChecksum(file_number);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -802,9 +821,9 @@ Status BlobFilePartitionManager::ResolveBlobDirectWriteIndex(
|
||||
}
|
||||
|
||||
Status s;
|
||||
const BlobFileOpenInfo blob_file{blob_idx.file_number(), Slice(), Slice()};
|
||||
CacheHandleGuard<BlobFileReader> reader;
|
||||
s = blob_file_cache->GetBlobFileReader(read_options, blob_idx.file_number(),
|
||||
&reader,
|
||||
s = blob_file_cache->GetBlobFileReader(read_options, blob_file, &reader,
|
||||
/*allow_footer_skip_retry=*/true);
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
@@ -829,7 +848,7 @@ Status BlobFilePartitionManager::ResolveBlobDirectWriteIndex(
|
||||
|
||||
std::unique_ptr<BlobFileReader> fresh_reader;
|
||||
s = blob_file_cache->OpenBlobFileReaderUncached(
|
||||
read_options, blob_idx.file_number(), &fresh_reader,
|
||||
read_options, blob_file, &fresh_reader,
|
||||
/*allow_footer_skip_retry=*/true);
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
@@ -843,8 +862,7 @@ Status BlobFilePartitionManager::ResolveBlobDirectWriteIndex(
|
||||
if (s.ok()) {
|
||||
blob_value->PinSelf(fresh_contents->data());
|
||||
CacheHandleGuard<BlobFileReader> ignored;
|
||||
blob_file_cache
|
||||
->RefreshBlobFileReader(blob_idx.file_number(), &fresh_reader, &ignored)
|
||||
blob_file_cache->RefreshBlobFileReader(blob_file, &fresh_reader, &ignored)
|
||||
.PermitUncheckedError();
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// (found in the LICENSE.Apache file in the root directory).
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
@@ -61,7 +62,8 @@ 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,
|
||||
BlobFileCache* blob_file_cache, BlobFileCompletionCallback* blob_callback,
|
||||
uint64_t blob_writer_max_buffer_size, 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,
|
||||
@@ -129,6 +131,11 @@ 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(
|
||||
@@ -260,6 +267,7 @@ 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_;
|
||||
|
||||
+280
-12
@@ -278,25 +278,31 @@ Status BlobFileReader::ReadFromFile(const RandomAccessFileReader* file_reader,
|
||||
return s;
|
||||
}
|
||||
|
||||
FSReadRequest read_req;
|
||||
read_req.offset = read_offset;
|
||||
read_req.len = read_size;
|
||||
if (file_reader->use_direct_io()) {
|
||||
constexpr char* scratch = nullptr;
|
||||
read_req.scratch = nullptr;
|
||||
AlignedBufferAllocationContext direct_io_context{direct_io_buffer};
|
||||
|
||||
s = file_reader->Read(io_options, read_offset, read_size, slice, scratch,
|
||||
&direct_io_context, &dbg);
|
||||
file_reader->Read(io_options, &read_req, &direct_io_context, &dbg);
|
||||
} else {
|
||||
buf->reset(new char[read_size]);
|
||||
|
||||
s = file_reader->Read(io_options, read_offset, read_size, slice, buf->get(),
|
||||
nullptr, &dbg);
|
||||
read_req.scratch = buf->get();
|
||||
file_reader->Read(io_options, &read_req, nullptr, &dbg);
|
||||
}
|
||||
s = std::move(read_req.status);
|
||||
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
*slice = read_req.result;
|
||||
|
||||
if (slice->size() != read_size) {
|
||||
return Status::Corruption("Failed to read data from blob file");
|
||||
return Status::Corruption("Incomplete blob read from " +
|
||||
file_reader->file_name() + " at offset " +
|
||||
std::to_string(read_offset) + ": expected " +
|
||||
std::to_string(read_size) + " bytes, got " +
|
||||
std::to_string(slice->size()));
|
||||
}
|
||||
|
||||
return Status::OK();
|
||||
@@ -330,7 +336,10 @@ Status BlobFileReader::GetBlob(
|
||||
|
||||
if (!IsValidBlobOffset(offset, key_size, value_size, file_size_,
|
||||
has_footer_)) {
|
||||
return Status::Corruption("Invalid blob offset");
|
||||
return Status::Corruption(
|
||||
"Invalid blob offset " + std::to_string(offset) + " for value size " +
|
||||
std::to_string(value_size) + " in " + file_reader_->file_name() +
|
||||
" (file size " + std::to_string(file_size_) + ")");
|
||||
}
|
||||
|
||||
if (compression_type != compression_type_) {
|
||||
@@ -416,6 +425,83 @@ 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 " + std::to_string(offset) + " for value size " +
|
||||
std::to_string(value_size) + " in " + file_reader_->file_name() +
|
||||
" (file size " + std::to_string(file_size_) + ")");
|
||||
}
|
||||
|
||||
// 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 [" + std::to_string(range_offset) + ", +" +
|
||||
std::to_string(range_length) + ") out of bounds for value size " +
|
||||
std::to_string(value_size) + " in " + file_reader_->file_name());
|
||||
}
|
||||
|
||||
// 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>>>&
|
||||
@@ -447,7 +533,10 @@ void BlobFileReader::MultiGetBlob(
|
||||
|
||||
if (!IsValidBlobOffset(offset, key_size, value_size, file_size_,
|
||||
has_footer_)) {
|
||||
*req->status = Status::Corruption("Invalid blob offset");
|
||||
*req->status = Status::Corruption(
|
||||
"Invalid blob offset " + std::to_string(offset) + " for value size " +
|
||||
std::to_string(value_size) + " in " + file_reader_->file_name() +
|
||||
" (file size " + std::to_string(file_size_) + ")");
|
||||
continue;
|
||||
}
|
||||
if (req->compression != compression_type_) {
|
||||
@@ -541,8 +630,11 @@ void BlobFileReader::MultiGetBlob(
|
||||
auto& read_req = read_reqs[j++];
|
||||
const auto& record_slice = read_req.result;
|
||||
if (read_req.status.ok() && record_slice.size() != read_req.len) {
|
||||
read_req.status =
|
||||
IOStatus::Corruption("Failed to read data from blob file");
|
||||
read_req.status = IOStatus::Corruption(
|
||||
"Incomplete blob read from " + file_reader_->file_name() +
|
||||
" at offset " + std::to_string(read_req.offset) + ": expected " +
|
||||
std::to_string(read_req.len) + " bytes, got " +
|
||||
std::to_string(record_slice.size()));
|
||||
}
|
||||
|
||||
*req->status = read_req.status;
|
||||
@@ -573,6 +665,182 @@ void BlobFileReader::MultiGetBlob(
|
||||
}
|
||||
}
|
||||
|
||||
void BlobFileReader::MultiGetBlobRange(
|
||||
const ReadOptions& read_options,
|
||||
autovector<std::pair<BlobRangeReadRequest*, std::unique_ptr<BlobContents>>>&
|
||||
blob_reqs,
|
||||
uint64_t* bytes_read) const {
|
||||
const size_t num_blobs = blob_reqs.size();
|
||||
assert(num_blobs > 0);
|
||||
assert(num_blobs <= MultiGetContext::MAX_BATCH_SIZE);
|
||||
|
||||
// Range reads are only issued for uncompressed blob references (a strict
|
||||
// sub-range of a compressed record cannot be decompressed in isolation).
|
||||
// Version::MultiGetBlobLazy rejects a compressed blob index before it reaches
|
||||
// here, so every request's blob index is uncompressed by contract; a
|
||||
// compressed blob file therefore means the blob index disagrees with the
|
||||
// file. Report that as the compression-type mismatch it is -- exactly like
|
||||
// the whole-value MultiGetBlob path -- rather than as a usage error. (Unlike
|
||||
// the single-read path, BlobSource has no per-request compression to check
|
||||
// for a range read, so this reader-level check is the range multi path's
|
||||
// compression backstop.)
|
||||
if (compression_type_ != kNoCompression) {
|
||||
for (auto& blob_req : blob_reqs) {
|
||||
assert(blob_req.first);
|
||||
assert(blob_req.first->status);
|
||||
*blob_req.first->status =
|
||||
Status::Corruption("Compression type mismatch when reading a blob");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
#ifndef NDEBUG
|
||||
for (size_t i = 0; i < num_blobs - 1; ++i) {
|
||||
assert(blob_reqs[i].first->offset + blob_reqs[i].first->range_offset <=
|
||||
blob_reqs[i + 1].first->offset +
|
||||
blob_reqs[i + 1].first->range_offset);
|
||||
}
|
||||
#endif // !NDEBUG
|
||||
|
||||
std::vector<FSReadRequest> read_reqs;
|
||||
uint64_t total_len = 0;
|
||||
read_reqs.reserve(num_blobs);
|
||||
for (size_t i = 0; i < num_blobs; ++i) {
|
||||
BlobRangeReadRequest* const req = blob_reqs[i].first;
|
||||
assert(req);
|
||||
assert(req->status);
|
||||
|
||||
const size_t key_size = req->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(req->offset, key_size, req->value_size, file_size_,
|
||||
has_footer_)) {
|
||||
*req->status = Status::Corruption(
|
||||
"Invalid blob offset " + std::to_string(req->offset) +
|
||||
" for value size " + std::to_string(req->value_size) + " in " +
|
||||
file_reader_->file_name() + " (file size " +
|
||||
std::to_string(file_size_) + ")");
|
||||
continue;
|
||||
}
|
||||
// The requested sub-range must lie within the value.
|
||||
if (req->range_offset > req->value_size ||
|
||||
req->range_length > req->value_size - req->range_offset) {
|
||||
*req->status = Status::InvalidArgument(
|
||||
"Blob range [" + std::to_string(req->range_offset) + ", +" +
|
||||
std::to_string(req->range_length) +
|
||||
") out of bounds for value size " + std::to_string(req->value_size) +
|
||||
" in " + file_reader_->file_name());
|
||||
continue;
|
||||
}
|
||||
|
||||
// Read only the requested bytes, at the value's file position plus the
|
||||
// range offset -- no record-header adjustment, no whole-record checksum.
|
||||
FSReadRequest read_req;
|
||||
read_req.offset = req->offset + req->range_offset;
|
||||
read_req.len = req->range_length;
|
||||
total_len += read_req.len;
|
||||
read_reqs.emplace_back(std::move(read_req));
|
||||
}
|
||||
|
||||
RecordTick(statistics_, BLOB_DB_BLOB_FILE_BYTES_READ, total_len);
|
||||
|
||||
if (read_reqs.empty()) {
|
||||
if (bytes_read) {
|
||||
*bytes_read = 0;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
Buffer buf;
|
||||
AlignedBuffer direct_io_buffer;
|
||||
|
||||
Status s;
|
||||
bool direct_io = file_reader_->use_direct_io();
|
||||
if (direct_io) {
|
||||
for (size_t i = 0; i < read_reqs.size(); ++i) {
|
||||
read_reqs[i].scratch = nullptr;
|
||||
}
|
||||
} else {
|
||||
buf.reset(new char[total_len]);
|
||||
std::ptrdiff_t pos = 0;
|
||||
for (size_t i = 0; i < read_reqs.size(); ++i) {
|
||||
read_reqs[i].scratch = buf.get() + pos;
|
||||
pos += read_reqs[i].len;
|
||||
}
|
||||
}
|
||||
TEST_SYNC_POINT("BlobFileReader::MultiGetBlobRange:ReadFromFile");
|
||||
PERF_COUNTER_ADD(blob_read_count, num_blobs);
|
||||
PERF_COUNTER_ADD(blob_read_byte, total_len);
|
||||
IOOptions opts;
|
||||
IODebugContext dbg;
|
||||
s = file_reader_->PrepareIOOptions(read_options, opts, &dbg);
|
||||
if (s.ok()) {
|
||||
AlignedBufferAllocationContext direct_io_context{&direct_io_buffer};
|
||||
s = file_reader_->MultiRead(opts, read_reqs.data(), read_reqs.size(),
|
||||
&direct_io_context, &dbg);
|
||||
}
|
||||
if (!s.ok()) {
|
||||
// Batch read failed; s is written to every request's status below, so these
|
||||
// per-request FS statuses carry nothing extra.
|
||||
for (auto& req : read_reqs) {
|
||||
req.status.PermitUncheckedError();
|
||||
}
|
||||
for (auto& blob_req : blob_reqs) {
|
||||
BlobRangeReadRequest* const req = blob_req.first;
|
||||
assert(req);
|
||||
assert(req->status);
|
||||
if (!req->status->IsCorruption() && !req->status->IsInvalidArgument()) {
|
||||
// Avoid overwriting per-request validation errors.
|
||||
*req->status = s;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
assert(s.ok());
|
||||
|
||||
TEST_SYNC_POINT_CALLBACK("BlobFileReader::MultiGetBlobRange:TamperWithResult",
|
||||
&read_reqs);
|
||||
|
||||
uint64_t total_bytes = 0;
|
||||
for (size_t i = 0, j = 0; i < num_blobs; ++i) {
|
||||
BlobRangeReadRequest* const req = blob_reqs[i].first;
|
||||
assert(req);
|
||||
assert(req->status);
|
||||
|
||||
if (!req->status->ok()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
assert(j < read_reqs.size());
|
||||
auto& read_req = read_reqs[j++];
|
||||
const Slice& range_slice = read_req.result;
|
||||
if (read_req.status.ok() && range_slice.size() != read_req.len) {
|
||||
read_req.status = IOStatus::Corruption(
|
||||
"Incomplete blob range read from " + file_reader_->file_name() +
|
||||
" at offset " + std::to_string(read_req.offset) + ": expected " +
|
||||
std::to_string(read_req.len) + " bytes, got " +
|
||||
std::to_string(range_slice.size()));
|
||||
}
|
||||
|
||||
*req->status = read_req.status;
|
||||
if (!req->status->ok()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// The blob is uncompressed, so the bytes read are exactly the requested
|
||||
// value bytes; copy them into an owned BlobContents (no decompression).
|
||||
BlobContentsCreator::Create(&blob_reqs[i].second, /*out_charge=*/nullptr,
|
||||
range_slice, kNoCompression,
|
||||
/*allocator=*/nullptr);
|
||||
total_bytes += range_slice.size();
|
||||
}
|
||||
|
||||
if (bytes_read) {
|
||||
*bytes_read = total_bytes;
|
||||
}
|
||||
}
|
||||
|
||||
Status BlobFileReader::VerifyBlob(const Slice& record_slice,
|
||||
const Slice& user_key, uint64_t value_size) {
|
||||
PERF_TIMER_GUARD(blob_checksum_time);
|
||||
|
||||
@@ -64,6 +64,23 @@ 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,
|
||||
@@ -71,6 +88,21 @@ class BlobFileReader {
|
||||
blob_reqs,
|
||||
uint64_t* bytes_read) const;
|
||||
|
||||
// Byte-range (partial) multi-read counterpart of MultiGetBlob: for each
|
||||
// request reads only its sub-range [offset + range_offset, +range_length) of
|
||||
// an *uncompressed* blob value, coalescing all requests into a single
|
||||
// MultiRead. Unlike MultiGetBlob it reads no record header/key, verifies no
|
||||
// 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). Each result owns a copy of its requested bytes.
|
||||
// Requests must be sorted ascending by effective read offset (offset +
|
||||
// range_offset) by the caller.
|
||||
void MultiGetBlobRange(
|
||||
const ReadOptions& read_options,
|
||||
autovector<std::pair<BlobRangeReadRequest*,
|
||||
std::unique_ptr<BlobContents>>>& blob_reqs,
|
||||
uint64_t* bytes_read) const;
|
||||
|
||||
CompressionType GetCompressionType() const { return compression_type_; }
|
||||
|
||||
uint64_t GetFileSize() const { return file_size_; }
|
||||
|
||||
+339
-16
@@ -5,9 +5,11 @@
|
||||
|
||||
#include "db/blob/blob_gen2_format.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "file/random_access_file_reader.h"
|
||||
#include "file/writable_file_writer.h"
|
||||
@@ -16,9 +18,56 @@
|
||||
#include "table/format.h"
|
||||
#include "util/cast_util.h"
|
||||
#include "util/coding.h"
|
||||
#include "util/crc32c.h"
|
||||
|
||||
namespace ROCKSDB_NAMESPACE {
|
||||
|
||||
namespace {
|
||||
|
||||
// Verifies a SimpleGen2Blob record's builtin checksum: the stored 4-byte
|
||||
// checksum (at record[payload_size + 1 ..], context-modified by the record's
|
||||
// file offset) against the checksum computed over the payload plus its 1-byte
|
||||
// compression marker. Returns OK, or a Corruption carrying debugging
|
||||
// information -- stored (with the per-offset context modifier removed),
|
||||
// computed, and checksum type, with CRC values unmasked so they can be compared
|
||||
// against a reference. Mirrors VerifyBlockChecksum() for the block-based
|
||||
// format, since a SimpleGen2Blob record's trailer uses the same
|
||||
// builtin-checksum scheme; shared by the scalar and batched readers so both
|
||||
// report the same diagnostics.
|
||||
Status VerifySimpleGen2BlobChecksum(ChecksumType checksum_type,
|
||||
uint32_t base_context_checksum,
|
||||
const char* record, size_t payload_size,
|
||||
uint64_t record_offset,
|
||||
const std::string& file_name) {
|
||||
uint32_t stored = DecodeFixed32(record + payload_size + 1);
|
||||
const uint32_t modifier =
|
||||
ChecksumModifierForContext(base_context_checksum, record_offset);
|
||||
stored -= modifier;
|
||||
const uint32_t computed = ComputeBuiltinChecksumWithLastByte(
|
||||
checksum_type, record, payload_size, record[payload_size]);
|
||||
if (stored == computed) {
|
||||
return Status::OK();
|
||||
}
|
||||
// Unmask CRC values (as VerifyBlockChecksum does) so a reader of the error
|
||||
// can compare against a reference checksum.
|
||||
uint32_t stored_for_msg = stored;
|
||||
uint32_t computed_for_msg = computed;
|
||||
if (checksum_type == kCRC32c) {
|
||||
stored_for_msg = crc32c::Unmask(stored);
|
||||
computed_for_msg = crc32c::Unmask(computed);
|
||||
}
|
||||
return Status::Corruption("SimpleGen2 blob record checksum mismatch: stored" +
|
||||
std::string(modifier ? "(context removed)" : "") +
|
||||
" = " + std::to_string(stored_for_msg) +
|
||||
", computed = " + std::to_string(computed_for_msg) +
|
||||
", type = " + std::to_string(checksum_type) +
|
||||
" in " + file_name + " offset " +
|
||||
std::to_string(record_offset) + " size " +
|
||||
std::to_string(payload_size));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Status ReadAndVerifySimpleGen2BlobRecord(
|
||||
const ReadOptions& read_options, RandomAccessFileReader* file,
|
||||
uint64_t record_offset, size_t payload_size, size_t record_size,
|
||||
@@ -33,14 +82,17 @@ Status ReadAndVerifySimpleGen2BlobRecord(
|
||||
IODebugContext dbg;
|
||||
Status s = file->PrepareIOOptions(read_options, opts, &dbg);
|
||||
if (s.ok()) {
|
||||
s = file->Read(opts, record_offset, record_size, &result, buf, nullptr,
|
||||
&dbg);
|
||||
s = file->Read(record_offset, record_size, opts, &result, buf, &dbg);
|
||||
}
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
if (result.size() != record_size) {
|
||||
return Status::Corruption("Could not read complete blob record");
|
||||
return Status::Corruption("Incomplete blob record read from " +
|
||||
file->file_name() + " at offset " +
|
||||
std::to_string(record_offset) + ": expected " +
|
||||
std::to_string(record_size) + " bytes, got " +
|
||||
std::to_string(result.size()));
|
||||
}
|
||||
// With mmap reads the data lands outside `buf`; copy it in so the caller can
|
||||
// rely on `buf` owning the bytes (this is the only copy on the mmap path).
|
||||
@@ -54,28 +106,299 @@ Status ReadAndVerifySimpleGen2BlobRecord(
|
||||
static_cast<CompressionType>(record[payload_size]);
|
||||
if (compression != expected_compression) {
|
||||
return Status::Corruption(
|
||||
"Blob record compression does not match blob index");
|
||||
"Blob record compression mismatch in " + file->file_name() +
|
||||
" at offset " + std::to_string(record_offset) + ": index expects " +
|
||||
std::to_string(static_cast<int>(expected_compression)) +
|
||||
", record has " + std::to_string(static_cast<int>(compression)));
|
||||
}
|
||||
|
||||
if (read_options.verify_checksums) {
|
||||
uint32_t stored = DecodeFixed32(record + payload_size + 1);
|
||||
stored -= ChecksumModifierForContext(base_context_checksum, record_offset);
|
||||
const uint32_t computed = ComputeBuiltinChecksumWithLastByte(
|
||||
checksum_type, record, payload_size, record[payload_size]);
|
||||
if (stored != computed) {
|
||||
return Status::Corruption("Blob record checksum mismatch in " +
|
||||
file->file_name() + " offset " +
|
||||
std::to_string(record_offset) + " size " +
|
||||
std::to_string(payload_size));
|
||||
const Status checksum_status = VerifySimpleGen2BlobChecksum(
|
||||
checksum_type, base_context_checksum, record, payload_size,
|
||||
record_offset, file->file_name());
|
||||
if (!checksum_status.ok()) {
|
||||
return checksum_status;
|
||||
}
|
||||
}
|
||||
|
||||
// The compression marker matched the blob index above, but SimpleGen2Blob
|
||||
// payloads are currently written uncompressed only (see
|
||||
// WriteSimpleGen2BlobRecord), so a record that actually carries a compression
|
||||
// type is not readable here. This guards a corrupt or forward-incompatible
|
||||
// record whose (compressed) marker happened to agree with a (compressed)
|
||||
// index.
|
||||
if (compression != kNoCompression) {
|
||||
return Status::Corruption("Blob record compression is not supported");
|
||||
return Status::Corruption("Blob record compression " +
|
||||
std::to_string(static_cast<int>(compression)) +
|
||||
" is not supported in " + file->file_name() +
|
||||
" at offset " + std::to_string(record_offset));
|
||||
}
|
||||
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 (compression " +
|
||||
std::to_string(static_cast<int>(expected_compression)) + ") in " +
|
||||
file->file_name() + " at offset " + std::to_string(record_offset));
|
||||
}
|
||||
|
||||
// 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 [" + std::to_string(range_offset) + ", +" +
|
||||
std::to_string(range_length) + ") out of bounds for payload size " +
|
||||
std::to_string(payload_size) + " in " + file->file_name() +
|
||||
" at offset " + std::to_string(record_offset));
|
||||
}
|
||||
|
||||
Slice result;
|
||||
IOOptions opts;
|
||||
IODebugContext dbg;
|
||||
Status s = file->PrepareIOOptions(read_options, opts, &dbg);
|
||||
if (s.ok()) {
|
||||
s = file->Read(record_offset + range_offset, range_length, opts, &result,
|
||||
buf, &dbg);
|
||||
}
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
if (result.size() != range_length) {
|
||||
return Status::Corruption("Incomplete blob range read from " +
|
||||
file->file_name() + " at offset " +
|
||||
std::to_string(record_offset + range_offset) +
|
||||
": expected " + std::to_string(range_length) +
|
||||
" bytes, got " + std::to_string(result.size()));
|
||||
}
|
||||
// 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();
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// One record's read description for the batched SimpleGen2Blob readers below:
|
||||
// where/how much to read, where to put it, and where to report the outcome.
|
||||
struct Gen2ReadSlot {
|
||||
uint64_t offset = 0;
|
||||
size_t len = 0;
|
||||
char* buf = nullptr;
|
||||
Status* status = nullptr;
|
||||
};
|
||||
|
||||
// Issues a single MultiRead for the records described by `slots` and copies
|
||||
// each result into its buf, setting *slots[i].status. Shared by the
|
||||
// whole-record and range batch readers; per-record format checks (compression
|
||||
// marker / checksum) are done by the whole-record caller afterwards from the
|
||||
// (now populated) buf.
|
||||
void MultiReadGen2(const ReadOptions& read_options,
|
||||
RandomAccessFileReader* file,
|
||||
std::vector<Gen2ReadSlot>& slots) {
|
||||
assert(file != nullptr);
|
||||
assert(!slots.empty());
|
||||
|
||||
// RandomAccessFileReader::MultiRead requires the requests sorted ascending by
|
||||
// file offset -- it asserts this, and in direct-I/O mode it aligns and merges
|
||||
// only consecutive requests, so unsorted input reads the wrong bytes. The
|
||||
// callers group records by SST but not by offset, so sort here. Each slot
|
||||
// carries its own output buf/status pointer, so sorting does not disturb
|
||||
// result routing.
|
||||
std::sort(slots.begin(), slots.end(),
|
||||
[](const Gen2ReadSlot& a, const Gen2ReadSlot& b) {
|
||||
return a.offset < b.offset;
|
||||
});
|
||||
|
||||
const size_t num = slots.size();
|
||||
std::vector<FSReadRequest> read_reqs;
|
||||
read_reqs.reserve(num);
|
||||
for (size_t i = 0; i < num; ++i) {
|
||||
FSReadRequest read_req;
|
||||
read_req.offset = slots[i].offset;
|
||||
read_req.len = slots[i].len;
|
||||
read_reqs.emplace_back(std::move(read_req));
|
||||
}
|
||||
|
||||
AlignedBuffer direct_io_buffer;
|
||||
const bool direct_io = file->use_direct_io();
|
||||
if (direct_io) {
|
||||
for (size_t i = 0; i < num; ++i) {
|
||||
read_reqs[i].scratch = nullptr;
|
||||
}
|
||||
} else {
|
||||
for (size_t i = 0; i < num; ++i) {
|
||||
read_reqs[i].scratch = slots[i].buf;
|
||||
}
|
||||
}
|
||||
|
||||
IOOptions opts;
|
||||
IODebugContext dbg;
|
||||
Status s = file->PrepareIOOptions(read_options, opts, &dbg);
|
||||
if (s.ok()) {
|
||||
AlignedBufferAllocationContext direct_io_context{&direct_io_buffer};
|
||||
s = file->MultiRead(opts, read_reqs.data(), read_reqs.size(),
|
||||
&direct_io_context, &dbg);
|
||||
}
|
||||
if (!s.ok()) {
|
||||
// Batch read failed; s is written to every slot's status below, so these
|
||||
// per-request FS statuses carry nothing extra.
|
||||
for (auto& read_req : read_reqs) {
|
||||
read_req.status.PermitUncheckedError();
|
||||
}
|
||||
for (size_t i = 0; i < num; ++i) {
|
||||
*slots[i].status = s;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < num; ++i) {
|
||||
FSReadRequest& read_req = read_reqs[i];
|
||||
if (read_req.status.ok() && read_req.result.size() != read_req.len) {
|
||||
read_req.status = IOStatus::Corruption(
|
||||
"Incomplete blob record read from " + file->file_name() +
|
||||
" at offset " + std::to_string(read_req.offset) + ": expected " +
|
||||
std::to_string(read_req.len) + " bytes, got " +
|
||||
std::to_string(read_req.result.size()));
|
||||
}
|
||||
*slots[i].status = read_req.status;
|
||||
if (!slots[i].status->ok()) {
|
||||
continue;
|
||||
}
|
||||
// With mmap/direct reads the data lands outside the caller's buf; copy it
|
||||
// in so the caller can rely on buf owning the bytes.
|
||||
if (read_req.result.data() != slots[i].buf) {
|
||||
memcpy(slots[i].buf, read_req.result.data(), read_req.len);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void ReadAndVerifySimpleGen2BlobRecords(const ReadOptions& read_options,
|
||||
RandomAccessFileReader* file,
|
||||
ChecksumType checksum_type,
|
||||
uint32_t base_context_checksum,
|
||||
size_t num_records,
|
||||
SimpleGen2RecordReadRequest* reqs) {
|
||||
assert(file != nullptr);
|
||||
assert(num_records > 0);
|
||||
|
||||
std::vector<Gen2ReadSlot> slots;
|
||||
slots.reserve(num_records);
|
||||
for (size_t i = 0; i < num_records; ++i) {
|
||||
assert(reqs[i].buf != nullptr);
|
||||
assert(reqs[i].status != nullptr);
|
||||
assert(reqs[i].record_size ==
|
||||
reqs[i].payload_size + kSimpleGen2BlobTrailerSize);
|
||||
slots.push_back({reqs[i].record_offset, reqs[i].record_size, reqs[i].buf,
|
||||
reqs[i].status});
|
||||
}
|
||||
|
||||
MultiReadGen2(read_options, file, slots);
|
||||
|
||||
for (size_t i = 0; i < num_records; ++i) {
|
||||
if (!reqs[i].status->ok()) {
|
||||
continue;
|
||||
}
|
||||
const char* record = reqs[i].buf;
|
||||
const size_t payload_size = reqs[i].payload_size;
|
||||
const CompressionType compression =
|
||||
static_cast<CompressionType>(record[payload_size]);
|
||||
if (compression != reqs[i].expected_compression) {
|
||||
*reqs[i].status = Status::Corruption(
|
||||
"Blob record compression mismatch in " + file->file_name() +
|
||||
" at offset " + std::to_string(reqs[i].record_offset) +
|
||||
": index expects " +
|
||||
std::to_string(static_cast<int>(reqs[i].expected_compression)) +
|
||||
", record has " + std::to_string(static_cast<int>(compression)));
|
||||
continue;
|
||||
}
|
||||
if (read_options.verify_checksums) {
|
||||
*reqs[i].status = VerifySimpleGen2BlobChecksum(
|
||||
checksum_type, base_context_checksum, record, payload_size,
|
||||
reqs[i].record_offset, file->file_name());
|
||||
if (!reqs[i].status->ok()) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// See ReadAndVerifySimpleGen2BlobRecord: the marker matched the index, but
|
||||
// only uncompressed SimpleGen2Blob payloads are currently supported.
|
||||
if (compression != kNoCompression) {
|
||||
*reqs[i].status = Status::Corruption(
|
||||
"Blob record compression " +
|
||||
std::to_string(static_cast<int>(compression)) +
|
||||
" is not supported in " + file->file_name() + " at offset " +
|
||||
std::to_string(reqs[i].record_offset));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ReadSimpleGen2BlobRanges(const ReadOptions& read_options,
|
||||
RandomAccessFileReader* file, size_t num_records,
|
||||
SimpleGen2RangeReadRequest* reqs) {
|
||||
assert(file != nullptr);
|
||||
assert(num_records > 0);
|
||||
|
||||
std::vector<Gen2ReadSlot> slots;
|
||||
slots.reserve(num_records);
|
||||
for (size_t i = 0; i < num_records; ++i) {
|
||||
assert(reqs[i].buf != nullptr);
|
||||
assert(reqs[i].status != nullptr);
|
||||
// A strict sub-range of a compressed payload cannot be decompressed in
|
||||
// isolation; callers resolve such payloads whole and slice instead.
|
||||
if (reqs[i].expected_compression != kNoCompression) {
|
||||
*reqs[i].status = Status::Corruption(
|
||||
"Cannot range-read a compressed blob (compression " +
|
||||
std::to_string(static_cast<int>(reqs[i].expected_compression)) +
|
||||
") in " + file->file_name() + " at offset " +
|
||||
std::to_string(reqs[i].record_offset));
|
||||
continue;
|
||||
}
|
||||
// The requested sub-range must lie within the payload (the trailer that
|
||||
// follows the payload is never part of a range read).
|
||||
if (reqs[i].range_offset > reqs[i].payload_size ||
|
||||
reqs[i].range_length > reqs[i].payload_size - reqs[i].range_offset) {
|
||||
*reqs[i].status = Status::InvalidArgument(
|
||||
"Blob range [" + std::to_string(reqs[i].range_offset) + ", +" +
|
||||
std::to_string(reqs[i].range_length) +
|
||||
") out of bounds for payload size " +
|
||||
std::to_string(reqs[i].payload_size) + " in " + file->file_name() +
|
||||
" at offset " + std::to_string(reqs[i].record_offset));
|
||||
continue;
|
||||
}
|
||||
slots.push_back({reqs[i].record_offset + reqs[i].range_offset,
|
||||
reqs[i].range_length, reqs[i].buf, reqs[i].status});
|
||||
}
|
||||
|
||||
if (slots.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// slots only covers requests that passed validation above; a failed
|
||||
// validation left *reqs[i].status non-OK and is skipped here.
|
||||
MultiReadGen2(read_options, file, slots);
|
||||
}
|
||||
|
||||
IOStatus WriteSimpleGen2BlobRecord(WritableFileWriter* file,
|
||||
const WriteOptions& write_options,
|
||||
ChecksumType checksum_type,
|
||||
@@ -100,12 +423,12 @@ IOStatus WriteSimpleGen2BlobRecord(WritableFileWriter* file,
|
||||
return io_s;
|
||||
}
|
||||
if (!payload.empty()) {
|
||||
io_s = file->Append(opts, payload);
|
||||
io_s = file->Append(payload, opts);
|
||||
if (!io_s.ok()) {
|
||||
return io_s;
|
||||
}
|
||||
}
|
||||
return file->Append(opts, Slice(trailer.data(), trailer.size()));
|
||||
return file->Append(Slice(trailer.data(), trailer.size()), opts);
|
||||
}
|
||||
|
||||
} // namespace ROCKSDB_NAMESPACE
|
||||
@@ -73,6 +73,75 @@ 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);
|
||||
|
||||
// One whole-record request in a batched SimpleGen2Blob read (see
|
||||
// ReadAndVerifySimpleGen2BlobRecords). Mirrors the scalar
|
||||
// ReadAndVerifySimpleGen2BlobRecord inputs, with the read bytes going into
|
||||
// caller-provided `buf` (capacity >= record_size) and the per-record outcome in
|
||||
// `*status`.
|
||||
struct SimpleGen2RecordReadRequest {
|
||||
uint64_t record_offset = 0;
|
||||
size_t payload_size = 0;
|
||||
size_t record_size = 0; // == payload_size + kSimpleGen2BlobTrailerSize
|
||||
CompressionType expected_compression = kNoCompression;
|
||||
char* buf = nullptr;
|
||||
Status* status = nullptr;
|
||||
};
|
||||
|
||||
// One sub-range request in a batched SimpleGen2Blob range read (see
|
||||
// ReadSimpleGen2BlobRanges). Mirrors the scalar ReadSimpleGen2BlobRange inputs.
|
||||
struct SimpleGen2RangeReadRequest {
|
||||
uint64_t record_offset = 0;
|
||||
size_t payload_size = 0;
|
||||
uint64_t range_offset = 0;
|
||||
size_t range_length = 0;
|
||||
CompressionType expected_compression = kNoCompression;
|
||||
char* buf = nullptr;
|
||||
Status* status = nullptr;
|
||||
};
|
||||
|
||||
// Batch counterpart of ReadAndVerifySimpleGen2BlobRecord: reads `num_records`
|
||||
// whole records from `file` in a single MultiRead, then per record verifies the
|
||||
// compression marker and (when read_options.verify_checksums) the
|
||||
// context-modified checksum, copying the record into reqs[i].buf. Per-record
|
||||
// outcome is written to *reqs[i].status; on success reqs[i].buf[0,
|
||||
// payload_size) holds the verified payload (the trailer sits unused at the
|
||||
// tail). Requests may be given in any order; they are sorted internally, as
|
||||
// RandomAccessFileReader::MultiRead requires ascending offsets.
|
||||
void ReadAndVerifySimpleGen2BlobRecords(const ReadOptions& read_options,
|
||||
RandomAccessFileReader* file,
|
||||
ChecksumType checksum_type,
|
||||
uint32_t base_context_checksum,
|
||||
size_t num_records,
|
||||
SimpleGen2RecordReadRequest* reqs);
|
||||
|
||||
// Batch counterpart of ReadSimpleGen2BlobRange: reads the requested sub-range
|
||||
// of `num_records` *uncompressed* payloads from `file` in a single MultiRead
|
||||
// (no trailer read, no checksum). Per-record outcome is in *reqs[i].status; on
|
||||
// success reqs[i].buf[0, range_length) holds the requested bytes. Requests may
|
||||
// be given in any order; they are sorted internally, as
|
||||
// RandomAccessFileReader::MultiRead requires ascending offsets.
|
||||
void ReadSimpleGen2BlobRanges(const ReadOptions& read_options,
|
||||
RandomAccessFileReader* file, size_t num_records,
|
||||
SimpleGen2RangeReadRequest* reqs);
|
||||
|
||||
// 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
|
||||
|
||||
@@ -29,7 +29,7 @@ Status BlobLogSequentialReader::ReadSlice(uint64_t size, Slice* slice,
|
||||
|
||||
StopWatch read_sw(clock_, statistics_, BLOB_DB_BLOB_FILE_READ_MICROS);
|
||||
// TODO: rate limit `BlobLogSequentialReader` reads (it appears unused?)
|
||||
Status s = file_->Read(IOOptions(), next_byte_, static_cast<size_t>(size),
|
||||
Status s = file_->Read(next_byte_, static_cast<size_t>(size), IOOptions(),
|
||||
slice, buf, nullptr);
|
||||
next_byte_ += size;
|
||||
if (!s.ok()) {
|
||||
|
||||
@@ -40,7 +40,7 @@ Status BlobLogWriter::Sync(const WriteOptions& write_options) {
|
||||
IOOptions opts;
|
||||
Status s = WritableFileWriter::PrepareIOOptions(write_options, opts);
|
||||
if (s.ok()) {
|
||||
s = dest_->Sync(opts, use_fsync_);
|
||||
s = use_fsync_ ? dest_->Fsync(opts) : dest_->Sync(opts);
|
||||
}
|
||||
if (s.ok()) {
|
||||
RecordTick(statistics_, BLOB_DB_BLOB_FILE_SYNCED);
|
||||
@@ -58,7 +58,7 @@ Status BlobLogWriter::WriteHeader(const WriteOptions& write_options,
|
||||
IOOptions opts;
|
||||
Status s = WritableFileWriter::PrepareIOOptions(write_options, opts);
|
||||
if (s.ok()) {
|
||||
s = dest_->Append(opts, Slice(str));
|
||||
s = dest_->Append(Slice(str), opts);
|
||||
}
|
||||
if (s.ok()) {
|
||||
block_offset_ += str.size();
|
||||
@@ -92,7 +92,7 @@ Status BlobLogWriter::AppendFooter(const WriteOptions& write_options,
|
||||
IOOptions opts;
|
||||
s = WritableFileWriter::PrepareIOOptions(write_options, opts);
|
||||
if (s.ok()) {
|
||||
s = dest_->Append(opts, Slice(str));
|
||||
s = dest_->Append(Slice(str), opts);
|
||||
}
|
||||
if (s.ok()) {
|
||||
block_offset_ += str.size();
|
||||
@@ -181,13 +181,13 @@ Status BlobLogWriter::EmitPhysicalRecord(const WriteOptions& write_options,
|
||||
IOOptions opts;
|
||||
Status s = WritableFileWriter::PrepareIOOptions(write_options, opts);
|
||||
if (s.ok()) {
|
||||
s = dest_->Append(opts, Slice(headerbuf));
|
||||
s = dest_->Append(Slice(headerbuf), opts);
|
||||
}
|
||||
if (s.ok()) {
|
||||
s = dest_->Append(opts, key);
|
||||
s = dest_->Append(key, opts);
|
||||
}
|
||||
if (s.ok()) {
|
||||
s = dest_->Append(opts, val);
|
||||
s = dest_->Append(val, opts);
|
||||
}
|
||||
if (do_flush_ && s.ok()) {
|
||||
s = dest_->Flush(opts);
|
||||
|
||||
@@ -14,10 +14,21 @@
|
||||
|
||||
namespace ROCKSDB_NAMESPACE {
|
||||
|
||||
// Non-owning metadata needed when opening a blob file for reading. The
|
||||
// checksum slices must remain valid while this object is in use. A file without
|
||||
// finalized checksum metadata, such as an active direct-write blob file, uses
|
||||
// empty slices for both checksum fields.
|
||||
struct BlobFileOpenInfo {
|
||||
uint64_t file_number = 0;
|
||||
Slice file_checksum;
|
||||
Slice file_checksum_func_name;
|
||||
};
|
||||
|
||||
// A read Blob request structure for use in BlobSource::MultiGetBlob and
|
||||
// BlobFileReader::MultiGetBlob.
|
||||
struct BlobReadRequest {
|
||||
// User key to lookup the paired blob
|
||||
// TODO: consider simplifying to copied Slice?
|
||||
const Slice* user_key = nullptr;
|
||||
|
||||
// File offset in bytes
|
||||
@@ -52,7 +63,51 @@ struct BlobReadRequest {
|
||||
};
|
||||
|
||||
using BlobFileReadRequests =
|
||||
std::tuple<uint64_t /* file_number */, uint64_t /* file_size */,
|
||||
std::tuple<BlobFileOpenInfo, uint64_t /* file_size */,
|
||||
autovector<BlobReadRequest>>;
|
||||
|
||||
// A byte-range (partial) blob read request for the lazy blob-read multi
|
||||
// primitives (BlobFileReader::MultiGetBlobRange /
|
||||
// BlobSource::MultiGetBlobRange). Unlike BlobReadRequest (whole value), it
|
||||
// reads only the sub-range [range_offset, range_offset + range_length) of an
|
||||
// *uncompressed* blob value, skipping whole-record checksum verification and
|
||||
// blob-cache population -- the multi-read counterpart of
|
||||
// BlobSource::GetBlobRange / BlobFileReader::GetBlobRange.
|
||||
struct BlobRangeReadRequest {
|
||||
// User key that pairs with the blob value (used for offset validation).
|
||||
Slice user_key;
|
||||
|
||||
// The blob value's file offset and full (logical == on-disk, uncompressed)
|
||||
// size, from the BlobIndex.
|
||||
uint64_t offset = 0;
|
||||
uint64_t value_size = 0;
|
||||
|
||||
// The requested sub-range within the value. `range_length` is the number of
|
||||
// bytes to read; the caller must ensure range_offset + range_length <=
|
||||
// value_size (it clamps before building the request).
|
||||
uint64_t range_offset = 0;
|
||||
size_t range_length = 0;
|
||||
|
||||
// Output parameter set to point to the requested bytes, and the read status.
|
||||
PinnableSlice* result = nullptr;
|
||||
Status* status = nullptr;
|
||||
|
||||
BlobRangeReadRequest(Slice _user_key, uint64_t _offset, uint64_t _value_size,
|
||||
uint64_t _range_offset, size_t _range_length,
|
||||
PinnableSlice* _result, Status* _status)
|
||||
: user_key(_user_key),
|
||||
offset(_offset),
|
||||
value_size(_value_size),
|
||||
range_offset(_range_offset),
|
||||
range_length(_range_length),
|
||||
result(_result),
|
||||
status(_status) {}
|
||||
|
||||
BlobRangeReadRequest() = default;
|
||||
};
|
||||
|
||||
using BlobFileRangeReadRequests =
|
||||
std::tuple<BlobFileOpenInfo, uint64_t /* file_size */,
|
||||
autovector<BlobRangeReadRequest>>;
|
||||
|
||||
} // namespace ROCKSDB_NAMESPACE
|
||||
+634
-59
@@ -7,6 +7,7 @@
|
||||
|
||||
#include <cassert>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "cache/cache_reservation_manager.h"
|
||||
#include "cache/charged_cache.h"
|
||||
@@ -36,6 +37,103 @@ 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,
|
||||
const BlobFileOpenInfo& blob_file,
|
||||
const ReadFn& read) {
|
||||
CacheHandleGuard<BlobFileReader> blob_file_reader;
|
||||
Status s = blob_file_cache->GetBlobFileReader(read_options, blob_file,
|
||||
&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(blob_file.file_number);
|
||||
|
||||
std::unique_ptr<BlobFileReader> fresh_reader;
|
||||
s = blob_file_cache->OpenBlobFileReaderUncached(
|
||||
read_options, blob_file, &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(blob_file, &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,
|
||||
@@ -175,9 +273,9 @@ Status BlobSource::InsertEntryIntoCache(const Slice& key, BlobContents* value,
|
||||
}
|
||||
|
||||
Status BlobSource::GetBlob(const ReadOptions& read_options,
|
||||
const Slice& user_key, uint64_t file_number,
|
||||
uint64_t offset, uint64_t file_size,
|
||||
uint64_t value_size,
|
||||
const Slice& user_key,
|
||||
const BlobFileOpenInfo& blob_file, uint64_t offset,
|
||||
uint64_t file_size, uint64_t value_size,
|
||||
CompressionType compression_type,
|
||||
FilePrefetchBuffer* prefetch_buffer,
|
||||
PinnableSlice* value, uint64_t* bytes_read) {
|
||||
@@ -185,7 +283,8 @@ Status BlobSource::GetBlob(const ReadOptions& read_options,
|
||||
|
||||
Status s;
|
||||
|
||||
const CacheKey cache_key = GetCacheKey(file_number, file_size, offset);
|
||||
const CacheKey cache_key =
|
||||
GetCacheKey(blob_file.file_number, file_size, offset);
|
||||
|
||||
CacheHandleGuard<BlobContents> blob_handle;
|
||||
|
||||
@@ -228,66 +327,36 @@ 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 = 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();
|
||||
}
|
||||
}
|
||||
s = ReadBlobWithReaderRetry(
|
||||
blob_file_cache_, read_options, blob_file, [&](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);
|
||||
});
|
||||
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) {
|
||||
@@ -308,6 +377,94 @@ Status BlobSource::GetBlob(const ReadOptions& read_options,
|
||||
return s;
|
||||
}
|
||||
|
||||
Status BlobSource::GetBlobRange(const ReadOptions& read_options,
|
||||
const Slice& user_key,
|
||||
const BlobFileOpenInfo& blob_file,
|
||||
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(blob_file.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) {
|
||||
s = Status::Incomplete("Cannot read blob(s): no disk I/O allowed");
|
||||
return s;
|
||||
}
|
||||
|
||||
// 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, blob_file, [&](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,
|
||||
@@ -348,7 +505,8 @@ Status BlobSource::GetSimpleGen2Blob(
|
||||
|
||||
const bool no_io = read_options.read_tier == kBlockCacheTier;
|
||||
if (no_io) {
|
||||
return Status::Incomplete("Cannot read blob(s): no disk I/O allowed");
|
||||
s = Status::Incomplete("Cannot read blob(s): no disk I/O allowed");
|
||||
return s;
|
||||
}
|
||||
|
||||
// Cache miss (or no cache configured). Read the record into a buffer
|
||||
@@ -379,6 +537,11 @@ 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
|
||||
@@ -398,6 +561,266 @@ 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) {
|
||||
s = Status::Incomplete("Cannot read blob(s): no disk I/O allowed");
|
||||
return s;
|
||||
}
|
||||
|
||||
// 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::MultiGetSimpleGen2Blob(
|
||||
const ReadOptions& read_options, const OffsetableCacheKey& base_cache_key,
|
||||
RandomAccessFileReader* file, ChecksumType checksum_type,
|
||||
uint32_t base_context_checksum, size_t num_records,
|
||||
SimpleGen2BlobReadRequest* reqs) {
|
||||
assert(file);
|
||||
if (num_records == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const bool no_io = read_options.read_tier == kBlockCacheTier;
|
||||
MemoryAllocator* const allocator = (blob_cache_ && read_options.fill_cache)
|
||||
? blob_cache_.get()->memory_allocator()
|
||||
: nullptr;
|
||||
|
||||
// Records that missed the cache and must be read from disk, in read order;
|
||||
// each owns its buffer until we build a BlobContents from it below.
|
||||
struct Pending {
|
||||
size_t idx;
|
||||
CacheAllocationPtr buf;
|
||||
uint64_t record_size;
|
||||
};
|
||||
std::vector<Pending> pending;
|
||||
std::vector<SimpleGen2RecordReadRequest> read_reqs;
|
||||
|
||||
for (size_t i = 0; i < num_records; ++i) {
|
||||
SimpleGen2BlobReadRequest& req = reqs[i];
|
||||
assert(req.result);
|
||||
assert(req.status);
|
||||
|
||||
const uint64_t record_size = req.payload_size + kSimpleGen2BlobTrailerSize;
|
||||
const CacheKey cache_key =
|
||||
GetSimpleGen2BlobCacheKey(base_cache_key, req.record_offset);
|
||||
|
||||
if (blob_cache_) {
|
||||
CacheHandleGuard<BlobContents> blob_handle;
|
||||
const Status cs = GetBlobFromCache(cache_key.AsSlice(), &blob_handle);
|
||||
if (cs.ok()) {
|
||||
*req.status = cs;
|
||||
PinCachedBlob(&blob_handle, req.result);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (no_io) {
|
||||
*req.status =
|
||||
Status::Incomplete("Cannot read blob(s): no disk I/O allowed");
|
||||
continue;
|
||||
}
|
||||
|
||||
CacheAllocationPtr buf =
|
||||
AllocateBlock(static_cast<size_t>(record_size), allocator);
|
||||
read_reqs.push_back(SimpleGen2RecordReadRequest{
|
||||
req.record_offset, static_cast<size_t>(req.payload_size),
|
||||
static_cast<size_t>(record_size), req.expected_compression, buf.get(),
|
||||
req.status});
|
||||
pending.push_back(Pending{i, std::move(buf), record_size});
|
||||
}
|
||||
|
||||
if (read_reqs.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
ReadAndVerifySimpleGen2BlobRecords(read_options, file, checksum_type,
|
||||
base_context_checksum, read_reqs.size(),
|
||||
read_reqs.data());
|
||||
|
||||
for (size_t k = 0; k < pending.size(); ++k) {
|
||||
SimpleGen2BlobReadRequest& req = reqs[pending[k].idx];
|
||||
if (!req.status->ok()) {
|
||||
continue;
|
||||
}
|
||||
const uint64_t record_size = pending[k].record_size;
|
||||
std::unique_ptr<BlobContents> blob_contents(new BlobContents(
|
||||
std::move(pending[k].buf), static_cast<size_t>(req.payload_size)));
|
||||
|
||||
RecordTick(statistics_, BLOB_DB_BLOB_FILE_BYTES_READ, record_size);
|
||||
PERF_COUNTER_ADD(blob_read_count, 1);
|
||||
PERF_COUNTER_ADD(blob_read_byte, record_size);
|
||||
if (read_options.io_activity == Env::IOActivity::kLazyResolve) {
|
||||
RecordLazyRead(statistics_, record_size);
|
||||
}
|
||||
|
||||
if (blob_cache_ && read_options.fill_cache) {
|
||||
const CacheKey cache_key =
|
||||
GetSimpleGen2BlobCacheKey(base_cache_key, req.record_offset);
|
||||
CacheHandleGuard<BlobContents> blob_handle;
|
||||
const Status ps =
|
||||
PutBlobIntoCache(cache_key.AsSlice(), &blob_contents, &blob_handle);
|
||||
if (!ps.ok()) {
|
||||
*req.status = ps;
|
||||
} else {
|
||||
PinCachedBlob(&blob_handle, req.result);
|
||||
}
|
||||
} else {
|
||||
PinOwnedBlob(&blob_contents, req.result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void BlobSource::MultiGetSimpleGen2BlobRange(
|
||||
const ReadOptions& read_options, const OffsetableCacheKey& base_cache_key,
|
||||
RandomAccessFileReader* file, size_t num_records,
|
||||
SimpleGen2BlobRangeReadRequest* reqs) {
|
||||
assert(file);
|
||||
// Range reads are only issued while resolving a lazy result (partial reads
|
||||
// are lazy-only), so the lazy read stats below are recorded unconditionally.
|
||||
assert(read_options.io_activity == Env::IOActivity::kLazyResolve);
|
||||
if (num_records == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const bool no_io = read_options.read_tier == kBlockCacheTier;
|
||||
|
||||
struct Pending {
|
||||
size_t idx;
|
||||
CacheAllocationPtr buf;
|
||||
};
|
||||
std::vector<Pending> pending;
|
||||
std::vector<SimpleGen2RangeReadRequest> read_reqs;
|
||||
|
||||
for (size_t i = 0; i < num_records; ++i) {
|
||||
SimpleGen2BlobRangeReadRequest& req = reqs[i];
|
||||
assert(req.result);
|
||||
assert(req.status);
|
||||
|
||||
const CacheKey cache_key =
|
||||
GetSimpleGen2BlobCacheKey(base_cache_key, req.record_offset);
|
||||
|
||||
// Probe the whole-payload cache; on a hit slice the requested sub-range.
|
||||
if (blob_cache_) {
|
||||
CacheHandleGuard<BlobContents> blob_handle;
|
||||
const Status cs = GetBlobFromCache(cache_key.AsSlice(), &blob_handle);
|
||||
if (cs.ok()) {
|
||||
*req.status = cs;
|
||||
PinCacheHitSubRange(&blob_handle, req.range_offset, req.range_length,
|
||||
req.result);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (no_io) {
|
||||
*req.status =
|
||||
Status::Incomplete("Cannot read blob(s): no disk I/O allowed");
|
||||
continue;
|
||||
}
|
||||
|
||||
// No cache-fill allocator: a partial payload is never inserted.
|
||||
CacheAllocationPtr buf =
|
||||
AllocateBlock(req.range_length, /*allocator=*/nullptr);
|
||||
read_reqs.push_back(SimpleGen2RangeReadRequest{
|
||||
req.record_offset, static_cast<size_t>(req.payload_size),
|
||||
req.range_offset, req.range_length, req.expected_compression, buf.get(),
|
||||
req.status});
|
||||
pending.push_back(Pending{i, std::move(buf)});
|
||||
}
|
||||
|
||||
if (read_reqs.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
ReadSimpleGen2BlobRanges(read_options, file, read_reqs.size(),
|
||||
read_reqs.data());
|
||||
|
||||
for (size_t k = 0; k < pending.size(); ++k) {
|
||||
SimpleGen2BlobRangeReadRequest& req = reqs[pending[k].idx];
|
||||
if (!req.status->ok()) {
|
||||
continue;
|
||||
}
|
||||
std::unique_ptr<BlobContents> blob_contents(
|
||||
new BlobContents(std::move(pending[k].buf), req.range_length));
|
||||
|
||||
RecordTick(statistics_, BLOB_DB_BLOB_FILE_BYTES_READ, req.range_length);
|
||||
PERF_COUNTER_ADD(blob_read_count, 1);
|
||||
PERF_COUNTER_ADD(blob_read_byte, req.range_length);
|
||||
RecordLazyRead(statistics_, req.range_length);
|
||||
RecordLazyPartialRead(statistics_, req.range_length, req.payload_size);
|
||||
|
||||
PinOwnedBlob(&blob_contents, req.result);
|
||||
}
|
||||
}
|
||||
|
||||
void BlobSource::MultiGetBlob(const ReadOptions& read_options,
|
||||
autovector<BlobFileReadRequests>& blob_reqs,
|
||||
uint64_t* bytes_read) {
|
||||
@@ -406,7 +829,7 @@ void BlobSource::MultiGetBlob(const ReadOptions& read_options,
|
||||
uint64_t total_bytes_read = 0;
|
||||
uint64_t bytes_read_in_file = 0;
|
||||
|
||||
for (auto& [file_number, file_size, blob_reqs_in_file] : blob_reqs) {
|
||||
for (auto& [blob_file, file_size, blob_reqs_in_file] : blob_reqs) {
|
||||
// sort blob_reqs_in_file by file offset.
|
||||
std::sort(
|
||||
blob_reqs_in_file.begin(), blob_reqs_in_file.end(),
|
||||
@@ -414,7 +837,7 @@ void BlobSource::MultiGetBlob(const ReadOptions& read_options,
|
||||
return lhs.offset < rhs.offset;
|
||||
});
|
||||
|
||||
MultiGetBlobFromOneFile(read_options, file_number, file_size,
|
||||
MultiGetBlobFromOneFile(read_options, blob_file, file_size,
|
||||
blob_reqs_in_file, &bytes_read_in_file);
|
||||
|
||||
total_bytes_read += bytes_read_in_file;
|
||||
@@ -426,7 +849,7 @@ void BlobSource::MultiGetBlob(const ReadOptions& read_options,
|
||||
}
|
||||
|
||||
void BlobSource::MultiGetBlobFromOneFile(const ReadOptions& read_options,
|
||||
uint64_t file_number,
|
||||
const BlobFileOpenInfo& blob_file,
|
||||
uint64_t /*file_size*/,
|
||||
autovector<BlobReadRequest>& blob_reqs,
|
||||
uint64_t* bytes_read) {
|
||||
@@ -444,6 +867,7 @@ void BlobSource::MultiGetBlobFromOneFile(const ReadOptions& read_options,
|
||||
Mask cache_hit_mask = 0;
|
||||
|
||||
uint64_t total_bytes = 0;
|
||||
const uint64_t file_number = blob_file.file_number;
|
||||
const OffsetableCacheKey base_cache_key(db_id_, db_session_id_, file_number);
|
||||
|
||||
if (blob_cache_) {
|
||||
@@ -515,7 +939,7 @@ void BlobSource::MultiGetBlobFromOneFile(const ReadOptions& read_options,
|
||||
}
|
||||
|
||||
CacheHandleGuard<BlobFileReader> blob_file_reader;
|
||||
Status s = blob_file_cache_->GetBlobFileReader(read_options, file_number,
|
||||
Status s = blob_file_cache_->GetBlobFileReader(read_options, blob_file,
|
||||
&blob_file_reader);
|
||||
if (!s.ok()) {
|
||||
for (size_t i = 0; i < _blob_reqs.size(); ++i) {
|
||||
@@ -555,7 +979,7 @@ void BlobSource::MultiGetBlobFromOneFile(const ReadOptions& read_options,
|
||||
|
||||
std::unique_ptr<BlobFileReader> fresh_reader;
|
||||
s = blob_file_cache_->OpenBlobFileReaderUncached(
|
||||
read_options, file_number, &fresh_reader,
|
||||
read_options, blob_file, &fresh_reader,
|
||||
/*allow_footer_skip_retry=*/false);
|
||||
if (!s.ok()) {
|
||||
for (const auto& blob_req : _blob_reqs) {
|
||||
@@ -616,7 +1040,7 @@ void BlobSource::MultiGetBlobFromOneFile(const ReadOptions& read_options,
|
||||
if (install_fresh_reader) {
|
||||
CacheHandleGuard<BlobFileReader> ignored_reader;
|
||||
blob_file_cache_
|
||||
->RefreshBlobFileReader(file_number, &fresh_reader, &ignored_reader)
|
||||
->RefreshBlobFileReader(blob_file, &fresh_reader, &ignored_reader)
|
||||
.PermitUncheckedError();
|
||||
}
|
||||
}
|
||||
@@ -649,6 +1073,24 @@ void BlobSource::MultiGetBlobFromOneFile(const ReadOptions& read_options,
|
||||
}
|
||||
}
|
||||
|
||||
// Whole-column reads on the lazy resolve path count as lazy reads (mirrors
|
||||
// BlobSource::GetBlob, which records only on a disk read, not a cache hit).
|
||||
// Gated on the activity so regular MultiGet is unaffected; the misses read
|
||||
// above are exactly the disk reads for these blob columns.
|
||||
if (read_options.io_activity == Env::IOActivity::kLazyResolve) {
|
||||
for (auto& [req, blob_contents] : _blob_reqs) {
|
||||
assert(req);
|
||||
if (req->status->ok()) {
|
||||
const uint64_t adjustment =
|
||||
read_options.verify_checksums
|
||||
? BlobLogRecord::CalculateAdjustmentForRecordHeader(
|
||||
req->user_key->size())
|
||||
: 0;
|
||||
RecordLazyRead(statistics_, req->len + adjustment);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
total_bytes += _bytes_read;
|
||||
if (bytes_read) {
|
||||
*bytes_read = total_bytes;
|
||||
@@ -656,6 +1098,139 @@ void BlobSource::MultiGetBlobFromOneFile(const ReadOptions& read_options,
|
||||
}
|
||||
}
|
||||
|
||||
void BlobSource::MultiGetBlobRange(
|
||||
const ReadOptions& read_options,
|
||||
autovector<BlobFileRangeReadRequests>& blob_reqs, uint64_t* bytes_read) {
|
||||
assert(blob_reqs.size() > 0);
|
||||
|
||||
uint64_t total_bytes_read = 0;
|
||||
uint64_t bytes_read_in_file = 0;
|
||||
|
||||
for (auto& [blob_file, file_size, blob_reqs_in_file] : blob_reqs) {
|
||||
// Sort by effective read offset so the file system layer can coalesce
|
||||
// adjacent sub-range reads within one MultiRead.
|
||||
std::sort(blob_reqs_in_file.begin(), blob_reqs_in_file.end(),
|
||||
[](const BlobRangeReadRequest& lhs,
|
||||
const BlobRangeReadRequest& rhs) -> bool {
|
||||
return lhs.offset + lhs.range_offset <
|
||||
rhs.offset + rhs.range_offset;
|
||||
});
|
||||
|
||||
MultiGetBlobRangeFromOneFile(read_options, blob_file, file_size,
|
||||
blob_reqs_in_file, &bytes_read_in_file);
|
||||
|
||||
total_bytes_read += bytes_read_in_file;
|
||||
bytes_read_in_file = 0; // reset: some early-return paths do not write it
|
||||
}
|
||||
|
||||
if (bytes_read) {
|
||||
*bytes_read = total_bytes_read;
|
||||
}
|
||||
}
|
||||
|
||||
void BlobSource::MultiGetBlobRangeFromOneFile(
|
||||
const ReadOptions& read_options, const BlobFileOpenInfo& blob_file,
|
||||
uint64_t /*file_size*/, autovector<BlobRangeReadRequest>& blob_reqs,
|
||||
uint64_t* bytes_read) {
|
||||
const size_t num_blobs = blob_reqs.size();
|
||||
assert(num_blobs > 0);
|
||||
assert(num_blobs <= MultiGetContext::MAX_BATCH_SIZE);
|
||||
// Range reads are only issued while resolving a lazy result (partial reads
|
||||
// are lazy-only), so the lazy read stats below are recorded unconditionally.
|
||||
assert(read_options.io_activity == Env::IOActivity::kLazyResolve);
|
||||
|
||||
using Mask = uint64_t;
|
||||
Mask cache_hit_mask = 0;
|
||||
|
||||
uint64_t total_bytes = 0;
|
||||
const uint64_t file_number = blob_file.file_number;
|
||||
const OffsetableCacheKey base_cache_key(db_id_, db_session_id_, file_number);
|
||||
|
||||
// Probe the whole-value cache per request; on a hit, slice the requested
|
||||
// sub-range (zero-copy, no disk read). A partial read is never cache-filled.
|
||||
if (blob_cache_) {
|
||||
size_t cached_blob_count = 0;
|
||||
for (size_t i = 0; i < num_blobs; ++i) {
|
||||
BlobRangeReadRequest& req = blob_reqs[i];
|
||||
assert(req.status);
|
||||
|
||||
CacheHandleGuard<BlobContents> blob_handle;
|
||||
const CacheKey cache_key = base_cache_key.WithOffset(req.offset);
|
||||
const Status s = GetBlobFromCache(cache_key.AsSlice(), &blob_handle);
|
||||
if (s.ok()) {
|
||||
*req.status = s;
|
||||
PinCacheHitSubRange(&blob_handle, req.range_offset, req.range_length,
|
||||
req.result);
|
||||
++cached_blob_count;
|
||||
cache_hit_mask |= (Mask{1} << i); // hit -> no disk read
|
||||
}
|
||||
}
|
||||
|
||||
if (cached_blob_count == num_blobs) {
|
||||
if (bytes_read) {
|
||||
*bytes_read = 0;
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const bool no_io = read_options.read_tier == kBlockCacheTier;
|
||||
if (no_io) {
|
||||
for (size_t i = 0; i < num_blobs; ++i) {
|
||||
if (!(cache_hit_mask & (Mask{1} << i))) {
|
||||
assert(blob_reqs[i].status);
|
||||
*blob_reqs[i].status =
|
||||
Status::Incomplete("Cannot read blob(s): no disk I/O allowed");
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
autovector<std::pair<BlobRangeReadRequest*, std::unique_ptr<BlobContents>>>
|
||||
_blob_reqs;
|
||||
for (size_t i = 0; i < num_blobs; ++i) {
|
||||
if (!(cache_hit_mask & (Mask{1} << i))) {
|
||||
_blob_reqs.emplace_back(&blob_reqs[i], std::unique_ptr<BlobContents>());
|
||||
}
|
||||
}
|
||||
|
||||
// Lazy range reads run against a pinned SuperVersion (max_open_files == -1),
|
||||
// and blob file numbers are never reused, so the stale cached-reader race
|
||||
// that MultiGetBlobFromOneFile guards against cannot occur here; a Corruption
|
||||
// is simply surfaced per request. Hence no reader-refresh retry and no
|
||||
// cache-fill (a partial value cannot represent the whole-record cache entry).
|
||||
CacheHandleGuard<BlobFileReader> blob_file_reader;
|
||||
Status s = blob_file_cache_->GetBlobFileReader(read_options, blob_file,
|
||||
&blob_file_reader);
|
||||
if (!s.ok()) {
|
||||
for (auto& blob_req : _blob_reqs) {
|
||||
assert(blob_req.first);
|
||||
assert(blob_req.first->status);
|
||||
*blob_req.first->status = s;
|
||||
}
|
||||
return;
|
||||
}
|
||||
assert(blob_file_reader.GetValue());
|
||||
|
||||
uint64_t _bytes_read = 0;
|
||||
blob_file_reader.GetValue()->MultiGetBlobRange(read_options, _blob_reqs,
|
||||
&_bytes_read);
|
||||
|
||||
for (auto& [req, blob_contents] : _blob_reqs) {
|
||||
assert(req);
|
||||
if (req->status->ok()) {
|
||||
PinOwnedBlob(&blob_contents, req->result);
|
||||
RecordLazyRead(statistics_, req->range_length);
|
||||
RecordLazyPartialRead(statistics_, req->range_length, req->value_size);
|
||||
}
|
||||
}
|
||||
|
||||
total_bytes += _bytes_read;
|
||||
if (bytes_read) {
|
||||
*bytes_read = total_bytes;
|
||||
}
|
||||
}
|
||||
|
||||
bool BlobSource::TEST_BlobInCache(uint64_t file_number, uint64_t file_size,
|
||||
uint64_t offset, size_t* charge) const {
|
||||
const CacheKey cache_key = GetCacheKey(file_number, file_size, offset);
|
||||
|
||||
+128
-5
@@ -28,6 +28,30 @@ class Slice;
|
||||
class RandomAccessFileReader;
|
||||
enum ChecksumType : char;
|
||||
|
||||
// One whole-record request for BlobSource::MultiGetSimpleGen2Blob (the batched
|
||||
// counterpart of GetSimpleGen2Blob). The per-file context (base cache key,
|
||||
// file, checksum context) is passed once to the batch call; these are the
|
||||
// per-record inputs and outputs.
|
||||
struct SimpleGen2BlobReadRequest {
|
||||
uint64_t record_offset = 0;
|
||||
uint64_t payload_size = 0;
|
||||
CompressionType expected_compression = kNoCompression;
|
||||
PinnableSlice* result = nullptr;
|
||||
Status* status = nullptr;
|
||||
};
|
||||
|
||||
// One sub-range request for BlobSource::MultiGetSimpleGen2BlobRange (the
|
||||
// batched counterpart of GetSimpleGen2BlobRange).
|
||||
struct SimpleGen2BlobRangeReadRequest {
|
||||
uint64_t record_offset = 0;
|
||||
uint64_t payload_size = 0;
|
||||
uint64_t range_offset = 0;
|
||||
size_t range_length = 0;
|
||||
CompressionType expected_compression = kNoCompression;
|
||||
PinnableSlice* result = nullptr;
|
||||
Status* status = nullptr;
|
||||
};
|
||||
|
||||
// BlobSource is a class that provides universal access to blobs, regardless of
|
||||
// whether they are in the blob cache, secondary cache, or (remote) storage.
|
||||
// Depending on user settings, it always fetch blobs from multi-tier cache and
|
||||
@@ -56,11 +80,38 @@ class BlobSource {
|
||||
// sets "*bytes_read" to the size of on-disk (possibly compressed) blob
|
||||
// record.
|
||||
Status GetBlob(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,
|
||||
const BlobFileOpenInfo& blob_file, uint64_t offset,
|
||||
uint64_t file_size, uint64_t value_size,
|
||||
CompressionType compression_type,
|
||||
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,
|
||||
const BlobFileOpenInfo& blob_file, 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
|
||||
@@ -96,6 +147,58 @@ 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);
|
||||
|
||||
// Batched counterpart of GetSimpleGen2Blob: resolves `num_records` whole
|
||||
// embedded (SimpleGen2Blob) records from one file, coalescing all cache-miss
|
||||
// reads into a single MultiRead. The per-file context (base cache key, file,
|
||||
// checksum type, base context checksum) is shared by all records; per-record
|
||||
// inputs/outputs are in `reqs`. Each record independently probes the blob
|
||||
// cache and, on a miss, is read + verified from the file; whole records are
|
||||
// cache-filled (when configured and fill_cache) exactly as GetSimpleGen2Blob.
|
||||
// Per-record outcome is written to *reqs[i].status.
|
||||
void MultiGetSimpleGen2Blob(const ReadOptions& read_options,
|
||||
const OffsetableCacheKey& base_cache_key,
|
||||
RandomAccessFileReader* file,
|
||||
ChecksumType checksum_type,
|
||||
uint32_t base_context_checksum,
|
||||
size_t num_records,
|
||||
SimpleGen2BlobReadRequest* reqs);
|
||||
|
||||
// Batched counterpart of GetSimpleGen2BlobRange: resolves `num_records`
|
||||
// uncompressed embedded sub-ranges from one file, coalescing cache-miss reads
|
||||
// into a single MultiRead. Like GetSimpleGen2BlobRange, each record probes
|
||||
// the whole-payload cache (slicing on a hit) and a partial read is never
|
||||
// inserted into the cache. Per-record outcome is in *reqs[i].status.
|
||||
void MultiGetSimpleGen2BlobRange(const ReadOptions& read_options,
|
||||
const OffsetableCacheKey& base_cache_key,
|
||||
RandomAccessFileReader* file,
|
||||
size_t num_records,
|
||||
SimpleGen2BlobRangeReadRequest* reqs);
|
||||
|
||||
// Read multiple blobs from the underlying cache or blob file(s).
|
||||
//
|
||||
// If successful, returns ok and sets "result" in the elements of "blob_reqs"
|
||||
@@ -131,14 +234,34 @@ class BlobSource {
|
||||
// "*bytes_read" to the total size of on-disk (possibly compressed) blob
|
||||
// records.
|
||||
void MultiGetBlobFromOneFile(const ReadOptions& read_options,
|
||||
uint64_t file_number, uint64_t file_size,
|
||||
const BlobFileOpenInfo& blob_file,
|
||||
uint64_t file_size,
|
||||
autovector<BlobReadRequest>& blob_reqs,
|
||||
uint64_t* bytes_read);
|
||||
|
||||
// Byte-range (partial) multi-read counterpart of MultiGetBlob: for each
|
||||
// request reads only its sub-range of an *uncompressed* blob value, from the
|
||||
// blob cache (whole-value hit, sliced) or coalesced disk reads (one MultiRead
|
||||
// per file). Like GetBlobRange, a partial read never fills the blob cache.
|
||||
// Groups requests by file and dispatches each file via
|
||||
// MultiGetBlobRangeFromOneFile. Per-request outcome is in
|
||||
// *blob_reqs[..].status.
|
||||
void MultiGetBlobRange(const ReadOptions& read_options,
|
||||
autovector<BlobFileRangeReadRequests>& blob_reqs,
|
||||
uint64_t* bytes_read);
|
||||
|
||||
// Byte-range (partial) multi-read counterpart of MultiGetBlobFromOneFile for
|
||||
// a single blob file. See MultiGetBlobRange.
|
||||
void MultiGetBlobRangeFromOneFile(const ReadOptions& read_options,
|
||||
const BlobFileOpenInfo& blob_file,
|
||||
uint64_t file_size,
|
||||
autovector<BlobRangeReadRequest>& blob_reqs,
|
||||
uint64_t* bytes_read);
|
||||
|
||||
inline Status GetBlobFileReader(
|
||||
const ReadOptions& read_options, uint64_t blob_file_number,
|
||||
const ReadOptions& read_options, const BlobFileOpenInfo& blob_file,
|
||||
CacheHandleGuard<BlobFileReader>* blob_file_reader) {
|
||||
return blob_file_cache_->GetBlobFileReader(read_options, blob_file_number,
|
||||
return blob_file_cache_->GetBlobFileReader(read_options, blob_file,
|
||||
blob_file_reader);
|
||||
}
|
||||
|
||||
|
||||
+93
-75
@@ -104,6 +104,10 @@ void WriteBlobFile(const ImmutableOptions& immutable_options,
|
||||
&checksum_method, &checksum_value));
|
||||
}
|
||||
|
||||
BlobFileOpenInfo OpenInfoWithoutChecksum(uint64_t file_number) {
|
||||
return BlobFileOpenInfo{file_number, Slice(), Slice()};
|
||||
}
|
||||
|
||||
} // anonymous namespace
|
||||
|
||||
class BlobSourceTest : public DBTestBase {
|
||||
@@ -212,10 +216,10 @@ TEST_F(BlobSourceTest, GetBlobsFromCache) {
|
||||
ASSERT_FALSE(blob_source.TEST_BlobInCache(blob_file_number, file_size,
|
||||
blob_offsets[i]));
|
||||
|
||||
ASSERT_OK(blob_source.GetBlob(read_options, keys[i], blob_file_number,
|
||||
blob_offsets[i], file_size, blob_sizes[i],
|
||||
kNoCompression, prefetch_buffer, &values[i],
|
||||
&bytes_read));
|
||||
ASSERT_OK(blob_source.GetBlob(
|
||||
read_options, keys[i], OpenInfoWithoutChecksum(blob_file_number),
|
||||
blob_offsets[i], file_size, blob_sizes[i], kNoCompression,
|
||||
prefetch_buffer, &values[i], &bytes_read));
|
||||
ASSERT_EQ(values[i], blobs[i]);
|
||||
ASSERT_TRUE(values[i].IsPinned());
|
||||
ASSERT_EQ(bytes_read,
|
||||
@@ -251,10 +255,10 @@ TEST_F(BlobSourceTest, GetBlobsFromCache) {
|
||||
ASSERT_FALSE(blob_source.TEST_BlobInCache(blob_file_number, file_size,
|
||||
blob_offsets[i]));
|
||||
|
||||
ASSERT_OK(blob_source.GetBlob(read_options, keys[i], blob_file_number,
|
||||
blob_offsets[i], file_size, blob_sizes[i],
|
||||
kNoCompression, prefetch_buffer, &values[i],
|
||||
&bytes_read));
|
||||
ASSERT_OK(blob_source.GetBlob(
|
||||
read_options, keys[i], OpenInfoWithoutChecksum(blob_file_number),
|
||||
blob_offsets[i], file_size, blob_sizes[i], kNoCompression,
|
||||
prefetch_buffer, &values[i], &bytes_read));
|
||||
ASSERT_EQ(values[i], blobs[i]);
|
||||
ASSERT_TRUE(values[i].IsPinned());
|
||||
ASSERT_EQ(bytes_read,
|
||||
@@ -299,10 +303,10 @@ TEST_F(BlobSourceTest, GetBlobsFromCache) {
|
||||
ASSERT_TRUE(blob_source.TEST_BlobInCache(blob_file_number, file_size,
|
||||
blob_offsets[i]));
|
||||
|
||||
ASSERT_OK(blob_source.GetBlob(read_options, keys[i], blob_file_number,
|
||||
blob_offsets[i], file_size, blob_sizes[i],
|
||||
kNoCompression, prefetch_buffer, &values[i],
|
||||
&bytes_read));
|
||||
ASSERT_OK(blob_source.GetBlob(
|
||||
read_options, keys[i], OpenInfoWithoutChecksum(blob_file_number),
|
||||
blob_offsets[i], file_size, blob_sizes[i], kNoCompression,
|
||||
prefetch_buffer, &values[i], &bytes_read));
|
||||
ASSERT_EQ(values[i], blobs[i]);
|
||||
ASSERT_TRUE(values[i].IsPinned());
|
||||
ASSERT_EQ(bytes_read,
|
||||
@@ -339,10 +343,10 @@ TEST_F(BlobSourceTest, GetBlobsFromCache) {
|
||||
ASSERT_TRUE(blob_source.TEST_BlobInCache(blob_file_number, file_size,
|
||||
blob_offsets[i]));
|
||||
|
||||
ASSERT_OK(blob_source.GetBlob(read_options, keys[i], blob_file_number,
|
||||
blob_offsets[i], file_size, blob_sizes[i],
|
||||
kNoCompression, prefetch_buffer, &values[i],
|
||||
&bytes_read));
|
||||
ASSERT_OK(blob_source.GetBlob(
|
||||
read_options, keys[i], OpenInfoWithoutChecksum(blob_file_number),
|
||||
blob_offsets[i], file_size, blob_sizes[i], kNoCompression,
|
||||
prefetch_buffer, &values[i], &bytes_read));
|
||||
ASSERT_EQ(values[i], blobs[i]);
|
||||
ASSERT_TRUE(values[i].IsPinned());
|
||||
ASSERT_EQ(bytes_read,
|
||||
@@ -385,7 +389,8 @@ TEST_F(BlobSourceTest, GetBlobsFromCache) {
|
||||
blob_offsets[i]));
|
||||
|
||||
ASSERT_TRUE(blob_source
|
||||
.GetBlob(read_options, keys[i], blob_file_number,
|
||||
.GetBlob(read_options, keys[i],
|
||||
OpenInfoWithoutChecksum(blob_file_number),
|
||||
blob_offsets[i], file_size, blob_sizes[i],
|
||||
kNoCompression, prefetch_buffer, &values[i],
|
||||
&bytes_read)
|
||||
@@ -427,7 +432,8 @@ TEST_F(BlobSourceTest, GetBlobsFromCache) {
|
||||
blob_offsets[i]));
|
||||
|
||||
ASSERT_TRUE(blob_source
|
||||
.GetBlob(read_options, keys[i], file_number,
|
||||
.GetBlob(read_options, keys[i],
|
||||
OpenInfoWithoutChecksum(file_number),
|
||||
blob_offsets[i], file_size, blob_sizes[i],
|
||||
kNoCompression, prefetch_buffer, &values[i],
|
||||
&bytes_read)
|
||||
@@ -522,8 +528,8 @@ TEST_F(BlobSourceTest, GetCompressedBlobs) {
|
||||
compression, blob_offsets, blob_sizes);
|
||||
|
||||
CacheHandleGuard<BlobFileReader> blob_file_reader;
|
||||
ASSERT_OK(blob_source.GetBlobFileReader(read_options, file_number,
|
||||
&blob_file_reader));
|
||||
ASSERT_OK(blob_source.GetBlobFileReader(
|
||||
read_options, OpenInfoWithoutChecksum(file_number), &blob_file_reader));
|
||||
ASSERT_NE(blob_file_reader.GetValue(), nullptr);
|
||||
|
||||
const uint64_t file_size = blob_file_reader.GetValue()->GetFileSize();
|
||||
@@ -541,10 +547,10 @@ TEST_F(BlobSourceTest, GetCompressedBlobs) {
|
||||
for (size_t i = 0; i < num_blobs; ++i) {
|
||||
ASSERT_FALSE(blob_source.TEST_BlobInCache(file_number, file_size,
|
||||
blob_offsets[i]));
|
||||
ASSERT_OK(blob_source.GetBlob(read_options, keys[i], file_number,
|
||||
blob_offsets[i], file_size, blob_sizes[i],
|
||||
compression, nullptr /*prefetch_buffer*/,
|
||||
&values[i], &bytes_read));
|
||||
ASSERT_OK(blob_source.GetBlob(
|
||||
read_options, keys[i], OpenInfoWithoutChecksum(file_number),
|
||||
blob_offsets[i], file_size, blob_sizes[i], compression,
|
||||
nullptr /*prefetch_buffer*/, &values[i], &bytes_read));
|
||||
ASSERT_EQ(values[i], blobs[i] /*uncompressed blob*/);
|
||||
ASSERT_NE(values[i].size(), blob_sizes[i] /*compressed size*/);
|
||||
ASSERT_EQ(bytes_read,
|
||||
@@ -564,10 +570,10 @@ TEST_F(BlobSourceTest, GetCompressedBlobs) {
|
||||
blob_offsets[i]));
|
||||
|
||||
// Compressed blob size is passed in GetBlob
|
||||
ASSERT_OK(blob_source.GetBlob(read_options, keys[i], file_number,
|
||||
blob_offsets[i], file_size, blob_sizes[i],
|
||||
compression, nullptr /*prefetch_buffer*/,
|
||||
&values[i], &bytes_read));
|
||||
ASSERT_OK(blob_source.GetBlob(
|
||||
read_options, keys[i], OpenInfoWithoutChecksum(file_number),
|
||||
blob_offsets[i], file_size, blob_sizes[i], compression,
|
||||
nullptr /*prefetch_buffer*/, &values[i], &bytes_read));
|
||||
ASSERT_EQ(values[i], blobs[i] /*uncompressed blob*/);
|
||||
ASSERT_NE(values[i].size(), blob_sizes[i] /*compressed size*/);
|
||||
ASSERT_EQ(bytes_read,
|
||||
@@ -674,7 +680,8 @@ TEST_F(BlobSourceTest, MultiGetBlobsFromMultiFiles) {
|
||||
keys[j], blob_offsets[j], blob_sizes[j], kNoCompression,
|
||||
&value_buf[i * num_blobs + j], &statuses_buf[i * num_blobs + j]);
|
||||
}
|
||||
blob_reqs.emplace_back(file_number, file_size, blob_reqs_in_file[i]);
|
||||
blob_reqs.emplace_back(OpenInfoWithoutChecksum(file_number), file_size,
|
||||
blob_reqs_in_file[i]);
|
||||
}
|
||||
|
||||
get_perf_context()->Reset();
|
||||
@@ -731,7 +738,8 @@ TEST_F(BlobSourceTest, MultiGetBlobsFromMultiFiles) {
|
||||
}
|
||||
|
||||
// Add a fake multi-get blob request.
|
||||
blob_reqs.emplace_back(fake_file_number, file_size, fake_blob_reqs_in_file);
|
||||
blob_reqs.emplace_back(OpenInfoWithoutChecksum(fake_file_number), file_size,
|
||||
fake_blob_reqs_in_file);
|
||||
|
||||
blob_source.MultiGetBlob(read_options, blob_reqs, &bytes_read);
|
||||
|
||||
@@ -865,8 +873,9 @@ TEST_F(BlobSourceTest, MultiGetBlobsFromCache) {
|
||||
statistics->Reset().PermitUncheckedError();
|
||||
|
||||
// Get half of blobs
|
||||
blob_source.MultiGetBlobFromOneFile(read_options, blob_file_number,
|
||||
file_size, blob_reqs, &bytes_read);
|
||||
blob_source.MultiGetBlobFromOneFile(
|
||||
read_options, OpenInfoWithoutChecksum(blob_file_number), file_size,
|
||||
blob_reqs, &bytes_read);
|
||||
|
||||
uint64_t fs_read_bytes = 0;
|
||||
uint64_t ca_read_bytes = 0;
|
||||
@@ -911,10 +920,10 @@ TEST_F(BlobSourceTest, MultiGetBlobsFromCache) {
|
||||
ASSERT_FALSE(blob_source.TEST_BlobInCache(blob_file_number, file_size,
|
||||
blob_offsets[i]));
|
||||
|
||||
ASSERT_OK(blob_source.GetBlob(read_options, keys[i], blob_file_number,
|
||||
blob_offsets[i], file_size, blob_sizes[i],
|
||||
kNoCompression, prefetch_buffer,
|
||||
&value_buf[i], &bytes_read));
|
||||
ASSERT_OK(blob_source.GetBlob(
|
||||
read_options, keys[i], OpenInfoWithoutChecksum(blob_file_number),
|
||||
blob_offsets[i], file_size, blob_sizes[i], kNoCompression,
|
||||
prefetch_buffer, &value_buf[i], &bytes_read));
|
||||
ASSERT_EQ(value_buf[i], blobs[i]);
|
||||
ASSERT_TRUE(value_buf[i].IsPinned());
|
||||
ASSERT_EQ(bytes_read,
|
||||
@@ -935,8 +944,9 @@ TEST_F(BlobSourceTest, MultiGetBlobsFromCache) {
|
||||
kNoCompression, &value_buf[i], &statuses_buf[i]);
|
||||
}
|
||||
|
||||
blob_source.MultiGetBlobFromOneFile(read_options, blob_file_number,
|
||||
file_size, blob_reqs, &bytes_read);
|
||||
blob_source.MultiGetBlobFromOneFile(
|
||||
read_options, OpenInfoWithoutChecksum(blob_file_number), file_size,
|
||||
blob_reqs, &bytes_read);
|
||||
|
||||
uint64_t blob_bytes = 0;
|
||||
for (size_t i = 0; i < num_blobs; ++i) {
|
||||
@@ -985,8 +995,9 @@ TEST_F(BlobSourceTest, MultiGetBlobsFromCache) {
|
||||
get_perf_context()->Reset();
|
||||
statistics->Reset().PermitUncheckedError();
|
||||
|
||||
blob_source.MultiGetBlobFromOneFile(read_options, blob_file_number,
|
||||
file_size, blob_reqs, &bytes_read);
|
||||
blob_source.MultiGetBlobFromOneFile(
|
||||
read_options, OpenInfoWithoutChecksum(blob_file_number), file_size,
|
||||
blob_reqs, &bytes_read);
|
||||
|
||||
for (size_t i = 0; i < num_blobs; ++i) {
|
||||
ASSERT_TRUE(statuses_buf[i].IsIncomplete());
|
||||
@@ -1029,8 +1040,9 @@ TEST_F(BlobSourceTest, MultiGetBlobsFromCache) {
|
||||
get_perf_context()->Reset();
|
||||
statistics->Reset().PermitUncheckedError();
|
||||
|
||||
blob_source.MultiGetBlobFromOneFile(read_options, non_existing_file_number,
|
||||
file_size, blob_reqs, &bytes_read);
|
||||
blob_source.MultiGetBlobFromOneFile(
|
||||
read_options, OpenInfoWithoutChecksum(non_existing_file_number),
|
||||
file_size, blob_reqs, &bytes_read);
|
||||
|
||||
for (size_t i = 0; i < num_blobs; ++i) {
|
||||
ASSERT_TRUE(statuses_buf[i].IsIOError());
|
||||
@@ -1104,8 +1116,9 @@ TEST_F(BlobSourceTest, GetBlobPreservesCorruptionDetailsWhenRefreshOpenFails) {
|
||||
PinnableSlice value;
|
||||
uint64_t bytes_read = 0;
|
||||
ASSERT_OK(blob_source.GetBlob(
|
||||
read_options, keys[0], blob_file_number, blob_offsets[0], file_size,
|
||||
blob_sizes[0], kNoCompression, prefetch_buffer, &value, &bytes_read));
|
||||
read_options, keys[0], OpenInfoWithoutChecksum(blob_file_number),
|
||||
blob_offsets[0], file_size, blob_sizes[0], kNoCompression,
|
||||
prefetch_buffer, &value, &bytes_read));
|
||||
ASSERT_EQ(value, blobs[0]);
|
||||
|
||||
const std::string blob_file_path =
|
||||
@@ -1114,10 +1127,10 @@ TEST_F(BlobSourceTest, GetBlobPreservesCorruptionDetailsWhenRefreshOpenFails) {
|
||||
|
||||
PinnableSlice invalid_value;
|
||||
bytes_read = 0;
|
||||
Status s =
|
||||
blob_source.GetBlob(read_options, keys[0], blob_file_number, file_size,
|
||||
file_size, blob_sizes[0], kNoCompression,
|
||||
prefetch_buffer, &invalid_value, &bytes_read);
|
||||
Status s = blob_source.GetBlob(
|
||||
read_options, keys[0], OpenInfoWithoutChecksum(blob_file_number),
|
||||
file_size, file_size, blob_sizes[0], kNoCompression, prefetch_buffer,
|
||||
&invalid_value, &bytes_read);
|
||||
ASSERT_TRUE(s.IsCorruption());
|
||||
ASSERT_EQ(bytes_read, 0);
|
||||
|
||||
@@ -1178,8 +1191,9 @@ TEST_F(BlobSourceTest,
|
||||
PinnableSlice value;
|
||||
uint64_t bytes_read = 0;
|
||||
ASSERT_OK(blob_source.GetBlob(
|
||||
read_options, keys[0], blob_file_number, blob_offsets[0], file_size,
|
||||
blob_sizes[0], kNoCompression, prefetch_buffer, &value, &bytes_read));
|
||||
read_options, keys[0], OpenInfoWithoutChecksum(blob_file_number),
|
||||
blob_offsets[0], file_size, blob_sizes[0], kNoCompression,
|
||||
prefetch_buffer, &value, &bytes_read));
|
||||
ASSERT_EQ(value, blobs[0]);
|
||||
|
||||
const std::string blob_file_path =
|
||||
@@ -1193,8 +1207,9 @@ TEST_F(BlobSourceTest,
|
||||
&values[0], &statuses[0]);
|
||||
|
||||
bytes_read = 0;
|
||||
blob_source.MultiGetBlobFromOneFile(read_options, blob_file_number, file_size,
|
||||
blob_reqs, &bytes_read);
|
||||
blob_source.MultiGetBlobFromOneFile(read_options,
|
||||
OpenInfoWithoutChecksum(blob_file_number),
|
||||
file_size, blob_reqs, &bytes_read);
|
||||
ASSERT_TRUE(statuses[0].IsCorruption());
|
||||
ASSERT_EQ(bytes_read, 0);
|
||||
|
||||
@@ -1303,8 +1318,8 @@ TEST_F(BlobSecondaryCacheTest, GetBlobsFromSecondaryCache) {
|
||||
|
||||
CacheHandleGuard<BlobFileReader> file_reader;
|
||||
ReadOptions read_options;
|
||||
ASSERT_OK(
|
||||
blob_source.GetBlobFileReader(read_options, file_number, &file_reader));
|
||||
ASSERT_OK(blob_source.GetBlobFileReader(
|
||||
read_options, OpenInfoWithoutChecksum(file_number), &file_reader));
|
||||
ASSERT_NE(file_reader.GetValue(), nullptr);
|
||||
const uint64_t file_size = file_reader.GetValue()->GetFileSize();
|
||||
ASSERT_EQ(file_reader.GetValue()->GetCompressionType(), kNoCompression);
|
||||
@@ -1322,7 +1337,8 @@ TEST_F(BlobSecondaryCacheTest, GetBlobsFromSecondaryCache) {
|
||||
get_perf_context()->Reset();
|
||||
|
||||
// key0 should be filled to the primary cache from the blob file.
|
||||
ASSERT_OK(blob_source.GetBlob(read_options, keys[0], file_number,
|
||||
ASSERT_OK(blob_source.GetBlob(read_options, keys[0],
|
||||
OpenInfoWithoutChecksum(file_number),
|
||||
blob_offsets[0], file_size, blob_sizes[0],
|
||||
kNoCompression, nullptr /* prefetch_buffer */,
|
||||
values.data(), nullptr /* bytes_read */));
|
||||
@@ -1331,17 +1347,18 @@ TEST_F(BlobSecondaryCacheTest, GetBlobsFromSecondaryCache) {
|
||||
|
||||
// key0 should be evicted and key0's dummy item is inserted into secondary
|
||||
// cache. key1 should be filled to the primary cache from the blob file.
|
||||
ASSERT_OK(blob_source.GetBlob(read_options, keys[1], file_number,
|
||||
blob_offsets[1], file_size, blob_sizes[1],
|
||||
kNoCompression, nullptr /* prefetch_buffer */,
|
||||
&values[1], nullptr /* bytes_read */));
|
||||
ASSERT_OK(blob_source.GetBlob(
|
||||
read_options, keys[1], OpenInfoWithoutChecksum(file_number),
|
||||
blob_offsets[1], file_size, blob_sizes[1], kNoCompression,
|
||||
nullptr /* prefetch_buffer */, &values[1], nullptr /* bytes_read */));
|
||||
|
||||
// Release cache handle
|
||||
values[1].Reset();
|
||||
|
||||
// key0 should be filled to the primary cache from the blob file. key1
|
||||
// should be evicted and key1's dummy item is inserted into secondary cache.
|
||||
ASSERT_OK(blob_source.GetBlob(read_options, keys[0], file_number,
|
||||
ASSERT_OK(blob_source.GetBlob(read_options, keys[0],
|
||||
OpenInfoWithoutChecksum(file_number),
|
||||
blob_offsets[0], file_size, blob_sizes[0],
|
||||
kNoCompression, nullptr /* prefetch_buffer */,
|
||||
values.data(), nullptr /* bytes_read */));
|
||||
@@ -1354,10 +1371,10 @@ TEST_F(BlobSecondaryCacheTest, GetBlobsFromSecondaryCache) {
|
||||
|
||||
// key0 should be evicted and is inserted into secondary cache.
|
||||
// key1 should be filled to the primary cache from the blob file.
|
||||
ASSERT_OK(blob_source.GetBlob(read_options, keys[1], file_number,
|
||||
blob_offsets[1], file_size, blob_sizes[1],
|
||||
kNoCompression, nullptr /* prefetch_buffer */,
|
||||
&values[1], nullptr /* bytes_read */));
|
||||
ASSERT_OK(blob_source.GetBlob(
|
||||
read_options, keys[1], OpenInfoWithoutChecksum(file_number),
|
||||
blob_offsets[1], file_size, blob_sizes[1], kNoCompression,
|
||||
nullptr /* prefetch_buffer */, &values[1], nullptr /* bytes_read */));
|
||||
ASSERT_EQ(values[1], blobs[1]);
|
||||
ASSERT_TRUE(
|
||||
blob_source.TEST_BlobInCache(file_number, file_size, blob_offsets[1]));
|
||||
@@ -1422,9 +1439,10 @@ TEST_F(BlobSecondaryCacheTest, GetBlobsFromSecondaryCache) {
|
||||
// fetch key0 from the blob file to the primary cache.
|
||||
// key1 is evicted and inserted into the secondary cache.
|
||||
ASSERT_OK(blob_source.GetBlob(
|
||||
read_options, keys[0], file_number, blob_offsets[0], file_size,
|
||||
blob_sizes[0], kNoCompression, nullptr /* prefetch_buffer */,
|
||||
values.data(), nullptr /* bytes_read */));
|
||||
read_options, keys[0], OpenInfoWithoutChecksum(file_number),
|
||||
blob_offsets[0], file_size, blob_sizes[0], kNoCompression,
|
||||
nullptr /* prefetch_buffer */, values.data(),
|
||||
nullptr /* bytes_read */));
|
||||
ASSERT_EQ(values[0], blobs[0]);
|
||||
|
||||
// Release cache handle
|
||||
@@ -1606,8 +1624,8 @@ TEST_F(BlobSourceCacheReservationTest, SimpleCacheReservation) {
|
||||
|
||||
for (size_t i = 0; i < kNumBlobs; ++i) {
|
||||
ASSERT_OK(blob_source.GetBlob(
|
||||
read_options, keys_[i], kBlobFileNumber, blob_offsets[i],
|
||||
blob_file_size_, blob_sizes[i], kNoCompression,
|
||||
read_options, keys_[i], OpenInfoWithoutChecksum(kBlobFileNumber),
|
||||
blob_offsets[i], blob_file_size_, blob_sizes[i], kNoCompression,
|
||||
nullptr /* prefetch_buffer */, &values[i], nullptr /* bytes_read */));
|
||||
ASSERT_EQ(cache_res_mgr->GetTotalReservedCacheSize(), 0);
|
||||
ASSERT_EQ(cache_res_mgr->GetTotalMemoryUsed(), 0);
|
||||
@@ -1625,8 +1643,8 @@ TEST_F(BlobSourceCacheReservationTest, SimpleCacheReservation) {
|
||||
uint64_t blob_bytes = 0;
|
||||
for (size_t i = 0; i < kNumBlobs; ++i) {
|
||||
ASSERT_OK(blob_source.GetBlob(
|
||||
read_options, keys_[i], kBlobFileNumber, blob_offsets[i],
|
||||
blob_file_size_, blob_sizes[i], kNoCompression,
|
||||
read_options, keys_[i], OpenInfoWithoutChecksum(kBlobFileNumber),
|
||||
blob_offsets[i], blob_file_size_, blob_sizes[i], kNoCompression,
|
||||
nullptr /* prefetch_buffer */, &values[i], nullptr /* bytes_read */));
|
||||
|
||||
size_t charge = 0;
|
||||
@@ -1728,8 +1746,8 @@ TEST_F(BlobSourceCacheReservationTest, IncreaseCacheReservation) {
|
||||
|
||||
for (size_t i = 0; i < kNumBlobs; ++i) {
|
||||
ASSERT_OK(blob_source.GetBlob(
|
||||
read_options, keys_[i], kBlobFileNumber, blob_offsets[i],
|
||||
blob_file_size_, blob_sizes[i], kNoCompression,
|
||||
read_options, keys_[i], OpenInfoWithoutChecksum(kBlobFileNumber),
|
||||
blob_offsets[i], blob_file_size_, blob_sizes[i], kNoCompression,
|
||||
nullptr /* prefetch_buffer */, &values[i], nullptr /* bytes_read */));
|
||||
ASSERT_EQ(cache_res_mgr->GetTotalReservedCacheSize(), 0);
|
||||
ASSERT_EQ(cache_res_mgr->GetTotalMemoryUsed(), 0);
|
||||
@@ -1744,8 +1762,8 @@ TEST_F(BlobSourceCacheReservationTest, IncreaseCacheReservation) {
|
||||
uint64_t blob_bytes = 0;
|
||||
for (size_t i = 0; i < kNumBlobs; ++i) {
|
||||
ASSERT_OK(blob_source.GetBlob(
|
||||
read_options, keys_[i], kBlobFileNumber, blob_offsets[i],
|
||||
blob_file_size_, blob_sizes[i], kNoCompression,
|
||||
read_options, keys_[i], OpenInfoWithoutChecksum(kBlobFileNumber),
|
||||
blob_offsets[i], blob_file_size_, blob_sizes[i], kNoCompression,
|
||||
nullptr /* prefetch_buffer */, &values[i], nullptr /* bytes_read */));
|
||||
|
||||
// Release cache handle
|
||||
|
||||
@@ -5,6 +5,9 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
@@ -17,15 +20,19 @@
|
||||
#include "db/column_family.h"
|
||||
#include "db/db_test_util.h"
|
||||
#include "db/db_with_timestamp_test_util.h"
|
||||
#include "env/composite_env_wrapper.h"
|
||||
#include "file/filename.h"
|
||||
#include "file/random_access_file_reader.h"
|
||||
#include "port/stack_trace.h"
|
||||
#include "rocksdb/convenience.h"
|
||||
#include "rocksdb/file_system.h"
|
||||
#include "rocksdb/trace_reader_writer.h"
|
||||
#include "rocksdb/trace_record.h"
|
||||
#include "rocksdb/utilities/replayer.h"
|
||||
#include "test_util/sync_point.h"
|
||||
#include "util/compression.h"
|
||||
#include "util/defer.h"
|
||||
#include "util/file_checksum_helper.h"
|
||||
#include "utilities/fault_injection_env.h"
|
||||
|
||||
namespace ROCKSDB_NAMESPACE {
|
||||
@@ -36,6 +43,49 @@ class DBBlobBasicTest : public DBTestBase {
|
||||
: DBTestBase("db_blob_basic_test", /* env_do_fsync */ false) {}
|
||||
};
|
||||
|
||||
class BlobFileChecksumCapturingFS : public FileSystemWrapper {
|
||||
public:
|
||||
explicit BlobFileChecksumCapturingFS(const std::shared_ptr<FileSystem>& base)
|
||||
: FileSystemWrapper(base) {}
|
||||
|
||||
static const char* kClassName() { return "BlobFileChecksumCapturingFS"; }
|
||||
const char* Name() const override { return kClassName(); }
|
||||
|
||||
IOStatus NewRandomAccessFile(const std::string& fname,
|
||||
const FileOptions& opts,
|
||||
std::unique_ptr<FSRandomAccessFile>* result,
|
||||
IODebugContext* dbg) override {
|
||||
if (fname.find(".blob") != std::string::npos) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
file_checksum_ = opts.file_checksum;
|
||||
file_checksum_func_name_ = opts.file_checksum_func_name;
|
||||
++capture_count_;
|
||||
}
|
||||
return target()->NewRandomAccessFile(fname, opts, result, dbg);
|
||||
}
|
||||
|
||||
std::string GetFileChecksum() {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return file_checksum_;
|
||||
}
|
||||
|
||||
std::string GetFileChecksumFuncName() {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return file_checksum_func_name_;
|
||||
}
|
||||
|
||||
int GetCaptureCount() {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return capture_count_;
|
||||
}
|
||||
|
||||
private:
|
||||
std::mutex mu_;
|
||||
std::string file_checksum_;
|
||||
std::string file_checksum_func_name_;
|
||||
int capture_count_ = 0;
|
||||
};
|
||||
|
||||
TEST_F(DBBlobBasicTest, GetBlob) {
|
||||
Options options = GetDefaultOptions();
|
||||
options.enable_blob_files = true;
|
||||
@@ -63,6 +113,110 @@ TEST_F(DBBlobBasicTest, GetBlob) {
|
||||
.IsIncomplete());
|
||||
}
|
||||
|
||||
TEST_F(DBBlobBasicTest, BlobFileChecksumInFileOptions) {
|
||||
auto capturing_fs =
|
||||
std::make_shared<BlobFileChecksumCapturingFS>(env_->GetFileSystem());
|
||||
std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, capturing_fs));
|
||||
|
||||
Options options = GetDefaultOptions();
|
||||
options.create_if_missing = true;
|
||||
options.env = env.get();
|
||||
options.enable_blob_files = true;
|
||||
options.min_blob_size = 0;
|
||||
options.file_checksum_gen_factory = GetFileChecksumGenCrc32cFactory();
|
||||
Defer close_db([this]() { Close(); });
|
||||
Reopen(options);
|
||||
|
||||
constexpr char key[] = "key";
|
||||
constexpr char blob_value[] = "blob_value";
|
||||
ASSERT_OK(Put(key, blob_value));
|
||||
ASSERT_OK(Flush());
|
||||
|
||||
std::vector<ColumnFamilyMetaData> column_family_metadata;
|
||||
db_->GetAllColumnFamilyMetaData(&column_family_metadata);
|
||||
ASSERT_EQ(column_family_metadata.size(), 1);
|
||||
ASSERT_EQ(column_family_metadata[0].blob_files.size(), 1);
|
||||
const BlobMetaData& blob_metadata = column_family_metadata[0].blob_files[0];
|
||||
ASSERT_FALSE(blob_metadata.checksum_value.empty());
|
||||
ASSERT_EQ(blob_metadata.checksum_method, "FileChecksumCrc32c");
|
||||
|
||||
ASSERT_EQ(Get(key), blob_value);
|
||||
|
||||
ASSERT_GT(capturing_fs->GetCaptureCount(), 0);
|
||||
ASSERT_EQ(capturing_fs->GetFileChecksum(), blob_metadata.checksum_value);
|
||||
ASSERT_EQ(capturing_fs->GetFileChecksumFuncName(),
|
||||
blob_metadata.checksum_method);
|
||||
}
|
||||
|
||||
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
|
||||
@@ -683,6 +837,15 @@ TEST_F(DBBlobBasicTest, MultiGetBlobsFromCache) {
|
||||
ASSERT_EQ(values[2], third_value);
|
||||
}
|
||||
|
||||
// Load the SST blocks into the block cache. The inlined key does not read
|
||||
// the blob file, so the blob cache stays empty.
|
||||
{
|
||||
ReadOptions fill_block_cache_options;
|
||||
std::string value;
|
||||
ASSERT_OK(db_->Get(fill_block_cache_options, first_key, &value));
|
||||
ASSERT_EQ(value, first_value);
|
||||
}
|
||||
|
||||
// Try again with no I/O allowed. The first (inlined) value should be
|
||||
// successfully read; however, the two blob values could only be read from the
|
||||
// blob file, so for those the read should return Incomplete.
|
||||
|
||||
@@ -40,6 +40,8 @@
|
||||
#include "rocksdb/utilities/replayer.h"
|
||||
#include "test_util/sync_point.h"
|
||||
#include "util/compression.h"
|
||||
#include "util/defer.h"
|
||||
#include "util/file_checksum_helper.h"
|
||||
#include "utilities/fault_injection_env.h"
|
||||
|
||||
namespace ROCKSDB_NAMESPACE {
|
||||
@@ -121,6 +123,59 @@ bool IsBlobFilePath(const std::string& fname) {
|
||||
file_type == kBlobFile;
|
||||
}
|
||||
|
||||
class BlobFileChecksumCapturingFileSystem : public FileSystemWrapper {
|
||||
public:
|
||||
explicit BlobFileChecksumCapturingFileSystem(
|
||||
const std::shared_ptr<FileSystem>& fs)
|
||||
: FileSystemWrapper(fs) {}
|
||||
|
||||
static const char* kClassName() {
|
||||
return "BlobFileChecksumCapturingFileSystem";
|
||||
}
|
||||
const char* Name() const override { return kClassName(); }
|
||||
|
||||
IOStatus NewRandomAccessFile(const std::string& fname,
|
||||
const FileOptions& opts,
|
||||
std::unique_ptr<FSRandomAccessFile>* result,
|
||||
IODebugContext* dbg) override {
|
||||
if (IsBlobFilePath(fname)) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
file_checksum_ = opts.file_checksum;
|
||||
file_checksum_func_name_ = opts.file_checksum_func_name;
|
||||
++capture_count_;
|
||||
}
|
||||
return target()->NewRandomAccessFile(fname, opts, result, dbg);
|
||||
}
|
||||
|
||||
void Reset() {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
file_checksum_.clear();
|
||||
file_checksum_func_name_.clear();
|
||||
capture_count_ = 0;
|
||||
}
|
||||
|
||||
std::string GetFileChecksum() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return file_checksum_;
|
||||
}
|
||||
|
||||
std::string GetFileChecksumFuncName() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return file_checksum_func_name_;
|
||||
}
|
||||
|
||||
int GetCaptureCount() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return capture_count_;
|
||||
}
|
||||
|
||||
private:
|
||||
mutable std::mutex mu_;
|
||||
std::string file_checksum_;
|
||||
std::string file_checksum_func_name_;
|
||||
int capture_count_ = 0;
|
||||
};
|
||||
|
||||
// Keeps track of when an active blob file stops being writer-visible so the
|
||||
// test filesystem can model current-size visibility only while the file remains
|
||||
// active.
|
||||
@@ -1755,6 +1810,54 @@ TEST_F(
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
ASSERT_EQ(iter->value().ToString(), values[target_idx]);
|
||||
}
|
||||
|
||||
TEST_F(DBBlobDirectWriteTest, DirectWriteDelayedReadUsesFinalizedFileChecksum) {
|
||||
auto capturing_fs = std::make_shared<BlobFileChecksumCapturingFileSystem>(
|
||||
env_->GetFileSystem());
|
||||
std::unique_ptr<Env> env(new CompositeEnvWrapper(env_, capturing_fs));
|
||||
|
||||
Options options = GetDirectWriteOptions();
|
||||
options.env = env.get();
|
||||
options.file_checksum_gen_factory = GetFileChecksumGenCrc32cFactory();
|
||||
Defer close_db([this]() { Close(); });
|
||||
Reopen(options);
|
||||
|
||||
const std::string key = "delayed-read-key";
|
||||
const std::string value(96, 'v');
|
||||
ASSERT_OK(Put(key, value));
|
||||
|
||||
ReadOptions read_options;
|
||||
read_options.allow_unprepared_value = true;
|
||||
std::unique_ptr<Iterator> iter(db_->NewIterator(read_options));
|
||||
iter->Seek(key);
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
ASSERT_EQ(iter->key(), key);
|
||||
ASSERT_TRUE(iter->value().empty());
|
||||
|
||||
ASSERT_OK(Flush());
|
||||
|
||||
std::vector<ColumnFamilyMetaData> column_family_metadata;
|
||||
db_->GetAllColumnFamilyMetaData(&column_family_metadata);
|
||||
ASSERT_EQ(column_family_metadata.size(), 1);
|
||||
ASSERT_EQ(column_family_metadata[0].blob_files.size(), 1);
|
||||
const BlobMetaData& blob_metadata = column_family_metadata[0].blob_files[0];
|
||||
ASSERT_FALSE(blob_metadata.checksum_value.empty());
|
||||
ASSERT_EQ(blob_metadata.checksum_method, "FileChecksumCrc32c");
|
||||
|
||||
capturing_fs->Reset();
|
||||
ASSERT_TRUE(iter->PrepareValue());
|
||||
ASSERT_TRUE(iter->Valid());
|
||||
ASSERT_EQ(iter->value().ToString(), value);
|
||||
ASSERT_GT(capturing_fs->GetCaptureCount(), 0);
|
||||
ASSERT_EQ(capturing_fs->GetFileChecksum(), blob_metadata.checksum_value);
|
||||
ASSERT_EQ(capturing_fs->GetFileChecksumFuncName(),
|
||||
blob_metadata.checksum_method);
|
||||
|
||||
const int capture_count = capturing_fs->GetCaptureCount();
|
||||
ASSERT_EQ(Get(key), value);
|
||||
ASSERT_EQ(capturing_fs->GetCaptureCount(), capture_count);
|
||||
}
|
||||
|
||||
TEST_F(DBBlobDirectWriteTest, OrderedTraceUsesLogicalBatchForBlobDirectWrite) {
|
||||
AssertOrderedTraceStoresLogicalPut(GetDirectWriteOptions(),
|
||||
/*expect_blob_files=*/true);
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
#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"
|
||||
@@ -138,8 +139,11 @@ 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, current, cfd(), value,
|
||||
read_options, key, resolve_direct_write_value, blob_fetcher, value,
|
||||
columns, s, is_blob_index, value_found);
|
||||
}
|
||||
|
||||
@@ -1028,6 +1032,53 @@ TEST_F(DBBlobIndexTest, EmbeddedBlobWideColumnGetEntityBlockCacheTier) {
|
||||
ASSERT_TRUE(s.IsIncomplete()) << s.ToString();
|
||||
}
|
||||
|
||||
// Companion to the test above (genuine miss -> Incomplete): with a blob cache
|
||||
// configured, a warm read populates the embedded record into the blob cache, so
|
||||
// a subsequent kBlockCacheTier GetEntity serves it from cache instead of
|
||||
// returning Incomplete. This exercises the non-lazy Get/GetEntity embedded path
|
||||
// (get_context -> EmbeddedAwareBlobFetcher -> GetSameFileBlob whole ->
|
||||
// ResolveEmbeddedBlobCached), which shares the block-cache-tier behavior with
|
||||
// the lazy resolver (a same-file column already in the blob cache is served).
|
||||
TEST_F(DBBlobIndexTest,
|
||||
EmbeddedBlobWideColumnGetEntityBlockCacheTierServesCached) {
|
||||
Options options = GetTestOptions();
|
||||
options.create_if_missing = true;
|
||||
LRUCacheOptions co;
|
||||
co.capacity = 8 << 20;
|
||||
options.blob_cache = NewLRUCache(co);
|
||||
DestroyAndReopen(options);
|
||||
|
||||
const std::string sst_path = dbname_ + "/embedded_wc_blockcache_hit.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 both the block cache (data block) and the blob cache (embedded record)
|
||||
// with a full read.
|
||||
{
|
||||
PinnableWideColumns result;
|
||||
ASSERT_OK(db_->GetEntity(ReadOptions(), db_->DefaultColumnFamily(), "k",
|
||||
&result));
|
||||
ASSERT_EQ(result.columns(), columns);
|
||||
}
|
||||
|
||||
// The embedded record is now cached, so a block-cache-only read serves it.
|
||||
ReadOptions read_options;
|
||||
read_options.read_tier = kBlockCacheTier;
|
||||
PinnableWideColumns result;
|
||||
ASSERT_OK(
|
||||
db_->GetEntity(read_options, db_->DefaultColumnFamily(), "k", &result));
|
||||
ASSERT_EQ(result.columns(), columns);
|
||||
}
|
||||
|
||||
// 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
|
||||
|
||||
@@ -5,6 +5,10 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#include "db/blob/blob_constants.h"
|
||||
#include "rocksdb/rocksdb_namespace.h"
|
||||
#include "rocksdb/status.h"
|
||||
|
||||
@@ -14,6 +18,18 @@ class BlobIndex;
|
||||
class PinnableSlice;
|
||||
struct ReadOptions;
|
||||
|
||||
// One request for SameFileBlobReader::MultiGetSameFileBlob (the batched
|
||||
// counterpart of GetSameFileBlob). See GetSameFileBlob for the per-field
|
||||
// semantics (range_length == kWholeBlobLength selects the whole value).
|
||||
struct SameFileBlobReadRequest {
|
||||
const BlobIndex* blob_index = nullptr;
|
||||
uint64_t range_offset = 0;
|
||||
size_t range_length = kWholeBlobLength;
|
||||
BlobVerifyPolicy verify_policy = BlobVerifyPolicy::kVerifyIfNoAmplification;
|
||||
PinnableSlice* result = nullptr;
|
||||
Status* status = nullptr;
|
||||
};
|
||||
|
||||
// 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)
|
||||
@@ -27,13 +43,48 @@ 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.
|
||||
// Resolves a same-file ("embedded") 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).
|
||||
//
|
||||
// range_length == kWholeBlobLength resolves the whole value. Any other length
|
||||
// resolves only the sub-range [range_offset, range_offset + range_length),
|
||||
// reading just those bytes on a cache miss -- skipping whole-record checksum
|
||||
// verification (a strict sub-range cannot cover it) and never populating the
|
||||
// blob cache; valid only for an uncompressed record and a verify_policy other
|
||||
// than kVerifyIfPresent, with range_offset + range_length <=
|
||||
// blob_index.size().
|
||||
//
|
||||
// verify_policy controls whole-record checksum verification (see
|
||||
// BlobVerifyPolicy); a whole read under kVerifyIfPresent verifies even when
|
||||
// ReadOptions::verify_checksums is off. 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,
|
||||
uint64_t range_offset, size_t range_length,
|
||||
BlobVerifyPolicy verify_policy,
|
||||
PinnableSlice* value) const = 0;
|
||||
|
||||
// Batched counterpart of GetSameFileBlob: resolves `num_reads` same-file blob
|
||||
// references (whole or sub-range, mixed) against this reader, writing each
|
||||
// outcome to *reqs[i].status. Implementations may coalesce the underlying
|
||||
// disk reads into a single MultiRead. The default implementation simply loops
|
||||
// over GetSameFileBlob (correct, but not coalesced); BlockBasedTable
|
||||
// overrides it to coalesce reads of embedded records in the same SST.
|
||||
virtual void MultiGetSameFileBlob(const ReadOptions& read_options,
|
||||
size_t num_reads,
|
||||
SameFileBlobReadRequest* reqs) const {
|
||||
for (size_t i = 0; i < num_reads; ++i) {
|
||||
SameFileBlobReadRequest& req = reqs[i];
|
||||
const Status s =
|
||||
GetSameFileBlob(read_options, *req.blob_index, req.range_offset,
|
||||
req.range_length, req.verify_policy, req.result);
|
||||
if (req.status) {
|
||||
*req.status = s;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace ROCKSDB_NAMESPACE
|
||||
+5
-3
@@ -207,7 +207,8 @@ Status BuildTable(
|
||||
std::move(file), fname, file_options, ioptions.clock, io_tracer,
|
||||
ioptions.stats, Histograms::SST_WRITE_MICROS, ioptions.listeners,
|
||||
ioptions.file_checksum_gen_factory.get(),
|
||||
tmp_set.Contains(FileType::kTableFile), false));
|
||||
tmp_set.Contains(FileType::kTableFile),
|
||||
tmp_set.Contains(FileType::kTableFile)));
|
||||
|
||||
builder = NewTableBuilder(tboptions, file_writer.get());
|
||||
}
|
||||
@@ -395,7 +396,7 @@ Status BuildTable(
|
||||
relevant_mapping,
|
||||
ioptions.compaction_style == CompactionStyle::kCompactionStyleFIFO
|
||||
? meta->file_creation_time
|
||||
: meta->oldest_ancester_time);
|
||||
: meta->oldest_ancestor_time);
|
||||
s = builder->Finish();
|
||||
}
|
||||
if (io_status->ok()) {
|
||||
@@ -451,7 +452,8 @@ Status BuildTable(
|
||||
WritableFileWriter::PrepareIOOptions(tboptions.write_options, opts);
|
||||
if (s.ok() && io_status->ok() && !empty) {
|
||||
StopWatch sw(ioptions.clock, ioptions.stats, TABLE_SYNC_MICROS);
|
||||
*io_status = file_writer->Sync(opts, ioptions.use_fsync);
|
||||
*io_status = ioptions.use_fsync ? file_writer->Fsync(opts)
|
||||
: file_writer->Sync(opts);
|
||||
}
|
||||
TEST_SYNC_POINT("BuildTable:BeforeCloseTableFile");
|
||||
if (s.ok() && io_status->ok() && !empty) {
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
|
||||
#include <cstdlib>
|
||||
#include <iterator>
|
||||
#include <limits>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <unordered_set>
|
||||
@@ -182,7 +183,6 @@ 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,10 +190,12 @@ 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;
|
||||
using ROCKSDB_NAMESPACE::WriteBatchWithIndex;
|
||||
using ROCKSDB_NAMESPACE::WriteBufferFlushPolicy;
|
||||
using ROCKSDB_NAMESPACE::WriteBufferManager;
|
||||
using ROCKSDB_NAMESPACE::WriteOptions;
|
||||
using ROCKSDB_NAMESPACE::WriteStallCondition;
|
||||
@@ -412,12 +414,16 @@ 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 = {};
|
||||
rep.table_filter = nullptr;
|
||||
table_filter_func = {};
|
||||
if (table_filter_destructor != nullptr) {
|
||||
(*table_filter_destructor)(table_filter_state);
|
||||
}
|
||||
@@ -435,11 +441,12 @@ struct rocksdb_readoptions_t {
|
||||
if (callback != nullptr) {
|
||||
auto cb = table_filter_callback;
|
||||
auto filter_state = table_filter_state;
|
||||
rep.table_filter = [cb, filter_state](const TableProperties& props) {
|
||||
table_filter_func = [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;
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -480,10 +487,10 @@ struct rocksdb_writablefile_t {
|
||||
WritableFile* rep;
|
||||
};
|
||||
struct rocksdb_wal_iterator_t {
|
||||
TransactionLogIterator* rep;
|
||||
WalIterator* rep;
|
||||
};
|
||||
struct rocksdb_wal_readoptions_t {
|
||||
TransactionLogIterator::ReadOptions rep;
|
||||
WalIterator::ReadOptions rep;
|
||||
};
|
||||
|
||||
struct rocksdb_wal_files_t {
|
||||
@@ -594,6 +601,63 @@ 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;
|
||||
};
|
||||
@@ -2560,6 +2624,59 @@ char* rocksdb_get(rocksdb_t* db, const rocksdb_readoptions_t* options,
|
||||
return result;
|
||||
}
|
||||
|
||||
static char* rocksdb_get_with_metadata_impl(
|
||||
rocksdb_t* db, const rocksdb_readoptions_t* options,
|
||||
ColumnFamilyHandle* column_family, const char* key, size_t keylen,
|
||||
size_t* vallen, char** timestamp, size_t* timestamp_len,
|
||||
unsigned char* newer_version_present, char** errptr) {
|
||||
ROCKSDB_NAMESPACE::OutputMetadata output_metadata;
|
||||
if (timestamp != nullptr && timestamp_len != nullptr) {
|
||||
output_metadata.WantTimestamp();
|
||||
}
|
||||
if (newer_version_present != nullptr) {
|
||||
output_metadata.WantNewerVersionPresent();
|
||||
}
|
||||
|
||||
PinnableSlice pinnable_val;
|
||||
const Status s =
|
||||
db->rep->GetWithMetadata(options->rep, column_family, Slice(key, keylen),
|
||||
&pinnable_val, &output_metadata);
|
||||
if (newer_version_present != nullptr) {
|
||||
*newer_version_present = *output_metadata.newer_version_present ? 1 : 0;
|
||||
}
|
||||
|
||||
char* result = nullptr;
|
||||
if (s.ok()) {
|
||||
*vallen = pinnable_val.size();
|
||||
result = CopyString(pinnable_val);
|
||||
if (output_metadata.timestamp.has_value()) {
|
||||
*timestamp_len = output_metadata.timestamp->size();
|
||||
*timestamp = CopyString(*output_metadata.timestamp);
|
||||
}
|
||||
} else {
|
||||
*vallen = 0;
|
||||
if (output_metadata.timestamp.has_value()) {
|
||||
*timestamp = nullptr;
|
||||
*timestamp_len = 0;
|
||||
}
|
||||
if (!s.IsNotFound()) {
|
||||
SaveError(errptr, s);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
char* rocksdb_get_with_metadata(rocksdb_t* db,
|
||||
const rocksdb_readoptions_t* options,
|
||||
const char* key, size_t keylen, size_t* vallen,
|
||||
char** timestamp, size_t* timestamp_len,
|
||||
unsigned char* newer_version_present,
|
||||
char** errptr) {
|
||||
return rocksdb_get_with_metadata_impl(
|
||||
db, options, db->rep->DefaultColumnFamily(), key, keylen, vallen,
|
||||
timestamp, timestamp_len, newer_version_present, errptr);
|
||||
}
|
||||
|
||||
char* rocksdb_get_cf(rocksdb_t* db, const rocksdb_readoptions_t* options,
|
||||
rocksdb_column_family_handle_t* column_family,
|
||||
const char* key, size_t keylen, size_t* vallen,
|
||||
@@ -2582,6 +2699,16 @@ char* rocksdb_get_cf(rocksdb_t* db, const rocksdb_readoptions_t* options,
|
||||
return result;
|
||||
}
|
||||
|
||||
char* rocksdb_get_cf_with_metadata(
|
||||
rocksdb_t* db, const rocksdb_readoptions_t* options,
|
||||
rocksdb_column_family_handle_t* column_family, const char* key,
|
||||
size_t keylen, size_t* vallen, char** timestamp, size_t* timestamp_len,
|
||||
unsigned char* newer_version_present, char** errptr) {
|
||||
return rocksdb_get_with_metadata_impl(
|
||||
db, options, column_family->rep, key, keylen, vallen, timestamp,
|
||||
timestamp_len, newer_version_present, errptr);
|
||||
}
|
||||
|
||||
char* rocksdb_get_with_ts(rocksdb_t* db, const rocksdb_readoptions_t* options,
|
||||
const char* key, size_t keylen, size_t* vallen,
|
||||
char** ts, size_t* tslen, char** errptr) {
|
||||
@@ -2673,6 +2800,72 @@ void rocksdb_multi_get(rocksdb_t* db, const rocksdb_readoptions_t* options,
|
||||
}
|
||||
}
|
||||
|
||||
static void rocksdb_multi_get_with_metadata_impl(
|
||||
rocksdb_t* db, const rocksdb_readoptions_t* options,
|
||||
ColumnFamilyHandle* const* column_families, size_t num_keys,
|
||||
const char* const* keys_list, const size_t* keys_list_sizes,
|
||||
char** values_list, size_t* values_list_sizes, char** timestamp_list,
|
||||
size_t* timestamp_list_sizes, unsigned char* newer_version_present,
|
||||
char** errs) {
|
||||
std::unique_ptr<Slice[]> keys(new Slice[num_keys]);
|
||||
std::vector<PinnableSlice> values(num_keys);
|
||||
std::vector<Status> statuses(num_keys);
|
||||
for (size_t i = 0; i < num_keys; ++i) {
|
||||
keys[i] = Slice(keys_list[i], keys_list_sizes[i]);
|
||||
}
|
||||
|
||||
ROCKSDB_NAMESPACE::MultiGetOutputMetadata output_metadata;
|
||||
if (timestamp_list != nullptr && timestamp_list_sizes != nullptr) {
|
||||
output_metadata.WantTimestamps();
|
||||
}
|
||||
if (newer_version_present != nullptr) {
|
||||
output_metadata.WantNewerVersionPresent();
|
||||
}
|
||||
db->rep->MultiGetWithMetadata(options->rep, num_keys, column_families,
|
||||
keys.get(), values.data(), statuses.data(),
|
||||
&output_metadata);
|
||||
|
||||
for (size_t i = 0; i < num_keys; ++i) {
|
||||
if (newer_version_present != nullptr) {
|
||||
newer_version_present[i] =
|
||||
(*output_metadata.newer_version_present)[i] ? 1 : 0;
|
||||
}
|
||||
if (statuses[i].ok()) {
|
||||
values_list[i] = CopyString(values[i]);
|
||||
values_list_sizes[i] = values[i].size();
|
||||
if (output_metadata.timestamps.has_value()) {
|
||||
timestamp_list[i] = CopyString((*output_metadata.timestamps)[i]);
|
||||
timestamp_list_sizes[i] = (*output_metadata.timestamps)[i].size();
|
||||
}
|
||||
errs[i] = nullptr;
|
||||
} else {
|
||||
values_list[i] = nullptr;
|
||||
values_list_sizes[i] = 0;
|
||||
if (output_metadata.timestamps.has_value()) {
|
||||
timestamp_list[i] = nullptr;
|
||||
timestamp_list_sizes[i] = 0;
|
||||
}
|
||||
errs[i] = statuses[i].IsNotFound()
|
||||
? nullptr
|
||||
: strdup(statuses[i].ToString().c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void rocksdb_multi_get_with_metadata(
|
||||
rocksdb_t* db, const rocksdb_readoptions_t* options, size_t num_keys,
|
||||
const char* const* keys_list, const size_t* keys_list_sizes,
|
||||
char** values_list, size_t* values_list_sizes, char** timestamp_list,
|
||||
size_t* timestamp_list_sizes, unsigned char* newer_version_present,
|
||||
char** errs) {
|
||||
std::vector<ColumnFamilyHandle*> column_families(
|
||||
num_keys, db->rep->DefaultColumnFamily());
|
||||
rocksdb_multi_get_with_metadata_impl(
|
||||
db, options, column_families.data(), num_keys, keys_list, keys_list_sizes,
|
||||
values_list, values_list_sizes, timestamp_list, timestamp_list_sizes,
|
||||
newer_version_present, errs);
|
||||
}
|
||||
|
||||
void rocksdb_multi_get_with_ts(rocksdb_t* db,
|
||||
const rocksdb_readoptions_t* options,
|
||||
size_t num_keys, const char* const* keys_list,
|
||||
@@ -2748,6 +2941,24 @@ void rocksdb_multi_get_cf(
|
||||
}
|
||||
}
|
||||
|
||||
void rocksdb_multi_get_cf_with_metadata(
|
||||
rocksdb_t* db, const rocksdb_readoptions_t* options,
|
||||
const rocksdb_column_family_handle_t* const* column_families,
|
||||
size_t num_keys, const char* const* keys_list,
|
||||
const size_t* keys_list_sizes, char** values_list,
|
||||
size_t* values_list_sizes, char** timestamp_list,
|
||||
size_t* timestamp_list_sizes, unsigned char* newer_version_present,
|
||||
char** errs) {
|
||||
std::vector<ColumnFamilyHandle*> cfs(num_keys);
|
||||
for (size_t i = 0; i < num_keys; ++i) {
|
||||
cfs[i] = column_families[i]->rep;
|
||||
}
|
||||
rocksdb_multi_get_with_metadata_impl(
|
||||
db, options, cfs.data(), num_keys, keys_list, keys_list_sizes,
|
||||
values_list, values_list_sizes, timestamp_list, timestamp_list_sizes,
|
||||
newer_version_present, errs);
|
||||
}
|
||||
|
||||
void rocksdb_multi_get_cf_with_ts(
|
||||
rocksdb_t* db, const rocksdb_readoptions_t* options,
|
||||
const rocksdb_column_family_handle_t* const* column_families,
|
||||
@@ -2862,6 +3073,44 @@ 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,
|
||||
@@ -2921,8 +3170,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<TransactionLogIterator> iter;
|
||||
TransactionLogIterator::ReadOptions ro;
|
||||
std::unique_ptr<WalIterator> iter;
|
||||
WalIterator::ReadOptions ro;
|
||||
if (options != nullptr) {
|
||||
ro = options->rep;
|
||||
}
|
||||
@@ -4949,6 +5198,11 @@ uint64_t rocksdb_table_properties_column_family_id(
|
||||
return props->rep.column_family_id;
|
||||
}
|
||||
|
||||
uint64_t rocksdb_table_properties_oldest_ancestor_time(
|
||||
const rocksdb_table_properties_t* props) {
|
||||
return props->rep.oldest_ancestor_time;
|
||||
}
|
||||
|
||||
uint64_t rocksdb_table_properties_creation_time(
|
||||
const rocksdb_table_properties_t* props) {
|
||||
return props->rep.creation_time;
|
||||
@@ -4979,11 +5233,6 @@ uint64_t rocksdb_table_properties_fast_compression_estimated_data_size(
|
||||
return props->rep.fast_compression_estimated_data_size;
|
||||
}
|
||||
|
||||
uint64_t rocksdb_table_properties_external_sst_file_global_seqno_offset(
|
||||
const rocksdb_table_properties_t* props) {
|
||||
return props->rep.external_sst_file_global_seqno_offset;
|
||||
}
|
||||
|
||||
uint64_t rocksdb_table_properties_tail_start_offset(
|
||||
const rocksdb_table_properties_t* props) {
|
||||
return props->rep.tail_start_offset;
|
||||
@@ -5019,6 +5268,11 @@ uint64_t rocksdb_table_properties_separate_key_value_in_data_block(
|
||||
return props->rep.separate_key_value_in_data_block;
|
||||
}
|
||||
|
||||
uint64_t rocksdb_table_properties_lsm_info_at_creation(
|
||||
const rocksdb_table_properties_t* props) {
|
||||
return props->rep.lsm_info_at_creation;
|
||||
}
|
||||
|
||||
const char* rocksdb_table_properties_db_id(
|
||||
const rocksdb_table_properties_t* props, size_t* size) {
|
||||
*size = props->rep.db_id.size();
|
||||
@@ -7508,6 +7762,35 @@ rocksdb_write_buffer_manager_t* rocksdb_write_buffer_manager_create(
|
||||
return wbm;
|
||||
}
|
||||
|
||||
static bool rocksdb_write_buffer_manager_parse_flush_policy(
|
||||
int value, WriteBufferFlushPolicy* policy) {
|
||||
switch (value) {
|
||||
case rocksdb_write_buffer_manager_flush_policy_oldest:
|
||||
*policy = WriteBufferFlushPolicy::kFlushOldest;
|
||||
return true;
|
||||
case rocksdb_write_buffer_manager_flush_policy_largest:
|
||||
*policy = WriteBufferFlushPolicy::kFlushLargest;
|
||||
return true;
|
||||
case rocksdb_write_buffer_manager_flush_policy_largest_across_dbs:
|
||||
*policy = WriteBufferFlushPolicy::kFlushLargestAcrossDBs;
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
rocksdb_write_buffer_manager_t* rocksdb_write_buffer_manager_create_with_policy(
|
||||
size_t buffer_size, bool allow_stall, int flush_policy) {
|
||||
WriteBufferFlushPolicy policy;
|
||||
if (!rocksdb_write_buffer_manager_parse_flush_policy(flush_policy, &policy)) {
|
||||
return nullptr;
|
||||
}
|
||||
rocksdb_write_buffer_manager_t* wbm = new rocksdb_write_buffer_manager_t;
|
||||
wbm->rep = std::make_shared<WriteBufferManager>(
|
||||
buffer_size, std::shared_ptr<Cache>{}, allow_stall, policy);
|
||||
return wbm;
|
||||
}
|
||||
|
||||
rocksdb_write_buffer_manager_t* rocksdb_write_buffer_manager_create_with_cache(
|
||||
size_t buffer_size, const rocksdb_cache_t* cache, bool allow_stall) {
|
||||
rocksdb_write_buffer_manager_t* wbm = new rocksdb_write_buffer_manager_t;
|
||||
@@ -7516,6 +7799,20 @@ rocksdb_write_buffer_manager_t* rocksdb_write_buffer_manager_create_with_cache(
|
||||
return wbm;
|
||||
}
|
||||
|
||||
rocksdb_write_buffer_manager_t*
|
||||
rocksdb_write_buffer_manager_create_with_cache_and_policy(
|
||||
size_t buffer_size, const rocksdb_cache_t* cache, bool allow_stall,
|
||||
int flush_policy) {
|
||||
WriteBufferFlushPolicy policy;
|
||||
if (!rocksdb_write_buffer_manager_parse_flush_policy(flush_policy, &policy)) {
|
||||
return nullptr;
|
||||
}
|
||||
rocksdb_write_buffer_manager_t* wbm = new rocksdb_write_buffer_manager_t;
|
||||
wbm->rep = std::make_shared<WriteBufferManager>(buffer_size, cache->rep,
|
||||
allow_stall, policy);
|
||||
return wbm;
|
||||
}
|
||||
|
||||
void rocksdb_write_buffer_manager_destroy(rocksdb_write_buffer_manager_t* wbm) {
|
||||
delete wbm;
|
||||
}
|
||||
@@ -7556,6 +7853,19 @@ ROCKSDB_LIBRARY_API void rocksdb_write_buffer_manager_set_allow_stall(
|
||||
wbm->rep->SetAllowStall(new_allow_stall);
|
||||
}
|
||||
|
||||
int rocksdb_write_buffer_manager_flush_policy(
|
||||
rocksdb_write_buffer_manager_t* wbm) {
|
||||
return static_cast<int>(wbm->rep->flush_policy());
|
||||
}
|
||||
|
||||
void rocksdb_write_buffer_manager_set_flush_policy(
|
||||
rocksdb_write_buffer_manager_t* wbm, int flush_policy) {
|
||||
WriteBufferFlushPolicy policy;
|
||||
if (rocksdb_write_buffer_manager_parse_flush_policy(flush_policy, &policy)) {
|
||||
wbm->rep->SetFlushPolicy(policy);
|
||||
}
|
||||
}
|
||||
|
||||
rocksdb_sst_file_manager_t* rocksdb_sst_file_manager_create(
|
||||
rocksdb_env_t* env) {
|
||||
rocksdb_sst_file_manager_t* sfm = new rocksdb_sst_file_manager_t;
|
||||
@@ -9107,6 +9417,15 @@ 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;
|
||||
@@ -9773,6 +10092,26 @@ const char* rocksdb_options_get_db_host_id(rocksdb_options_t* opt,
|
||||
return opt->rep.db_host_id.data();
|
||||
}
|
||||
|
||||
void rocksdb_options_set_remote_compaction_manifest_floor(
|
||||
rocksdb_options_t* opt, unsigned char v) {
|
||||
opt->rep.remote_compaction_manifest_floor = v;
|
||||
}
|
||||
|
||||
unsigned char rocksdb_options_get_remote_compaction_manifest_floor(
|
||||
rocksdb_options_t* opt) {
|
||||
return opt->rep.remote_compaction_manifest_floor;
|
||||
}
|
||||
|
||||
void rocksdb_options_set_use_session_tmp_dir_for_remote_compaction(
|
||||
rocksdb_options_t* opt, unsigned char v) {
|
||||
opt->rep.use_session_tmp_dir_for_remote_compaction = v;
|
||||
}
|
||||
|
||||
unsigned char rocksdb_options_get_use_session_tmp_dir_for_remote_compaction(
|
||||
rocksdb_options_t* opt) {
|
||||
return opt->rep.use_session_tmp_dir_for_remote_compaction;
|
||||
}
|
||||
|
||||
void rocksdb_options_set_lowest_used_cache_tier(rocksdb_options_t* opt, int v) {
|
||||
opt->rep.lowest_used_cache_tier =
|
||||
static_cast<decltype(opt->rep.lowest_used_cache_tier)>(v);
|
||||
@@ -9813,6 +10152,16 @@ uint64_t rocksdb_options_get_max_compaction_trigger_wakeup_seconds(
|
||||
return opt->rep.max_compaction_trigger_wakeup_seconds;
|
||||
}
|
||||
|
||||
void rocksdb_options_set_periodic_compaction_phase_recovery_percent(
|
||||
rocksdb_options_t* opt, int v) {
|
||||
opt->rep.periodic_compaction_phase_recovery_percent = v;
|
||||
}
|
||||
|
||||
int rocksdb_options_get_periodic_compaction_phase_recovery_percent(
|
||||
rocksdb_options_t* opt) {
|
||||
return opt->rep.periodic_compaction_phase_recovery_percent;
|
||||
}
|
||||
|
||||
void rocksdb_options_set_follower_refresh_catchup_period_ms(
|
||||
rocksdb_options_t* opt, uint64_t v) {
|
||||
opt->rep.follower_refresh_catchup_period_ms = v;
|
||||
@@ -10262,6 +10611,16 @@ 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);
|
||||
@@ -10974,16 +11333,6 @@ unsigned char rocksdb_ingestexternalfileoptions_get_ingest_behind(
|
||||
return opt->rep.ingest_behind;
|
||||
}
|
||||
|
||||
void rocksdb_ingestexternalfileoptions_set_write_global_seqno(
|
||||
rocksdb_ingestexternalfileoptions_t* opt, unsigned char v) {
|
||||
opt->rep.write_global_seqno = v;
|
||||
}
|
||||
|
||||
unsigned char rocksdb_ingestexternalfileoptions_get_write_global_seqno(
|
||||
rocksdb_ingestexternalfileoptions_t* opt) {
|
||||
return opt->rep.write_global_seqno;
|
||||
}
|
||||
|
||||
void rocksdb_ingestexternalfileoptions_set_verify_checksums_before_ingest(
|
||||
rocksdb_ingestexternalfileoptions_t* opt, unsigned char v) {
|
||||
opt->rep.verify_checksums_before_ingest = v;
|
||||
@@ -11064,6 +11413,16 @@ int rocksdb_ingestexternalfileoptions_get_file_opening_threads(
|
||||
|
||||
/* OpenAndCompactOptions */
|
||||
|
||||
void rocksdb_open_and_compact_options_set_max_secondary_open_retries(
|
||||
rocksdb_open_and_compact_options_t* opt, uint32_t v) {
|
||||
opt->rep.max_secondary_open_retries = v;
|
||||
}
|
||||
|
||||
uint32_t rocksdb_open_and_compact_options_get_max_secondary_open_retries(
|
||||
rocksdb_open_and_compact_options_t* opt) {
|
||||
return opt->rep.max_secondary_open_retries;
|
||||
}
|
||||
|
||||
unsigned char rocksdb_open_and_compact_options_get_allow_resumption(
|
||||
rocksdb_open_and_compact_options_t* opt) {
|
||||
return opt->rep.allow_resumption;
|
||||
@@ -11461,6 +11820,17 @@ double rocksdb_block_based_options_get_uniform_cv_threshold(
|
||||
return opt->rep.uniform_cv_threshold;
|
||||
}
|
||||
|
||||
void rocksdb_block_based_options_set_optimize_key_common_prefix(
|
||||
rocksdb_block_based_table_options_t* opt, int v) {
|
||||
opt->rep.optimize_key_common_prefix =
|
||||
static_cast<decltype(opt->rep.optimize_key_common_prefix)>(v);
|
||||
}
|
||||
|
||||
int rocksdb_block_based_options_get_optimize_key_common_prefix(
|
||||
rocksdb_block_based_table_options_t* opt) {
|
||||
return static_cast<int>(opt->rep.optimize_key_common_prefix);
|
||||
}
|
||||
|
||||
void rocksdb_block_based_options_set_enable_index_compression(
|
||||
rocksdb_block_based_table_options_t* opt, unsigned char v) {
|
||||
opt->rep.enable_index_compression = v;
|
||||
|
||||
+237
@@ -189,6 +189,57 @@ 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;
|
||||
@@ -834,6 +885,39 @@ 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) {
|
||||
@@ -2390,6 +2474,35 @@ int main(int argc, char** argv) {
|
||||
CheckNoError(err);
|
||||
rocksdb_readoptions_set_snapshot(roptions, snap);
|
||||
CheckGet(db, roptions, "foo", "hello");
|
||||
|
||||
size_t metadata_value_len = 0;
|
||||
unsigned char newer_version_present = 0;
|
||||
char* metadata_value =
|
||||
rocksdb_get_with_metadata(db, roptions, "foo", 3, &metadata_value_len,
|
||||
NULL, NULL, &newer_version_present, &err);
|
||||
// NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling)
|
||||
CheckNoError(err);
|
||||
CheckEqual("hello", metadata_value, metadata_value_len);
|
||||
// NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling)
|
||||
CheckCondition(newer_version_present == 1);
|
||||
Free(&metadata_value);
|
||||
|
||||
const char* metadata_keys[] = {"foo"};
|
||||
const size_t metadata_key_sizes[] = {3};
|
||||
char* metadata_values[1];
|
||||
size_t metadata_value_sizes[1];
|
||||
unsigned char newer_versions[1];
|
||||
char* metadata_errors[1];
|
||||
rocksdb_multi_get_with_metadata(
|
||||
db, roptions, 1, metadata_keys, metadata_key_sizes, metadata_values,
|
||||
metadata_value_sizes, NULL, NULL, newer_versions, metadata_errors);
|
||||
// NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling)
|
||||
CheckCondition(metadata_errors[0] == NULL);
|
||||
CheckEqual("hello", metadata_values[0], metadata_value_sizes[0]);
|
||||
// NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling)
|
||||
CheckCondition(newer_versions[0] == 1);
|
||||
Free(&metadata_values[0]);
|
||||
|
||||
rocksdb_readoptions_set_snapshot(roptions, NULL);
|
||||
CheckGet(db, roptions, "foo", NULL);
|
||||
rocksdb_release_snapshot(db, snap);
|
||||
@@ -2639,12 +2752,17 @@ 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};
|
||||
@@ -3167,6 +3285,95 @@ 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;
|
||||
|
||||
@@ -6509,6 +6716,36 @@ int main(int argc, char** argv) {
|
||||
300 == rocksdb_write_buffer_manager_buffer_size(write_buffer_manager));
|
||||
|
||||
rocksdb_write_buffer_manager_destroy(write_buffer_manager);
|
||||
|
||||
write_buffer_manager = rocksdb_write_buffer_manager_create_with_policy(
|
||||
200, true,
|
||||
rocksdb_write_buffer_manager_flush_policy_largest_across_dbs);
|
||||
CheckCondition(write_buffer_manager != NULL);
|
||||
CheckCondition(
|
||||
rocksdb_write_buffer_manager_flush_policy_largest_across_dbs ==
|
||||
rocksdb_write_buffer_manager_flush_policy(write_buffer_manager));
|
||||
rocksdb_write_buffer_manager_set_flush_policy(
|
||||
write_buffer_manager,
|
||||
rocksdb_write_buffer_manager_flush_policy_largest);
|
||||
CheckCondition(
|
||||
rocksdb_write_buffer_manager_flush_policy_largest ==
|
||||
rocksdb_write_buffer_manager_flush_policy(write_buffer_manager));
|
||||
rocksdb_write_buffer_manager_set_flush_policy(write_buffer_manager, 999);
|
||||
CheckCondition(
|
||||
rocksdb_write_buffer_manager_flush_policy_largest ==
|
||||
rocksdb_write_buffer_manager_flush_policy(write_buffer_manager));
|
||||
rocksdb_write_buffer_manager_destroy(write_buffer_manager);
|
||||
|
||||
write_buffer_manager =
|
||||
rocksdb_write_buffer_manager_create_with_cache_and_policy(
|
||||
200, lru, true,
|
||||
rocksdb_write_buffer_manager_flush_policy_largest_across_dbs);
|
||||
CheckCondition(write_buffer_manager != NULL);
|
||||
rocksdb_write_buffer_manager_destroy(write_buffer_manager);
|
||||
|
||||
write_buffer_manager =
|
||||
rocksdb_write_buffer_manager_create_with_policy(200, true, 999);
|
||||
CheckCondition(write_buffer_manager == NULL);
|
||||
rocksdb_cache_destroy(lru);
|
||||
}
|
||||
|
||||
|
||||
+127
-10
@@ -33,6 +33,7 @@
|
||||
#include "db/write_controller.h"
|
||||
#include "file/sst_file_manager_impl.h"
|
||||
#include "logging/logging.h"
|
||||
#include "memtable/flush_initiator.h"
|
||||
#include "monitoring/thread_status_util.h"
|
||||
#include "options/options_helper.h"
|
||||
#include "port/port.h"
|
||||
@@ -672,7 +673,7 @@ ColumnFamilyData::ColumnFamilyData(
|
||||
new InternalStats(ioptions_.num_levels, ioptions_.clock, this));
|
||||
table_cache_.reset(new TableCache(ioptions_, file_options, _table_cache,
|
||||
block_cache_tracer, io_tracer,
|
||||
db_session_id, fast_sst_open));
|
||||
db_session_id, fast_sst_open, name_));
|
||||
blob_file_cache_.reset(
|
||||
new BlobFileCache(_table_cache, &ioptions(), soptions(), id_,
|
||||
internal_stats_->GetBlobFileReadHist(), io_tracer));
|
||||
@@ -834,6 +835,11 @@ void ColumnFamilyData::SetDropped() {
|
||||
// can't drop default CF
|
||||
assert(id_ != 0);
|
||||
dropped_ = true;
|
||||
// A tracker can still contain accounting published while a different WBM
|
||||
// policy was active. Cleanup therefore cannot depend on the current policy.
|
||||
if (mem_ != nullptr) {
|
||||
mem_->StopWBMTracking();
|
||||
}
|
||||
write_controller_token_.reset();
|
||||
|
||||
// remove from column_family_set
|
||||
@@ -1246,7 +1252,10 @@ uint64_t ColumnFamilyData::GetLiveSstFilesSize() const {
|
||||
MemTable* ColumnFamilyData::ConstructNewMemtable(
|
||||
const MutableCFOptions& mutable_cf_options, SequenceNumber earliest_seq) {
|
||||
return new MemTable(internal_comparator_, ioptions_, mutable_cf_options,
|
||||
write_buffer_manager_, earliest_seq, id_);
|
||||
write_buffer_manager_, earliest_seq, id_,
|
||||
column_family_set_ != nullptr
|
||||
? column_family_set_->flush_initiator()
|
||||
: nullptr);
|
||||
}
|
||||
|
||||
void ColumnFamilyData::CreateNewMemtable(SequenceNumber earliest_seq) {
|
||||
@@ -1281,15 +1290,15 @@ Compaction* ColumnFamilyData::PickCompaction(
|
||||
}
|
||||
|
||||
bool ColumnFamilyData::RangeOverlapWithCompaction(
|
||||
const Slice& smallest_user_key, const Slice& largest_user_key,
|
||||
int level) const {
|
||||
const Slice& smallest_user_key, const Slice& largest_user_key, int level,
|
||||
bool range_limit_exclusive) const {
|
||||
return compaction_picker_->RangeOverlapWithCompaction(
|
||||
smallest_user_key, largest_user_key, level);
|
||||
smallest_user_key, largest_user_key, level, range_limit_exclusive);
|
||||
}
|
||||
|
||||
Status ColumnFamilyData::RangesOverlapWithMemtables(
|
||||
const autovector<UserKeyRange>& ranges, SuperVersion* super_version,
|
||||
bool allow_data_in_errors, bool* overlap) {
|
||||
bool allow_data_in_errors, bool* overlap, bool range_limit_exclusive) {
|
||||
assert(overlap != nullptr);
|
||||
*overlap = false;
|
||||
// Create an InternalIterator over all unflushed memtables
|
||||
@@ -1334,12 +1343,15 @@ Status ColumnFamilyData::RangesOverlapWithMemtables(
|
||||
}
|
||||
|
||||
if (status.ok()) {
|
||||
const int limit_cmp = memtable_iter->Valid()
|
||||
? ucmp->CompareWithoutTimestamp(
|
||||
seek_result.user_key, ranges[i].limit)
|
||||
: 1;
|
||||
if (memtable_iter->Valid() &&
|
||||
ucmp->CompareWithoutTimestamp(seek_result.user_key,
|
||||
ranges[i].limit) <= 0) {
|
||||
(range_limit_exclusive ? limit_cmp < 0 : limit_cmp <= 0)) {
|
||||
*overlap = true;
|
||||
} else if (range_del_agg.IsRangeOverlapped(ranges[i].start,
|
||||
ranges[i].limit)) {
|
||||
} else if (range_del_agg.IsRangeOverlapped(
|
||||
ranges[i].start, ranges[i].limit, range_limit_exclusive)) {
|
||||
*overlap = true;
|
||||
}
|
||||
}
|
||||
@@ -1896,6 +1908,102 @@ size_t ColumnFamilySet::NumberOfColumnFamilies() const {
|
||||
return column_families_.size();
|
||||
}
|
||||
|
||||
void ColumnFamilySet::RefreshFlushableMemAccounting() {
|
||||
if (flush_initiator_ == nullptr || write_buffer_manager_ == nullptr ||
|
||||
!write_buffer_manager_->ShouldTrackFlushInitiator()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (bulk_flushable_mem_accounting_depth_ > 0) {
|
||||
bulk_flushable_mem_accounting_dirty_ = true;
|
||||
flush_initiator_->InvalidateLargestFlushableCFMem();
|
||||
return;
|
||||
}
|
||||
|
||||
// Keep candidate readers from consuming a mixture of the previous snapshot
|
||||
// and the values published by this rebuild.
|
||||
flush_initiator_->InvalidateLargestFlushableCFMem();
|
||||
constexpr int kMaxRefreshAttempts = 3;
|
||||
for (int attempt = 0; attempt < kMaxRefreshAttempts; ++attempt) {
|
||||
const uint64_t update_seq =
|
||||
flush_initiator_->GetFlushableMemUpdateSequence();
|
||||
bool has_mutable_mem = false;
|
||||
bool has_ineligible_cf = false;
|
||||
size_t largest = 0;
|
||||
size_t waiting_immutable_mem = 0;
|
||||
for (auto cfd : *this) {
|
||||
if (cfd->IsDropped() || !cfd->initialized()) {
|
||||
continue;
|
||||
}
|
||||
const bool mutable_not_empty = !cfd->mem()->IsEmpty();
|
||||
if (mutable_not_empty) {
|
||||
cfd->mem()->RefreshWBMTracking();
|
||||
}
|
||||
const bool has_mutable =
|
||||
mutable_not_empty && cfd->mem()->IsWBMTrackingActive();
|
||||
has_mutable_mem = has_mutable_mem || has_mutable;
|
||||
if (flush_initiator_->UsesTotalMutableMem()) {
|
||||
waiting_immutable_mem +=
|
||||
cfd->imm()->WBMTrackedUnstartedMemTablesMemoryUsage();
|
||||
continue;
|
||||
}
|
||||
if (cfd->imm()->IsFlushPendingOrRunning()) {
|
||||
has_ineligible_cf = true;
|
||||
continue;
|
||||
}
|
||||
const size_t mutable_mem =
|
||||
has_mutable ? cfd->mem()->WBMTrackedMemoryUsage() : 0;
|
||||
const size_t immutable_mem =
|
||||
cfd->imm()->WBMTrackedUnflushedMemTablesMemoryUsage();
|
||||
waiting_immutable_mem += immutable_mem;
|
||||
largest = std::max(largest, mutable_mem + immutable_mem);
|
||||
}
|
||||
if (flush_initiator_->UsesTotalMutableMem()) {
|
||||
flush_initiator_->SetHasIneligibleCF(false);
|
||||
flush_initiator_->SetHasFlushableCF(has_mutable_mem ||
|
||||
waiting_immutable_mem > 0);
|
||||
if (flush_initiator_->TrySetLargestFlushableCFMem(
|
||||
0, waiting_immutable_mem, update_seq)) {
|
||||
write_buffer_manager_->NotifyFlushInitiatorChanged();
|
||||
return;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
flush_initiator_->SetHasIneligibleCF(has_ineligible_cf);
|
||||
flush_initiator_->SetHasFlushableCF(largest > 0);
|
||||
if (flush_initiator_->TrySetLargestFlushableCFMem(
|
||||
largest, waiting_immutable_mem, update_seq)) {
|
||||
write_buffer_manager_->NotifyFlushInitiatorChanged();
|
||||
return;
|
||||
}
|
||||
}
|
||||
flush_initiator_->InvalidateLargestFlushableCFMem();
|
||||
}
|
||||
|
||||
void ColumnFamilySet::BeginBulkFlushableMemAccountingUpdate() {
|
||||
++bulk_flushable_mem_accounting_depth_;
|
||||
if (bulk_flushable_mem_accounting_depth_ == 1) {
|
||||
bulk_flushable_mem_accounting_dirty_ = true;
|
||||
if (flush_initiator_ != nullptr && write_buffer_manager_ != nullptr &&
|
||||
write_buffer_manager_->ShouldTrackFlushInitiator()) {
|
||||
flush_initiator_->InvalidateLargestFlushableCFMem();
|
||||
write_buffer_manager_->NotifyFlushInitiatorChanged();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ColumnFamilySet::EndBulkFlushableMemAccountingUpdate() {
|
||||
assert(bulk_flushable_mem_accounting_depth_ > 0);
|
||||
--bulk_flushable_mem_accounting_depth_;
|
||||
if (bulk_flushable_mem_accounting_depth_ == 0 &&
|
||||
bulk_flushable_mem_accounting_dirty_) {
|
||||
bulk_flushable_mem_accounting_dirty_ = false;
|
||||
TEST_SYNC_POINT(
|
||||
"ColumnFamilySet::EndBulkFlushableMemAccountingUpdate:Refresh");
|
||||
RefreshFlushableMemAccounting();
|
||||
}
|
||||
}
|
||||
|
||||
// under a DB mutex AND write thread
|
||||
ColumnFamilyData* ColumnFamilySet::CreateColumnFamily(
|
||||
const std::string& name, uint32_t id, Version* dummy_versions,
|
||||
@@ -1936,6 +2044,15 @@ void ColumnFamilySet::RemoveColumnFamily(ColumnFamilyData* cfd) {
|
||||
column_families_.erase(cfd->GetName());
|
||||
running_ts_sz_.erase(cf_id);
|
||||
ts_sz_for_record_.erase(cf_id);
|
||||
if (bulk_flushable_mem_accounting_depth_ > 0) {
|
||||
bulk_flushable_mem_accounting_dirty_ = true;
|
||||
if (flush_initiator_ != nullptr) {
|
||||
flush_initiator_->InvalidateLargestFlushableCFMem();
|
||||
}
|
||||
return;
|
||||
}
|
||||
TEST_SYNC_POINT("ColumnFamilySet::RemoveColumnFamily:Refresh");
|
||||
RefreshFlushableMemAccounting();
|
||||
}
|
||||
|
||||
// under a DB mutex OR from a write thread
|
||||
|
||||
+67
-5
@@ -29,6 +29,7 @@
|
||||
#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 {
|
||||
@@ -51,6 +52,7 @@ struct SuperVersionContext;
|
||||
class BlobFileCache;
|
||||
class BlobFilePartitionManager;
|
||||
class BlobSource;
|
||||
class FlushInitiator;
|
||||
|
||||
extern const double kIncSlowdownRatio;
|
||||
// This file contains a list of data structures for managing column family
|
||||
@@ -444,8 +446,8 @@ class ColumnFamilyData {
|
||||
// Check if the passed range overlap with any running compactions.
|
||||
// REQUIRES: DB mutex held
|
||||
bool RangeOverlapWithCompaction(const Slice& smallest_user_key,
|
||||
const Slice& largest_user_key,
|
||||
int level) const;
|
||||
const Slice& largest_user_key, int level,
|
||||
bool range_limit_exclusive) const;
|
||||
|
||||
// Check if the passed ranges overlap with any unflushed memtables
|
||||
// (immutable or mutable).
|
||||
@@ -456,7 +458,8 @@ class ColumnFamilyData {
|
||||
// Thread-safe
|
||||
Status RangesOverlapWithMemtables(const autovector<UserKeyRange>& ranges,
|
||||
SuperVersion* super_version,
|
||||
bool allow_data_in_errors, bool* overlap);
|
||||
bool allow_data_in_errors, bool* overlap,
|
||||
bool range_limit_exclusive);
|
||||
|
||||
// A flag to tell a manual compaction is to compact all levels together
|
||||
// instead of a specific level.
|
||||
@@ -520,6 +523,32 @@ 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,
|
||||
@@ -711,10 +740,26 @@ class ColumnFamilyData {
|
||||
// If true --> this ColumnFamily is currently present in DBImpl::flush_queue_
|
||||
bool queued_for_flush_;
|
||||
|
||||
// If true --> this ColumnFamily is currently present in
|
||||
// DBImpl::compaction_queue_
|
||||
// If true, this ColumnFamily is in DBImpl::compaction_queue_ or its parked
|
||||
// compaction set.
|
||||
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
|
||||
@@ -827,6 +872,19 @@ class ColumnFamilySet {
|
||||
|
||||
WriteBufferManager* write_buffer_manager() { return write_buffer_manager_; }
|
||||
|
||||
void SetFlushInitiator(FlushInitiator* flush_initiator) {
|
||||
flush_initiator_ = flush_initiator;
|
||||
}
|
||||
|
||||
FlushInitiator* flush_initiator() const { return flush_initiator_; }
|
||||
|
||||
void RefreshFlushableMemAccounting();
|
||||
|
||||
// Coalesces accounting rebuilds while a caller removes multiple column
|
||||
// families. Both methods require the DB mutex.
|
||||
void BeginBulkFlushableMemAccountingUpdate();
|
||||
void EndBulkFlushableMemAccountingUpdate();
|
||||
|
||||
WriteController* write_controller() { return write_controller_; }
|
||||
|
||||
private:
|
||||
@@ -854,6 +912,9 @@ class ColumnFamilySet {
|
||||
// column families with non-zero user-defined timestamp size.
|
||||
UnorderedMap<uint32_t, size_t> ts_sz_for_record_;
|
||||
|
||||
int bulk_flushable_mem_accounting_depth_ = 0;
|
||||
bool bulk_flushable_mem_accounting_dirty_ = false;
|
||||
|
||||
uint32_t max_column_family_;
|
||||
const FileOptions file_options_;
|
||||
|
||||
@@ -868,6 +929,7 @@ class ColumnFamilySet {
|
||||
const ImmutableDBOptions* const db_options_;
|
||||
Cache* table_cache_;
|
||||
WriteBufferManager* write_buffer_manager_;
|
||||
FlushInitiator* flush_initiator_ = nullptr;
|
||||
WriteController* write_controller_;
|
||||
BlockCacheTracer* const block_cache_tracer_;
|
||||
std::shared_ptr<IOTracer> io_tracer_;
|
||||
|
||||
@@ -774,6 +774,8 @@ TEST_P(ColumnFamilyTest, BulkAddDrop) {
|
||||
constexpr int kNumCF = 1000;
|
||||
ColumnFamilyOptions cf_options;
|
||||
WriteOptions write_options;
|
||||
db_options_.write_buffer_manager = std::make_shared<WriteBufferManager>(
|
||||
1 << 30, nullptr, false, WriteBufferFlushPolicy::kFlushLargestAcrossDBs);
|
||||
Open();
|
||||
std::vector<std::string> cf_names;
|
||||
std::vector<ColumnFamilyHandle*> cf_handles;
|
||||
@@ -784,7 +786,22 @@ TEST_P(ColumnFamilyTest, BulkAddDrop) {
|
||||
for (int i = 1; i <= kNumCF; i++) {
|
||||
ASSERT_OK(db_->Put(write_options, cf_handles[i - 1], "foo", "bar"));
|
||||
}
|
||||
std::atomic<int> per_removal_refreshes{0};
|
||||
std::atomic<int> bulk_refreshes{0};
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
|
||||
"ColumnFamilySet::RemoveColumnFamily:Refresh",
|
||||
[&](void*) { ++per_removal_refreshes; });
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
|
||||
"ColumnFamilySet::EndBulkFlushableMemAccountingUpdate:Refresh",
|
||||
[&](void*) { ++bulk_refreshes; });
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
|
||||
Defer cleanup_sync_points([] {
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearAllCallBacks();
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
|
||||
});
|
||||
ASSERT_OK(db_->DropColumnFamilies(cf_handles));
|
||||
EXPECT_EQ(0, per_removal_refreshes.load());
|
||||
EXPECT_EQ(1, bulk_refreshes.load());
|
||||
std::vector<ColumnFamilyDescriptor> cf_descriptors;
|
||||
for (auto* handle : cf_handles) {
|
||||
delete handle;
|
||||
@@ -798,7 +815,10 @@ TEST_P(ColumnFamilyTest, BulkAddDrop) {
|
||||
for (int i = 1; i <= kNumCF; i++) {
|
||||
ASSERT_OK(db_->Put(write_options, cf_handles[i - 1], "foo", "bar"));
|
||||
}
|
||||
bulk_refreshes.store(0);
|
||||
ASSERT_OK(db_->DropColumnFamilies(cf_handles));
|
||||
EXPECT_EQ(0, per_removal_refreshes.load());
|
||||
EXPECT_EQ(1, bulk_refreshes.load());
|
||||
for (auto* handle : cf_handles) {
|
||||
delete handle;
|
||||
}
|
||||
@@ -3167,6 +3187,32 @@ TEST_P(ColumnFamilyTest, CreateDropAndDestroy) {
|
||||
ASSERT_OK(db_->DestroyColumnFamilyHandle(cfh));
|
||||
}
|
||||
|
||||
TEST_P(ColumnFamilyTest, DropWaitsForUnorderedMemtableWrite) {
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->LoadDependency(
|
||||
{{"DBImpl::WriteImpl:UnorderedWriteAfterWriteWAL",
|
||||
"ColumnFamilyTest::DropWaitsForUnorderedMemtableWrite:AfterWAL"},
|
||||
{"DBImpl::WaitForPendingWrites:BeforeBlock",
|
||||
"DBImpl::WriteImpl:BeforeUnorderedWriteMemtable"}});
|
||||
|
||||
db_options_.unordered_write = true;
|
||||
Open();
|
||||
ColumnFamilyHandle* cfh;
|
||||
ASSERT_OK(db_->CreateColumnFamily(ColumnFamilyOptions(), "yoyo", &cfh));
|
||||
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
|
||||
port::Thread writer(
|
||||
[&] { ASSERT_OK(db_->Put(WriteOptions(), cfh, "foo", "bar")); });
|
||||
|
||||
TEST_SYNC_POINT(
|
||||
"ColumnFamilyTest::DropWaitsForUnorderedMemtableWrite:AfterWAL");
|
||||
ASSERT_OK(db_->DropColumnFamily(cfh));
|
||||
writer.join();
|
||||
ASSERT_OK(db_->DestroyColumnFamilyHandle(cfh));
|
||||
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearAllCallBacks();
|
||||
}
|
||||
|
||||
TEST_P(ColumnFamilyTest, CreateDropAndDestroyWithoutFileDeletion) {
|
||||
ColumnFamilyHandle* cfh;
|
||||
Open();
|
||||
|
||||
+12
-10
@@ -491,7 +491,8 @@ int Compaction::GetProximalLevel() const { return proximal_level_; }
|
||||
// smallest_key and largest_key include timestamps if user-defined timestamp is
|
||||
// enabled.
|
||||
bool Compaction::OverlapProximalLevelOutputRange(
|
||||
const Slice& smallest_key, const Slice& largest_key) const {
|
||||
const Slice& smallest_key, const Slice& largest_key,
|
||||
bool range_limit_exclusive) const {
|
||||
if (!SupportsPerKeyPlacement()) {
|
||||
return false;
|
||||
}
|
||||
@@ -506,10 +507,11 @@ bool Compaction::OverlapProximalLevelOutputRange(
|
||||
const Comparator* ucmp =
|
||||
input_vstorage_->InternalComparator()->user_comparator();
|
||||
|
||||
const int largest_cmp = ucmp->CompareWithoutTimestamp(
|
||||
largest_key, proximal_level_smallest_.user_key());
|
||||
return ucmp->CompareWithoutTimestamp(
|
||||
smallest_key, proximal_level_largest_.user_key()) <= 0 &&
|
||||
ucmp->CompareWithoutTimestamp(
|
||||
largest_key, proximal_level_smallest_.user_key()) >= 0;
|
||||
(range_limit_exclusive ? largest_cmp > 0 : largest_cmp >= 0);
|
||||
}
|
||||
|
||||
// key includes timestamp if user-defined timestamp is enabled.
|
||||
@@ -984,9 +986,9 @@ uint64_t Compaction::MaxInputFileNewestKeyTime(const InternalKey* start,
|
||||
return newest_key_time;
|
||||
}
|
||||
|
||||
uint64_t Compaction::MinInputFileOldestAncesterTime(
|
||||
uint64_t Compaction::MinInputFileOldestAncestorTime(
|
||||
const InternalKey* start, const InternalKey* end) const {
|
||||
uint64_t min_oldest_ancester_time = std::numeric_limits<uint64_t>::max();
|
||||
uint64_t min_oldest_ancestor_time = std::numeric_limits<uint64_t>::max();
|
||||
const InternalKeyComparator& icmp =
|
||||
column_family_data()->internal_comparator();
|
||||
for (const auto& level_files : inputs_) {
|
||||
@@ -997,14 +999,14 @@ uint64_t Compaction::MinInputFileOldestAncesterTime(
|
||||
if (end != nullptr && icmp.Compare(file->smallest, *end) > 0) {
|
||||
continue;
|
||||
}
|
||||
uint64_t oldest_ancester_time = file->TryGetOldestAncesterTime();
|
||||
if (oldest_ancester_time != 0) {
|
||||
min_oldest_ancester_time =
|
||||
std::min(min_oldest_ancester_time, oldest_ancester_time);
|
||||
uint64_t oldest_ancestor_time = file->TryGetOldestAncestorTime();
|
||||
if (oldest_ancestor_time != 0) {
|
||||
min_oldest_ancestor_time =
|
||||
std::min(min_oldest_ancestor_time, oldest_ancestor_time);
|
||||
}
|
||||
}
|
||||
}
|
||||
return min_oldest_ancester_time;
|
||||
return min_oldest_ancestor_time;
|
||||
}
|
||||
|
||||
uint64_t Compaction::MinInputFileEpochNumber() const {
|
||||
|
||||
@@ -397,7 +397,8 @@ class Compaction {
|
||||
// Both smallest_key and largest_key include timestamps if user-defined
|
||||
// timestamp is enabled.
|
||||
bool OverlapProximalLevelOutputRange(const Slice& smallest_key,
|
||||
const Slice& largest_key) const;
|
||||
const Slice& largest_key,
|
||||
bool range_limit_exclusive) const;
|
||||
|
||||
// For testing purposes, check that a key is within proximal level
|
||||
// output range for per_key_placement feature, which is safe to place the key
|
||||
@@ -437,8 +438,8 @@ class Compaction {
|
||||
const InternalKey* end) const;
|
||||
|
||||
// start and end are sub compact range. Null if no boundary.
|
||||
// This is used to filter out some input files' ancester's time range.
|
||||
uint64_t MinInputFileOldestAncesterTime(const InternalKey* start,
|
||||
// This is used to filter out some input files' ancestor's time range.
|
||||
uint64_t MinInputFileOldestAncestorTime(const InternalKey* start,
|
||||
const InternalKey* end) const;
|
||||
// Return the minimum epoch number among
|
||||
// input files' associated with this compaction
|
||||
|
||||
@@ -1909,8 +1909,7 @@ void CompactionIterator::PrepareOutput() {
|
||||
// KeyNotExistsBeyondOutputLevel() return true?
|
||||
if (Valid() && bottommost_level_ &&
|
||||
DefinitelyInSnapshot(ikey_.sequence, earliest_snapshot_) &&
|
||||
ikey_.type != kTypeMerge && current_key_committed_ &&
|
||||
ikey_.sequence <= preserve_seqno_after_ && !is_range_del_) {
|
||||
ikey_.type != kTypeMerge && current_key_committed_ && !is_range_del_) {
|
||||
assert(compaction_ != nullptr && !compaction_->allow_ingest_behind());
|
||||
if (ikey_.type == kTypeDeletion ||
|
||||
(ikey_.type == kTypeSingleDeletion && timestamp_size_ == 0)) {
|
||||
@@ -1932,19 +1931,29 @@ void CompactionIterator::PrepareOutput() {
|
||||
}
|
||||
|
||||
bool zeroed_seqno = false;
|
||||
if (!timestamp_size_) {
|
||||
current_key_.UpdateInternalKey(0, ikey_.type);
|
||||
zeroed_seqno = true;
|
||||
} else if (full_history_ts_low_ && cmp_with_history_ts_low_ < 0) {
|
||||
// For UDT, the seqno and timestamp could only be zeroed out after the
|
||||
// key is below history_ts_low_.
|
||||
// For the same user key (excluding timestamp), the timestamp-based
|
||||
// history can be collapsed to save some space if the timestamp is
|
||||
// older than *full_history_ts_low_.
|
||||
const std::string kTsMin(timestamp_size_, static_cast<char>(0));
|
||||
const Slice ts_slice = kTsMin;
|
||||
ikey_.SetTimestamp(ts_slice);
|
||||
current_key_.UpdateInternalKey(0, ikey_.type, &ts_slice);
|
||||
// Whether the sequence number can actually be zeroed out here is decided
|
||||
// by the shared BottommostSeqnoCanBeZeroed() predicate, which the
|
||||
// bottommost-file marking logic
|
||||
// (VersionStorageInfo::ComputeBottommostFilesMarkedForCompaction) also
|
||||
// consults. Keeping both on one predicate ensures a file is only marked
|
||||
// for a compaction that can make progress; otherwise the file would be
|
||||
// re-marked forever (infinite compaction loop).
|
||||
if (BottommostSeqnoCanBeZeroed(
|
||||
ikey_.sequence, preserve_seqno_after_, timestamp_size_,
|
||||
full_history_ts_low_ != nullptr, cmp_with_history_ts_low_ < 0)) {
|
||||
if (!timestamp_size_) {
|
||||
current_key_.UpdateInternalKey(0, ikey_.type);
|
||||
} else {
|
||||
// For UDT, the seqno and timestamp could only be zeroed out after the
|
||||
// key is below history_ts_low_.
|
||||
// For the same user key (excluding timestamp), the timestamp-based
|
||||
// history can be collapsed to save some space if the timestamp is
|
||||
// older than *full_history_ts_low_.
|
||||
const std::string kTsMin(timestamp_size_, static_cast<char>(0));
|
||||
const Slice ts_slice = kTsMin;
|
||||
ikey_.SetTimestamp(ts_slice);
|
||||
current_key_.UpdateInternalKey(0, ikey_.type, &ts_slice);
|
||||
}
|
||||
zeroed_seqno = true;
|
||||
}
|
||||
|
||||
|
||||
@@ -152,7 +152,8 @@ 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)
|
||||
int* bg_compaction_scheduled, int* bg_bottom_compaction_scheduled,
|
||||
std::atomic<int>* num_running_remote_compactions)
|
||||
: compact_(new CompactionState(compaction)),
|
||||
internal_stats_(compaction->compaction_reason(), 1),
|
||||
db_options_(db_options),
|
||||
@@ -198,7 +199,8 @@ 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) {
|
||||
bg_bottom_compaction_scheduled_(bg_bottom_compaction_scheduled),
|
||||
num_running_remote_compactions_(num_running_remote_compactions) {
|
||||
assert(job_stats_ != nullptr);
|
||||
assert(log_buffer_ != nullptr);
|
||||
assert(job_context);
|
||||
@@ -393,6 +395,24 @@ void CompactionJob::Prepare(
|
||||
std::min(preclude_last_level_min_seqno, preserve_time_min_seqno);
|
||||
#endif
|
||||
|
||||
// For a bottommost-file compaction, which exists only because the marker
|
||||
// (VersionStorageInfo::ComputeBottommostFilesMarkedForCompaction) decided the
|
||||
// file's largest sequence number could be zeroed, honor that same
|
||||
// version-carried preserve boundary here. The marker reads DBImpl's live,
|
||||
// DB-wide seqno->time mapping, whereas the value computed above is derived
|
||||
// only from the selected file's persisted mapping, which can be sparse or
|
||||
// empty (e.g. a file written before preserve/preclude was enabled). Taking
|
||||
// the max ensures this compaction can zero at least the sequence numbers the
|
||||
// marker considered zeroable, so a marked file makes progress instead of
|
||||
// being re-marked forever (infinite compaction loop). Other compaction
|
||||
// reasons keep the per-input-file boundary so their seqno-zeroing behavior is
|
||||
// unchanged. When preserve/preclude is inactive the version value is
|
||||
// kMaxSequenceNumber, making this a no-op.
|
||||
if (c->compaction_reason() == CompactionReason::kBottommostFiles) {
|
||||
preserve_time_min_seqno = std::max(preserve_time_min_seqno,
|
||||
storage_info->GetPreserveTimeMinSeqno());
|
||||
}
|
||||
|
||||
// Preserve sequence numbers for preserved write times and snapshots, though
|
||||
// the specific sequence number of the earliest snapshot can be zeroed.
|
||||
preserve_seqno_after_ =
|
||||
@@ -421,6 +441,17 @@ void CompactionJob::Prepare(
|
||||
c->GetKeepInLastLevelThroughSeqno());
|
||||
|
||||
options_file_number_ = versions_->options_file_number();
|
||||
|
||||
// For remote compaction hardening: capture the current MANIFEST position as a
|
||||
// floor for the worker's recovery. manifest_file_size() is a physical byte
|
||||
// offset that VersionSet::ProcessManifestWrites records under the DB mutex
|
||||
// only after the whole version-edit batch is written and sync'd, so it is a
|
||||
// durable, complete-batch offset -- never mid-record or mid-atomic-group --
|
||||
// at or past the compaction's (already committed) input version.
|
||||
if (mutable_db_options_copy_.remote_compaction_manifest_floor) {
|
||||
min_manifest_file_number_ = versions_->manifest_file_number();
|
||||
min_manifest_file_size_ = versions_->manifest_file_size();
|
||||
}
|
||||
}
|
||||
|
||||
void CompactionJob::MaybeAssignCompactionProgressAndWriter(
|
||||
@@ -1668,8 +1699,12 @@ 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
|
||||
if (compaction_aborted_.load(std::memory_order_acquire) > 0) {
|
||||
// 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) {
|
||||
return Status::Incomplete(Status::SubCode::kCompactionAborted);
|
||||
}
|
||||
|
||||
@@ -1691,7 +1726,8 @@ 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) {
|
||||
if (compaction_aborted_.load(std::memory_order_acquire) > 0 ||
|
||||
cfd->compaction_aborted() > 0) {
|
||||
status = Status::Incomplete(Status::SubCode::kCompactionAborted);
|
||||
break;
|
||||
}
|
||||
@@ -2124,20 +2160,20 @@ Status CompactionJob::FinishCompactionOutputFile(
|
||||
|
||||
if (s.ok()) {
|
||||
// With accurate smallest and largest key, we can get a slightly more
|
||||
// accurate oldest ancester time.
|
||||
// This makes oldest ancester time in manifest more accurate than in
|
||||
// accurate oldest ancestor time.
|
||||
// This makes oldest ancestor time in manifest more accurate than in
|
||||
// table properties. Not sure how to resolve it.
|
||||
if (meta->smallest.size() > 0 && meta->largest.size() > 0) {
|
||||
uint64_t refined_oldest_ancester_time;
|
||||
uint64_t refined_oldest_ancestor_time;
|
||||
Slice new_smallest = meta->smallest.user_key();
|
||||
Slice new_largest = meta->largest.user_key();
|
||||
if (!new_largest.empty() && !new_smallest.empty()) {
|
||||
refined_oldest_ancester_time =
|
||||
sub_compact->compaction->MinInputFileOldestAncesterTime(
|
||||
refined_oldest_ancestor_time =
|
||||
sub_compact->compaction->MinInputFileOldestAncestorTime(
|
||||
&(meta->smallest), &(meta->largest));
|
||||
if (refined_oldest_ancester_time !=
|
||||
if (refined_oldest_ancestor_time !=
|
||||
std::numeric_limits<uint64_t>::max()) {
|
||||
meta->oldest_ancester_time = refined_oldest_ancester_time;
|
||||
meta->oldest_ancestor_time = refined_oldest_ancestor_time;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2519,7 +2555,7 @@ Status CompactionJob::OpenCompactionOutputFile(SubcompactionState* sub_compact,
|
||||
return s;
|
||||
}
|
||||
|
||||
// Try to figure out the output file's oldest ancester time.
|
||||
// Try to figure out the output file's oldest ancestor time.
|
||||
int64_t temp_current_time = 0;
|
||||
auto get_time_status = db_options_.clock->GetCurrentTime(&temp_current_time);
|
||||
// Safe to proceed even if GetCurrentTime fails. So, log and proceed.
|
||||
@@ -2536,14 +2572,14 @@ Status CompactionJob::OpenCompactionOutputFile(SubcompactionState* sub_compact,
|
||||
if (sub_compact->end.has_value()) {
|
||||
tmp_end.SetMinPossibleForUserKey(*(sub_compact->end));
|
||||
}
|
||||
uint64_t oldest_ancester_time =
|
||||
sub_compact->compaction->MinInputFileOldestAncesterTime(
|
||||
uint64_t oldest_ancestor_time =
|
||||
sub_compact->compaction->MinInputFileOldestAncestorTime(
|
||||
sub_compact->start.has_value() ? &tmp_start : nullptr,
|
||||
sub_compact->end.has_value() ? &tmp_end : nullptr);
|
||||
if (oldest_ancester_time == std::numeric_limits<uint64_t>::max()) {
|
||||
if (oldest_ancestor_time == std::numeric_limits<uint64_t>::max()) {
|
||||
// TODO: fix DBSSTTest.GetTotalSstFilesSize and use
|
||||
// kUnknownOldestAncesterTime
|
||||
oldest_ancester_time = current_time;
|
||||
// kUnknownOldestAncestorTime
|
||||
oldest_ancestor_time = current_time;
|
||||
}
|
||||
|
||||
uint64_t newest_key_time = sub_compact->compaction->MaxInputFileNewestKeyTime(
|
||||
@@ -2556,7 +2592,7 @@ Status CompactionJob::OpenCompactionOutputFile(SubcompactionState* sub_compact,
|
||||
FileMetaData meta;
|
||||
meta.fd = FileDescriptor(file_number,
|
||||
sub_compact->compaction->output_path_id(), 0);
|
||||
meta.oldest_ancester_time = oldest_ancester_time;
|
||||
meta.oldest_ancestor_time = oldest_ancestor_time;
|
||||
meta.file_creation_time = current_time;
|
||||
meta.epoch_number = epoch_number;
|
||||
meta.temperature = temperature;
|
||||
@@ -2598,7 +2634,8 @@ Status CompactionJob::OpenCompactionOutputFile(SubcompactionState* sub_compact,
|
||||
std::move(writable_file), fname, fo_copy, db_options_.clock, io_tracer_,
|
||||
db_options_.stats, Histograms::SST_WRITE_MICROS, listeners,
|
||||
db_options_.file_checksum_gen_factory.get(),
|
||||
tmp_set.Contains(FileType::kTableFile), false));
|
||||
tmp_set.Contains(FileType::kTableFile),
|
||||
tmp_set.Contains(FileType::kTableFile)));
|
||||
|
||||
// TODO(hx235): pass in the correct `oldest_key_time` instead of `0`
|
||||
const ReadOptions read_options(Env::IOActivity::kCompaction);
|
||||
@@ -2613,7 +2650,8 @@ 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*/);
|
||||
proximal_after_seqno_ /*last_level_inclusive_max_seqno_threshold*/,
|
||||
dbname_ /*db_name*/, IsRemoteCompaction() /*is_remote_compaction*/);
|
||||
|
||||
outputs.NewBuilder(tboptions);
|
||||
|
||||
@@ -3230,7 +3268,8 @@ Status CompactionJob::PersistSubcompactionProgress(
|
||||
s = WritableFileWriter::PrepareIOOptions(write_options, opts);
|
||||
}
|
||||
if (s.ok()) {
|
||||
s = compaction_progress_writer_->file()->Sync(opts, db_options_.use_fsync);
|
||||
s = db_options_.use_fsync ? compaction_progress_writer_->file()->Fsync(opts)
|
||||
: compaction_progress_writer_->file()->Sync(opts);
|
||||
}
|
||||
|
||||
if (!s.ok()) {
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
#include "rocksdb/db.h"
|
||||
#include "rocksdb/env.h"
|
||||
#include "rocksdb/memtablerep.h"
|
||||
#include "rocksdb/transaction_log.h"
|
||||
#include "rocksdb/wal_iterator.h"
|
||||
#include "util/autovector.h"
|
||||
#include "util/stop_watch.h"
|
||||
#include "util/thread_local.h"
|
||||
@@ -166,7 +166,8 @@ 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);
|
||||
int* bg_bottom_compaction_scheduled = nullptr,
|
||||
std::atomic<int>* num_running_remote_compactions = nullptr);
|
||||
|
||||
virtual ~CompactionJob();
|
||||
|
||||
@@ -500,8 +501,14 @@ 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.
|
||||
// it also collects the smallest_seqno -> oldest_ancestor_time from the SST.
|
||||
SeqnoToTimeMapping seqno_to_time_mapping_;
|
||||
|
||||
// Max seqno that can be zeroed out in last level, including for preserving
|
||||
@@ -517,12 +524,23 @@ class CompactionJob {
|
||||
// Setting this requires DBMutex.
|
||||
uint64_t options_file_number_ = 0;
|
||||
|
||||
// MANIFEST position (file number and size, in bytes) captured in Prepare()
|
||||
// (mutex held) to send to the remote worker as a floor. Zero when
|
||||
// DBOptions::remote_compaction_manifest_floor is off (or this is not a remote
|
||||
// compaction), meaning no floor is sent. Setting these requires DBMutex.
|
||||
uint64_t min_manifest_file_number_ = 0;
|
||||
uint64_t min_manifest_file_size_ = 0;
|
||||
|
||||
// Writer for persisting compaction progress during compaction
|
||||
log::Writer* compaction_progress_writer_ = nullptr;
|
||||
|
||||
// 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.
|
||||
@@ -573,6 +591,7 @@ class CompactionJob {
|
||||
struct CompactionServiceInput {
|
||||
std::string cf_name;
|
||||
|
||||
// Snapshot sequence numbers in strictly increasing order.
|
||||
std::vector<SequenceNumber> snapshots;
|
||||
|
||||
// SST files for compaction, it should already be expended to include all the
|
||||
@@ -592,6 +611,18 @@ struct CompactionServiceInput {
|
||||
|
||||
uint64_t options_file_number = 0;
|
||||
|
||||
// MANIFEST position (file number and size, in bytes) the primary scheduled
|
||||
// this compaction from, used as a floor by the remote worker: it refuses to
|
||||
// reconstruct the compaction against an older MANIFEST view (an older file
|
||||
// number, or the same file number read to a smaller size) and falls back to
|
||||
// local compaction. A non-zero min_manifest_file_number also signals the
|
||||
// worker to use "trust the MANIFEST" recovery. Zero means the primary did not
|
||||
// provide a floor (kill switch off, or an older primary); the worker then
|
||||
// uses the original recovery with no floor check.
|
||||
// See DBOptions::remote_compaction_manifest_floor.
|
||||
uint64_t min_manifest_file_number = 0;
|
||||
uint64_t min_manifest_file_size = 0;
|
||||
|
||||
// serialization interface to read and write the object
|
||||
static Status Read(const std::string& data_str, CompactionServiceInput* obj);
|
||||
Status Write(std::string* output);
|
||||
@@ -610,7 +641,7 @@ struct CompactionServiceOutputFile {
|
||||
SequenceNumber largest_seqno{};
|
||||
std::string smallest_internal_key;
|
||||
std::string largest_internal_key;
|
||||
uint64_t oldest_ancester_time = kUnknownOldestAncesterTime;
|
||||
uint64_t oldest_ancestor_time = kUnknownOldestAncestorTime;
|
||||
uint64_t file_creation_time = kUnknownFileCreationTime;
|
||||
uint64_t epoch_number = kUnknownEpochNumber;
|
||||
std::string file_checksum = kUnknownFileChecksum;
|
||||
@@ -626,7 +657,7 @@ struct CompactionServiceOutputFile {
|
||||
CompactionServiceOutputFile(
|
||||
const std::string& name, uint64_t size, SequenceNumber smallest,
|
||||
SequenceNumber largest, std::string _smallest_internal_key,
|
||||
std::string _largest_internal_key, uint64_t _oldest_ancester_time,
|
||||
std::string _largest_internal_key, uint64_t _oldest_ancestor_time,
|
||||
uint64_t _file_creation_time, uint64_t _epoch_number,
|
||||
const std::string& _file_checksum,
|
||||
const std::string& _file_checksum_func_name, uint64_t _paranoid_hash,
|
||||
@@ -639,7 +670,7 @@ struct CompactionServiceOutputFile {
|
||||
largest_seqno(largest),
|
||||
smallest_internal_key(std::move(_smallest_internal_key)),
|
||||
largest_internal_key(std::move(_largest_internal_key)),
|
||||
oldest_ancester_time(_oldest_ancester_time),
|
||||
oldest_ancestor_time(_oldest_ancestor_time),
|
||||
file_creation_time(_file_creation_time),
|
||||
epoch_number(_epoch_number),
|
||||
file_checksum(_file_checksum),
|
||||
@@ -730,6 +761,7 @@ 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_;
|
||||
|
||||
|
||||
@@ -387,7 +387,7 @@ class CompactionJobTestBase : public testing::Test {
|
||||
edit.AddFile(
|
||||
level, file_number, 0, file_size, smallest_key, largest_key,
|
||||
smallest_seqno, largest_seqno, false, Temperature::kUnknown,
|
||||
oldest_blob_file_number, kUnknownOldestAncesterTime,
|
||||
oldest_blob_file_number, kUnknownOldestAncestorTime,
|
||||
kUnknownFileCreationTime,
|
||||
versions_->GetColumnFamilySet()->GetDefault()->NewEpochNumber(),
|
||||
kUnknownFileChecksum, kUnknownFileChecksumFuncName, kNullUniqueId64x2,
|
||||
@@ -1572,6 +1572,10 @@ TEST_F(CompactionJobTest, InputSerialization) {
|
||||
while (!rnd.OneIn(10)) {
|
||||
input.snapshots.emplace_back(rnd64.Uniform(UINT64_MAX));
|
||||
}
|
||||
std::sort(input.snapshots.begin(), input.snapshots.end());
|
||||
input.snapshots.erase(
|
||||
std::unique(input.snapshots.begin(), input.snapshots.end()),
|
||||
input.snapshots.end());
|
||||
while (!rnd.OneIn(10)) {
|
||||
input.input_files.emplace_back(rnd.RandomString(
|
||||
rnd.Uniform(kStrMaxLen - 1) +
|
||||
@@ -1641,6 +1645,25 @@ TEST_F(CompactionJobTest, InputSerialization) {
|
||||
ASSERT_TRUE(s.IsNotSupported());
|
||||
}
|
||||
|
||||
TEST_F(CompactionJobTest, OpenAndCompactRejectsUnorderedSnapshots) {
|
||||
for (const std::vector<SequenceNumber>& snapshots :
|
||||
{std::vector<SequenceNumber>{2, 1}, std::vector<SequenceNumber>{1, 1}}) {
|
||||
CompactionServiceInput input;
|
||||
input.snapshots = snapshots;
|
||||
|
||||
std::string serialized_input;
|
||||
ASSERT_OK(input.Write(&serialized_input));
|
||||
|
||||
std::string serialized_result;
|
||||
Status s =
|
||||
DB::OpenAndCompact("", "output", serialized_input, &serialized_result,
|
||||
CompactionServiceOptionsOverride());
|
||||
ASSERT_TRUE(s.IsInvalidArgument());
|
||||
ASSERT_NE(s.ToString().find("snapshots must be strictly increasing"),
|
||||
std::string::npos);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(CompactionJobTest, ResultSerialization) {
|
||||
// Setup a random CompactionServiceResult
|
||||
CompactionServiceResult result;
|
||||
@@ -1679,7 +1702,7 @@ TEST_F(CompactionJobTest, ResultSerialization) {
|
||||
rnd.Uniform(kStrMaxLen)) /* smallest_internal_key */,
|
||||
rnd.RandomBinaryString(
|
||||
rnd.Uniform(kStrMaxLen)) /* largest_internal_key */,
|
||||
rnd64.Uniform(UINT64_MAX) /* oldest_ancester_time */,
|
||||
rnd64.Uniform(UINT64_MAX) /* oldest_ancestor_time */,
|
||||
rnd64.Uniform(UINT64_MAX) /* file_creation_time */,
|
||||
rnd64.Uniform(UINT64_MAX) /* epoch_number */,
|
||||
file_checksum /* file_checksum */,
|
||||
|
||||
@@ -32,7 +32,7 @@ Status CompactionOutputs::Finish(
|
||||
meta->fd.largest_seqno);
|
||||
relevant_mapping.SetCapacity(kMaxSeqnoTimePairsPerSST);
|
||||
builder_->SetSeqnoTimeTableProperties(relevant_mapping,
|
||||
meta->oldest_ancester_time);
|
||||
meta->oldest_ancestor_time);
|
||||
s = builder_->Finish();
|
||||
|
||||
} else {
|
||||
@@ -73,7 +73,7 @@ IOStatus CompactionOutputs::WriterSyncClose(const Status& input_status,
|
||||
WriteOptions(Env::IOActivity::kCompaction), opts);
|
||||
if (input_status.ok() && io_s.ok()) {
|
||||
StopWatch sw(clock, statistics, COMPACTION_OUTFILE_SYNC_MICROS);
|
||||
io_s = file_writer_->Sync(opts, use_fsync);
|
||||
io_s = use_fsync ? file_writer_->Fsync(opts) : file_writer_->Sync(opts);
|
||||
}
|
||||
if (input_status.ok() && io_s.ok()) {
|
||||
io_s = file_writer_->Close(opts);
|
||||
@@ -267,11 +267,22 @@ bool CompactionOutputs::ShouldStopBefore(const CompactionIterator& c_iter) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If there's user defined partitioner, check that first
|
||||
if (partitioner_ && partitioner_->ShouldPartition(PartitionerRequest(
|
||||
last_key_for_partitioner_, c_iter.user_key(),
|
||||
current_output_file_size_)) == kRequired) {
|
||||
return true;
|
||||
if (partitioner_) {
|
||||
if (partitioner_prefix_valid_) {
|
||||
// Fast path: no per-key copy or virtual call. A partition is requested at
|
||||
// the first key that no longer shares the established prefix. An empty
|
||||
// prefix means no further partitions (every key "starts with" it).
|
||||
if (UNLIKELY(!c_iter.user_key().starts_with(partitioner_prefix_))) {
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
// Slow path: per-key callback (and copy elsewhere)
|
||||
if (UNLIKELY(partitioner_->ShouldPartition(PartitionerRequest(
|
||||
last_key_for_partitioner_, c_iter.user_key(),
|
||||
current_output_file_size_)) == kRequired)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// files output to Level 0 won't be split
|
||||
@@ -401,11 +412,27 @@ Status CompactionOutputs::AddToOutput(
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
// A new output file starts a fresh partition-tracking window. Establish the
|
||||
// partitioner fast path from this file's first key: if the partitioner can
|
||||
// express its next boundary as "first key not sharing this prefix", cache
|
||||
// that prefix; otherwise fall back to per-key ShouldPartition(). This is
|
||||
// the only place the prefix needs to be (re)derived, since a partition
|
||||
// boundary always forces a file cut, and re-deriving on non-partition cuts
|
||||
// just recomputes the same still-valid prefix.
|
||||
if (partitioner_) {
|
||||
OptSlice prefix =
|
||||
partitioner_->ShouldPartitionByPrefix(c_iter.user_key());
|
||||
partitioner_prefix_valid_ = prefix.has_value();
|
||||
if (partitioner_prefix_valid_) {
|
||||
partitioner_prefix_.assign(prefix->data(), prefix->size());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// c_iter may emit range deletion keys, so update `last_key_for_partitioner_`
|
||||
// here before returning below when `is_range_del` is true
|
||||
if (partitioner_) {
|
||||
// here before returning below when `is_range_del` is true. Only needed in the
|
||||
// fallback mode; the prefix fast path does not use it.
|
||||
if (partitioner_ && !partitioner_prefix_valid_) {
|
||||
last_key_for_partitioner_.assign(c_iter.user_key().data_,
|
||||
c_iter.user_key().size_);
|
||||
}
|
||||
@@ -790,10 +817,10 @@ void CompactionOutputs::FillFilesToCutForTtl() {
|
||||
*(compaction_->inputs(compaction_->num_input_levels() - 1));
|
||||
for (FileMetaData* file : olevel) {
|
||||
// Worth filtering out by start and end?
|
||||
uint64_t oldest_ancester_time = file->TryGetOldestAncesterTime();
|
||||
uint64_t oldest_ancestor_time = file->TryGetOldestAncestorTime();
|
||||
// We put old files if they are not too small to prevent a flood
|
||||
// of small files.
|
||||
if (oldest_ancester_time < old_age_thres &&
|
||||
if (oldest_ancestor_time < old_age_thres &&
|
||||
file->fd.GetFileSize() >
|
||||
compaction_->mutable_cf_options().target_file_size_base / 2) {
|
||||
files_to_cut_for_ttl_.push_back(file);
|
||||
|
||||
@@ -349,8 +349,19 @@ class CompactionOutputs {
|
||||
const bool is_proximal_level_;
|
||||
|
||||
// partitioner information
|
||||
std::string last_key_for_partitioner_;
|
||||
std::unique_ptr<SstPartitioner> partitioner_;
|
||||
// Previous user key, only maintained (copied per key) in the fallback mode
|
||||
// (see below).
|
||||
std::string last_key_for_partitioner_;
|
||||
// Fast path for partitioners that support ShouldPartitionByPrefix(): when
|
||||
// partitioner_prefix_valid_ is true, all keys in the current output file
|
||||
// share partitioner_prefix_, and a partition boundary is requested at the
|
||||
// first future key that does not start with that prefix. This is (re)derived
|
||||
// once per output file from its first key, avoiding a per-key copy and
|
||||
// virtual ShouldPartition() call. When false, we fall back to comparing
|
||||
// against last_key_for_partitioner_ via ShouldPartition() on every key.
|
||||
std::string partitioner_prefix_;
|
||||
bool partitioner_prefix_valid_ = false;
|
||||
|
||||
// A flag determines if this subcompaction has been split by the cursor
|
||||
// for RoundRobin compaction
|
||||
@@ -360,7 +371,7 @@ class CompactionOutputs {
|
||||
// repetitive comparison in ShouldStopBefore()
|
||||
const InternalKey* local_output_split_key_ = nullptr;
|
||||
|
||||
// Some identified files with old oldest ancester time and the range should be
|
||||
// Some identified files with old oldest ancestor time and the range should be
|
||||
// isolated out so that the output file(s) in that range can be merged down
|
||||
// for TTL and clear the timestamps for the range.
|
||||
std::vector<FileMetaData*> files_to_cut_for_ttl_;
|
||||
|
||||
@@ -319,21 +319,22 @@ bool CompactionPicker::ExpandInputsToCleanCut(const std::string& /*cf_name*/,
|
||||
}
|
||||
|
||||
bool CompactionPicker::RangeOverlapWithCompaction(
|
||||
const Slice& smallest_user_key, const Slice& largest_user_key,
|
||||
int level) const {
|
||||
const Slice& smallest_user_key, const Slice& largest_user_key, int level,
|
||||
bool range_limit_exclusive) const {
|
||||
const Comparator* ucmp = icmp_->user_comparator();
|
||||
for (Compaction* c : compactions_in_progress_) {
|
||||
const int largest_cmp = ucmp->CompareWithoutTimestamp(
|
||||
largest_user_key, c->GetSmallestUserKey());
|
||||
if (c->output_level() == level &&
|
||||
ucmp->CompareWithoutTimestamp(smallest_user_key,
|
||||
c->GetLargestUserKey()) <= 0 &&
|
||||
ucmp->CompareWithoutTimestamp(largest_user_key,
|
||||
c->GetSmallestUserKey()) >= 0) {
|
||||
(range_limit_exclusive ? largest_cmp > 0 : largest_cmp >= 0)) {
|
||||
// Overlap
|
||||
return true;
|
||||
}
|
||||
if (c->SupportsPerKeyPlacement()) {
|
||||
if (c->OverlapProximalLevelOutputRange(smallest_user_key,
|
||||
largest_user_key)) {
|
||||
if (c->OverlapProximalLevelOutputRange(
|
||||
smallest_user_key, largest_user_key, range_limit_exclusive)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -364,7 +365,8 @@ bool CompactionPicker::FilesRangeOverlapWithCompaction(
|
||||
if (proximal_level != Compaction::kInvalidLevel) {
|
||||
if (ioptions_.compaction_style == kCompactionStyleUniversal) {
|
||||
if (RangeOverlapWithCompaction(smallest.user_key(), largest.user_key(),
|
||||
proximal_level)) {
|
||||
proximal_level,
|
||||
/*range_limit_exclusive=*/false)) {
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
@@ -372,14 +374,16 @@ bool CompactionPicker::FilesRangeOverlapWithCompaction(
|
||||
GetRange(inputs, &proximal_smallest, &proximal_largest, level);
|
||||
if (RangeOverlapWithCompaction(proximal_smallest.user_key(),
|
||||
proximal_largest.user_key(),
|
||||
proximal_level)) {
|
||||
proximal_level,
|
||||
/*range_limit_exclusive=*/false)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return RangeOverlapWithCompaction(smallest.user_key(), largest.user_key(),
|
||||
level);
|
||||
level,
|
||||
/*range_limit_exclusive=*/false);
|
||||
}
|
||||
|
||||
// Returns true if any one of specified files are being compacted
|
||||
|
||||
@@ -154,8 +154,8 @@ class CompactionPicker {
|
||||
// Return true if the passed key range overlap with a compaction output
|
||||
// that is currently running.
|
||||
bool RangeOverlapWithCompaction(const Slice& smallest_user_key,
|
||||
const Slice& largest_user_key,
|
||||
int level) const;
|
||||
const Slice& largest_user_key, int level,
|
||||
bool range_limit_exclusive) const;
|
||||
|
||||
// Stores the minimal range that covers all entries in inputs in
|
||||
// *smallest, *largest.
|
||||
|
||||
@@ -105,9 +105,10 @@ Compaction* FIFOCompactionPicker::PickTTLCompaction(
|
||||
TableReader* reader = f->fd.pinned_reader.Get();
|
||||
if (reader != nullptr && reader->GetTableProperties() != nullptr) {
|
||||
uint64_t newest_key_time = f->TryGetNewestKeyTime();
|
||||
uint64_t creation_time = reader->GetTableProperties()->creation_time;
|
||||
uint64_t oldest_ancestor_time =
|
||||
reader->GetTableProperties()->oldest_ancestor_time;
|
||||
uint64_t est_newest_key_time = newest_key_time == kUnknownNewestKeyTime
|
||||
? creation_time
|
||||
? oldest_ancestor_time
|
||||
: newest_key_time;
|
||||
if (est_newest_key_time == kUnknownNewestKeyTime ||
|
||||
est_newest_key_time >= (current_time - mutable_cf_options.ttl)) {
|
||||
@@ -165,13 +166,13 @@ Compaction* FIFOCompactionPicker::PickTTLCompaction(
|
||||
for (const auto& f : inputs[0].files) {
|
||||
assert(f);
|
||||
uint64_t newest_key_time = f->TryGetNewestKeyTime();
|
||||
uint64_t creation_time = 0;
|
||||
uint64_t oldest_ancestor_time = 0;
|
||||
TableReader* reader = f->fd.pinned_reader.Get();
|
||||
if (reader != nullptr && reader->GetTableProperties() != nullptr) {
|
||||
creation_time = reader->GetTableProperties()->creation_time;
|
||||
oldest_ancestor_time = reader->GetTableProperties()->oldest_ancestor_time;
|
||||
}
|
||||
uint64_t est_newest_key_time = newest_key_time == kUnknownNewestKeyTime
|
||||
? creation_time
|
||||
? oldest_ancestor_time
|
||||
: newest_key_time;
|
||||
ROCKS_LOG_BUFFER(log_buffer,
|
||||
"[%s] FIFO compaction: picking file %" PRIu64
|
||||
|
||||
@@ -90,7 +90,8 @@ class CompactionPickerTestBase : public testing::Test {
|
||||
&icmp_, ucmp_, options_.num_levels, style, nullptr, false,
|
||||
EpochNumberRequirement::kMustPresent, ioptions_.clock,
|
||||
options_.bottommost_file_compaction_delay,
|
||||
OffpeakTimeOption(mutable_db_options_.daily_offpeak_time_utc)));
|
||||
OffpeakTimeOption(mutable_db_options_.daily_offpeak_time_utc),
|
||||
PeriodicCompactionPhaseParams{}));
|
||||
vstorage_->PrepareForVersionAppend(ioptions_, mutable_cf_options_);
|
||||
}
|
||||
|
||||
@@ -101,7 +102,8 @@ class CompactionPickerTestBase : public testing::Test {
|
||||
&icmp_, ucmp_, options_.num_levels, ioptions_.compaction_style,
|
||||
vstorage_.get(), false, EpochNumberRequirement::kMustPresent,
|
||||
ioptions_.clock, options_.bottommost_file_compaction_delay,
|
||||
OffpeakTimeOption(mutable_db_options_.daily_offpeak_time_utc)));
|
||||
OffpeakTimeOption(mutable_db_options_.daily_offpeak_time_utc),
|
||||
PeriodicCompactionPhaseParams{}));
|
||||
}
|
||||
|
||||
void DeleteVersionStorage() {
|
||||
@@ -118,7 +120,7 @@ class CompactionPickerTestBase : public testing::Test {
|
||||
SequenceNumber smallest_seq = 100, SequenceNumber largest_seq = 100,
|
||||
size_t compensated_file_size = 0, bool marked_for_compact = false,
|
||||
Temperature temperature = Temperature::kUnknown,
|
||||
uint64_t oldest_ancestor_time = kUnknownOldestAncesterTime,
|
||||
uint64_t oldest_ancestor_time = kUnknownOldestAncestorTime,
|
||||
uint64_t newest_key_time = kUnknownNewestKeyTime,
|
||||
Slice ts_of_smallest = Slice(), Slice ts_of_largest = Slice(),
|
||||
uint64_t epoch_number = kUnknownEpochNumber) {
|
||||
@@ -160,15 +162,15 @@ class CompactionPickerTestBase : public testing::Test {
|
||||
FileMetaData* f = new FileMetaData(
|
||||
file_number, path_id, file_size, smallest_ikey, largest_ikey,
|
||||
smallest_seq, largest_seq, marked_for_compact, temperature,
|
||||
kInvalidBlobFileNumber, kUnknownOldestAncesterTime,
|
||||
kInvalidBlobFileNumber, kUnknownOldestAncestorTime,
|
||||
kUnknownFileCreationTime, epoch_number, kUnknownFileChecksum,
|
||||
kUnknownFileChecksumFuncName, kNullUniqueId64x2, 0, 0,
|
||||
true /* user_defined_timestamps_persisted */, "" /* min timestamp */,
|
||||
"" /* max timestamp */);
|
||||
f->compensated_file_size =
|
||||
(compensated_file_size != 0) ? compensated_file_size : file_size;
|
||||
// oldest_ancester_time is only used if newest_key_time is not available
|
||||
f->oldest_ancester_time = oldest_ancestor_time;
|
||||
// oldest_ancestor_time is only used if newest_key_time is not available
|
||||
f->oldest_ancestor_time = oldest_ancestor_time;
|
||||
// Set min/max timestamps for UDT support
|
||||
if (!ts_of_smallest.empty()) {
|
||||
f->min_timestamp = ts_of_smallest.ToString();
|
||||
@@ -323,7 +325,7 @@ class CompactionPickerU64TsTest : public CompactionPickerTestBase {
|
||||
/*smallest_seq=*/10, /*largest_seq=*/40,
|
||||
/*compensated_file_size=*/1000,
|
||||
/*marked_for_compact=*/false, Temperature::kUnknown,
|
||||
kUnknownOldestAncesterTime, kUnknownNewestKeyTime, ts_small, ts_large);
|
||||
kUnknownOldestAncestorTime, kUnknownNewestKeyTime, ts_small, ts_large);
|
||||
|
||||
std::string full_history_ts_low = MakeU64Timestamp(full_history_ts_low_val);
|
||||
|
||||
@@ -348,12 +350,12 @@ class CompactionPickerU64TsTest : public CompactionPickerTestBase {
|
||||
/*smallest_seq=*/100, /*largest_seq=*/100,
|
||||
/*compensated_file_size=*/file_size,
|
||||
/*marked_for_compact=*/false, Temperature::kUnknown,
|
||||
kUnknownOldestAncesterTime, kUnknownNewestKeyTime, ts1, ts2);
|
||||
kUnknownOldestAncestorTime, kUnknownNewestKeyTime, ts1, ts2);
|
||||
Add(0, 2U, "150", "250", file_size, /*path_id=*/0,
|
||||
/*smallest_seq=*/200, /*largest_seq=*/200,
|
||||
/*compensated_file_size=*/file_size,
|
||||
/*marked_for_compact=*/false, Temperature::kUnknown,
|
||||
kUnknownOldestAncesterTime, kUnknownNewestKeyTime, ts1, ts2);
|
||||
kUnknownOldestAncestorTime, kUnknownNewestKeyTime, ts1, ts2);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1450,14 +1452,14 @@ TEST_F(CompactionPickerTest, FIFOToCold1) {
|
||||
static_cast<uint64_t>(current_time) - kColdThreshold;
|
||||
Add(0 /* level */, 4U /* file_number */, "260", "300", 1 * kFileSize, 0,
|
||||
2500, 2600, 0, true, Temperature::kUnknown,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime
|
||||
: threshold_time - 2000 /* oldest_ancestor_time */,
|
||||
newestKeyTimeKnown ? threshold_time - 2000
|
||||
: kUnknownNewestKeyTime /* newest_key_time */);
|
||||
// Qualifies for compaction to kCold.
|
||||
Add(0, 3U, "200", "300", 4 * kFileSize, 0, 2300, 2400, 0, true,
|
||||
Temperature::kUnknown,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime : threshold_time - 3000,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime : threshold_time - 3000,
|
||||
newestKeyTimeKnown ? threshold_time - 3000
|
||||
: kUnknownNewestKeyTime /* newest_key_time */);
|
||||
UpdateVersionStorageInfo();
|
||||
@@ -1502,32 +1504,32 @@ TEST_F(CompactionPickerTest, FIFOToColdMaxCompactionSize) {
|
||||
static_cast<uint64_t>(current_time) - kColdThreshold;
|
||||
Add(0, 6U, "240", "290", 2 * kFileSize, 0, 2900, 3000, 0, true,
|
||||
Temperature::kUnknown,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime
|
||||
: static_cast<uint64_t>(current_time) - 100,
|
||||
newestKeyTimeKnown ? static_cast<uint64_t>(current_time) - 100
|
||||
: kUnknownNewestKeyTime);
|
||||
Add(0, 5U, "240", "290", 2 * kFileSize, 0, 2700, 2800, 0, true,
|
||||
Temperature::kUnknown,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime : threshold_time + 100,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime : threshold_time + 100,
|
||||
newestKeyTimeKnown ? threshold_time + 100 : kUnknownNewestKeyTime);
|
||||
Add(0, 4U, "260", "300", 1 * kFileSize, 0, 2500, 2600, 0, true,
|
||||
Temperature::kUnknown,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime : threshold_time - 2000,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime : threshold_time - 2000,
|
||||
newestKeyTimeKnown ? threshold_time - 2000 : kUnknownNewestKeyTime);
|
||||
// The following two files qualify for compaction to kCold.
|
||||
// But only the last two should be included to respect
|
||||
// `max_compaction_bytes`.
|
||||
Add(0, 3U, "200", "300", 4 * kFileSize, 0, 2300, 2400, 0, true,
|
||||
Temperature::kUnknown,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime : threshold_time - 3000,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime : threshold_time - 3000,
|
||||
newestKeyTimeKnown ? threshold_time - 3000 : kUnknownNewestKeyTime);
|
||||
Add(0, 2U, "200", "300", 4 * kFileSize, 0, 2100, 2200, 0, true,
|
||||
Temperature::kUnknown,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime : threshold_time - 4000,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime : threshold_time - 4000,
|
||||
newestKeyTimeKnown ? threshold_time - 4000 : kUnknownNewestKeyTime);
|
||||
Add(0, 1U, "200", "300", 4 * kFileSize, 0, 2000, 2100, 0, true,
|
||||
Temperature::kUnknown,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime : threshold_time - 5000,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime : threshold_time - 5000,
|
||||
newestKeyTimeKnown ? threshold_time - 5000 : kUnknownNewestKeyTime);
|
||||
UpdateVersionStorageInfo();
|
||||
|
||||
@@ -1572,30 +1574,30 @@ TEST_F(CompactionPickerTest, FIFOToColdWithExistingCold) {
|
||||
static_cast<uint64_t>(current_time) - kColdThreshold;
|
||||
Add(0, 6U, "240", "290", 2 * kFileSize, 0, 2900, 3000, 0, true,
|
||||
Temperature::kUnknown,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime
|
||||
: static_cast<uint64_t>(current_time) - 100,
|
||||
newestKeyTimeKnown ? static_cast<uint64_t>(current_time) - 100
|
||||
: kUnknownNewestKeyTime);
|
||||
Add(0, 5U, "240", "290", 2 * kFileSize, 0, 2700, 2800, 0, true,
|
||||
Temperature::kUnknown,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime : threshold_time + 100,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime : threshold_time + 100,
|
||||
newestKeyTimeKnown ? threshold_time + 100 : kUnknownNewestKeyTime);
|
||||
Add(0, 4U, "260", "300", 1 * kFileSize, 0, 2500, 2600, 0, true,
|
||||
Temperature::kUnknown,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime : threshold_time - 2000,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime : threshold_time - 2000,
|
||||
newestKeyTimeKnown ? threshold_time - 2000 : kUnknownNewestKeyTime);
|
||||
// The following two files qualify for compaction to kCold.
|
||||
Add(0, 3U, "200", "300", 4 * kFileSize, 0, 2300, 2400, 0, true,
|
||||
Temperature::kUnknown,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime : threshold_time - 3000,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime : threshold_time - 3000,
|
||||
newestKeyTimeKnown ? threshold_time - 3000 : kUnknownNewestKeyTime);
|
||||
Add(0, 2U, "200", "300", 4 * kFileSize, 0, 2100, 2200, 0, true,
|
||||
Temperature::kUnknown,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime : threshold_time - 4000,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime : threshold_time - 4000,
|
||||
newestKeyTimeKnown ? threshold_time - 4000 : kUnknownNewestKeyTime);
|
||||
Add(0, 1U, "200", "300", 4 * kFileSize, 0, 2000, 2100, 0, true,
|
||||
Temperature::kCold,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime : threshold_time - 5000,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime : threshold_time - 5000,
|
||||
newestKeyTimeKnown ? threshold_time - 5000 : kUnknownNewestKeyTime);
|
||||
UpdateVersionStorageInfo();
|
||||
|
||||
@@ -1640,30 +1642,30 @@ TEST_F(CompactionPickerTest, FIFOToColdWithHotBetweenCold) {
|
||||
static_cast<uint64_t>(current_time) - kColdThreshold;
|
||||
Add(0, 6U, "240", "290", 2 * kFileSize, 0, 2900, 3000, 0, true,
|
||||
Temperature::kUnknown,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime
|
||||
: static_cast<uint64_t>(current_time) - 100,
|
||||
newestKeyTimeKnown ? static_cast<uint64_t>(current_time) - 100
|
||||
: kUnknownNewestKeyTime);
|
||||
Add(0, 5U, "240", "290", 2 * kFileSize, 0, 2700, 2800, 0, true,
|
||||
Temperature::kUnknown,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime : threshold_time + 100,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime : threshold_time + 100,
|
||||
newestKeyTimeKnown ? threshold_time + 100 : kUnknownNewestKeyTime);
|
||||
Add(0, 4U, "260", "300", 1 * kFileSize, 0, 2500, 2600, 0, true,
|
||||
Temperature::kUnknown,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime : threshold_time - 2000,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime : threshold_time - 2000,
|
||||
newestKeyTimeKnown ? threshold_time - 2000 : kUnknownNewestKeyTime);
|
||||
Add(0, 3U, "200", "300", 4 * kFileSize, 0, 2300, 2400, 0, true,
|
||||
Temperature::kCold,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime : threshold_time - 3000,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime : threshold_time - 3000,
|
||||
newestKeyTimeKnown ? threshold_time - 3000 : kUnknownNewestKeyTime);
|
||||
// Qualifies for compaction to kCold.
|
||||
Add(0, 2U, "200", "300", 4 * kFileSize, 0, 2100, 2200, 0, true,
|
||||
Temperature::kUnknown,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime : threshold_time - 4000,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime : threshold_time - 4000,
|
||||
newestKeyTimeKnown ? threshold_time - 4000 : kUnknownNewestKeyTime);
|
||||
Add(0, 1U, "200", "300", 4 * kFileSize, 0, 2000, 2100, 0, true,
|
||||
Temperature::kCold,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime : threshold_time - 5000,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime : threshold_time - 5000,
|
||||
newestKeyTimeKnown ? threshold_time - 5000 : kUnknownNewestKeyTime);
|
||||
UpdateVersionStorageInfo();
|
||||
|
||||
@@ -1712,36 +1714,36 @@ TEST_F(CompactionPickerTest, FIFOToHotAndWarm) {
|
||||
static_cast<uint64_t>(current_time) - kWarmThreshold;
|
||||
Add(0, 6U, "240", "290", 2 * kFileSize, 0, 2900, 3000, 0, true,
|
||||
Temperature::kUnknown,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime
|
||||
: static_cast<uint64_t>(current_time) - 100,
|
||||
newestKeyTimeKnown ? static_cast<uint64_t>(current_time) - 100
|
||||
: kUnknownNewestKeyTime);
|
||||
Add(0, 5U, "240", "290", 2 * kFileSize, 0, 2700, 2800, 0, true,
|
||||
Temperature::kUnknown,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime
|
||||
: hot_threshold_time + 100,
|
||||
newestKeyTimeKnown ? hot_threshold_time + 100 : kUnknownNewestKeyTime);
|
||||
Add(0, 4U, "260", "300", 1 * kFileSize, 0, 2500, 2600, 0, true,
|
||||
Temperature::kUnknown,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime
|
||||
: hot_threshold_time - 200,
|
||||
newestKeyTimeKnown ? hot_threshold_time - 200 : kUnknownNewestKeyTime);
|
||||
// Qualifies for Hot
|
||||
Add(0, 3U, "200", "300", 4 * kFileSize, 0, 2300, 2400, 0, true,
|
||||
Temperature::kUnknown,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime
|
||||
: warm_threshold_time - 100,
|
||||
newestKeyTimeKnown ? warm_threshold_time - 100 : kUnknownNewestKeyTime);
|
||||
// Qualifies for Warm
|
||||
Add(0, 2U, "200", "300", 4 * kFileSize, 0, 2100, 2200, 0, true,
|
||||
Temperature::kUnknown,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime
|
||||
: warm_threshold_time - 4000,
|
||||
newestKeyTimeKnown ? warm_threshold_time - 4000
|
||||
: kUnknownNewestKeyTime);
|
||||
Add(0, 1U, "200", "300", 4 * kFileSize, 0, 2000, 2100, 0, true,
|
||||
Temperature::kUnknown,
|
||||
newestKeyTimeKnown ? kUnknownOldestAncesterTime
|
||||
newestKeyTimeKnown ? kUnknownOldestAncestorTime
|
||||
: warm_threshold_time - 5000,
|
||||
newestKeyTimeKnown ? warm_threshold_time - 5000
|
||||
: kUnknownNewestKeyTime);
|
||||
@@ -2488,7 +2490,7 @@ TEST_F(CompactionPickerTest, FileTtlBoosterLargeNumLevels) {
|
||||
FileTtlBooster booster(kCurrentTime, /*ttl=*/2048,
|
||||
/*num_non_empty_levels=*/100, /*level=*/1);
|
||||
FileMetaData meta;
|
||||
meta.oldest_ancester_time = kCurrentTime - 1023;
|
||||
meta.oldest_ancestor_time = kCurrentTime - 1023;
|
||||
ASSERT_EQ(1, booster.GetBoostScore(&meta));
|
||||
}
|
||||
|
||||
@@ -2507,47 +2509,47 @@ TEST_F(CompactionPickerTest, FileTtlBooster) {
|
||||
FileTtlBooster booster(kCurrentTime, 2048, 7, 3);
|
||||
|
||||
// Not triggering if the file is younger than ttl/2
|
||||
meta.oldest_ancester_time = kCurrentTime - 1023;
|
||||
meta.oldest_ancestor_time = kCurrentTime - 1023;
|
||||
ASSERT_EQ(1, booster.GetBoostScore(&meta));
|
||||
meta.oldest_ancester_time = kCurrentTime - 1024;
|
||||
meta.oldest_ancestor_time = kCurrentTime - 1024;
|
||||
ASSERT_EQ(1, booster.GetBoostScore(&meta));
|
||||
meta.oldest_ancester_time = kCurrentTime + 10;
|
||||
meta.oldest_ancestor_time = kCurrentTime + 10;
|
||||
ASSERT_EQ(1, booster.GetBoostScore(&meta));
|
||||
|
||||
// Within one boosting step
|
||||
meta.oldest_ancester_time = kCurrentTime - (1024 + 120 + 6);
|
||||
meta.oldest_ancestor_time = kCurrentTime - (1024 + 120 + 6);
|
||||
ASSERT_EQ(1, booster.GetBoostScore(&meta));
|
||||
|
||||
// One boosting step
|
||||
meta.oldest_ancester_time = kCurrentTime - (1024 + 120 + 7);
|
||||
meta.oldest_ancestor_time = kCurrentTime - (1024 + 120 + 7);
|
||||
ASSERT_EQ(2, booster.GetBoostScore(&meta));
|
||||
meta.oldest_ancester_time = kCurrentTime - (1024 + 120 + 8);
|
||||
meta.oldest_ancestor_time = kCurrentTime - (1024 + 120 + 8);
|
||||
ASSERT_EQ(2, booster.GetBoostScore(&meta));
|
||||
|
||||
// Multiple boosting steps
|
||||
meta.oldest_ancester_time = kCurrentTime - (1024 + 120 + 30);
|
||||
meta.oldest_ancestor_time = kCurrentTime - (1024 + 120 + 30);
|
||||
ASSERT_EQ(5, booster.GetBoostScore(&meta));
|
||||
|
||||
// Very high boosting steps
|
||||
meta.oldest_ancester_time = kCurrentTime - (1024 + 120 + 700);
|
||||
meta.oldest_ancestor_time = kCurrentTime - (1024 + 120 + 700);
|
||||
ASSERT_EQ(101, booster.GetBoostScore(&meta));
|
||||
}
|
||||
{
|
||||
// Test second last level
|
||||
FileTtlBooster booster(kCurrentTime, 2048, 7, 5);
|
||||
meta.oldest_ancester_time = kCurrentTime - (1024 + 480);
|
||||
meta.oldest_ancestor_time = kCurrentTime - (1024 + 480);
|
||||
ASSERT_EQ(1, booster.GetBoostScore(&meta));
|
||||
meta.oldest_ancester_time = kCurrentTime - (1024 + 480 + 60);
|
||||
meta.oldest_ancestor_time = kCurrentTime - (1024 + 480 + 60);
|
||||
ASSERT_EQ(3, booster.GetBoostScore(&meta));
|
||||
}
|
||||
{
|
||||
// Test last level
|
||||
FileTtlBooster booster(kCurrentTime, 2048, 7, 6);
|
||||
meta.oldest_ancester_time = kCurrentTime - (1024 + 480);
|
||||
meta.oldest_ancestor_time = kCurrentTime - (1024 + 480);
|
||||
ASSERT_EQ(1, booster.GetBoostScore(&meta));
|
||||
meta.oldest_ancester_time = kCurrentTime - (1024 + 480 + 60);
|
||||
meta.oldest_ancestor_time = kCurrentTime - (1024 + 480 + 60);
|
||||
ASSERT_EQ(1, booster.GetBoostScore(&meta));
|
||||
meta.oldest_ancester_time = kCurrentTime - 3000;
|
||||
meta.oldest_ancestor_time = kCurrentTime - 3000;
|
||||
ASSERT_EQ(1, booster.GetBoostScore(&meta));
|
||||
}
|
||||
}
|
||||
@@ -3575,21 +3577,21 @@ TEST_F(CompactionPickerTest, UniversalMarkedCompactionFullOverlap) {
|
||||
|
||||
Add(0, 1U, "150", "200", kFileSize, 0, 500, 550, /*compensated_file_size*/ 0,
|
||||
/*marked_for_compact*/ false, /* temperature*/ Temperature::kUnknown,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncesterTime,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncestorTime,
|
||||
/*newest_key_time*/ kUnknownNewestKeyTime,
|
||||
/*ts_of_smallest*/ Slice(), /*ts_of_largest*/ Slice(),
|
||||
/*epoch_number*/ 3);
|
||||
Add(0, 2U, "201", "250", 2 * kFileSize, 0, 401, 450,
|
||||
/*compensated_file_size*/ 0, /*marked_for_compact*/ false,
|
||||
/* temperature*/ Temperature::kUnknown,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncesterTime,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncestorTime,
|
||||
/*newest_key_time*/ kUnknownNewestKeyTime,
|
||||
/*ts_of_smallest*/ Slice(), /*ts_of_largest*/ Slice(),
|
||||
/*epoch_number*/ 2);
|
||||
Add(0, 4U, "260", "300", 4 * kFileSize, 0, 260, 300,
|
||||
/*compensated_file_size*/ 0, /*marked_for_compact*/ false,
|
||||
/* temperature*/ Temperature::kUnknown,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncesterTime,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncestorTime,
|
||||
/*newest_key_time*/ kUnknownNewestKeyTime,
|
||||
/*ts_of_smallest*/ Slice(), /*ts_of_largest*/ Slice(),
|
||||
/*epoch_number*/ 1);
|
||||
@@ -3617,7 +3619,7 @@ TEST_F(CompactionPickerTest, UniversalMarkedCompactionFullOverlap) {
|
||||
// Simulate a flush and mark the file for compaction
|
||||
Add(0, 7U, "150", "200", kFileSize, 0, 551, 600, 0, true,
|
||||
/* temperature*/ Temperature::kUnknown,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncesterTime,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncestorTime,
|
||||
/*newest_key_time*/ kUnknownNewestKeyTime,
|
||||
/*ts_of_smallest*/ Slice(), /*ts_of_largest*/ Slice(),
|
||||
/*epoch_number*/ 4);
|
||||
@@ -3645,7 +3647,7 @@ TEST_F(CompactionPickerTest, UniversalMarkedCompactionFullOverlap2) {
|
||||
// Mark file number 4 for compaction
|
||||
Add(0, 4U, "260", "300", 4 * kFileSize, 0, 260, 300, 0, true,
|
||||
/* temperature*/ Temperature::kUnknown,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncesterTime,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncestorTime,
|
||||
/*newest_key_time*/ kUnknownNewestKeyTime,
|
||||
/*ts_of_smallest*/ Slice(), /*ts_of_largest*/ Slice(),
|
||||
/*epoch_number*/ 1);
|
||||
@@ -3672,14 +3674,14 @@ TEST_F(CompactionPickerTest, UniversalMarkedCompactionFullOverlap2) {
|
||||
AddVersionStorage();
|
||||
Add(0, 1U, "150", "200", kFileSize, 0, 500, 550, /*compensated_file_size*/ 0,
|
||||
/*marked_for_compact*/ false, /* temperature*/ Temperature::kUnknown,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncesterTime,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncestorTime,
|
||||
/*newest_key_time*/ kUnknownNewestKeyTime,
|
||||
/*ts_of_smallest*/ Slice(), /*ts_of_largest*/ Slice(),
|
||||
/*epoch_number*/ 3);
|
||||
Add(0, 2U, "201", "250", 2 * kFileSize, 0, 401, 450,
|
||||
/*compensated_file_size*/ 0, /*marked_for_compact*/ false,
|
||||
/* temperature*/ Temperature::kUnknown,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncesterTime,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncestorTime,
|
||||
/*newest_key_time*/ kUnknownNewestKeyTime,
|
||||
/*ts_of_smallest*/ Slice(), /*ts_of_largest*/ Slice(),
|
||||
/*epoch_number*/ 2);
|
||||
@@ -3857,27 +3859,27 @@ TEST_F(CompactionPickerTest, UniversalMarkedL0Overlap2) {
|
||||
Add(0, 4U, "260", "300", 1 * kFileSize, 0, 260, 300,
|
||||
/*compensated_file_size*/ 0, /*marked_for_compact*/ false,
|
||||
/* temperature*/ Temperature::kUnknown,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncesterTime,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncestorTime,
|
||||
/*newest_key_time*/ kUnknownNewestKeyTime,
|
||||
/*ts_of_smallest*/ Slice(), /*ts_of_largest*/ Slice(),
|
||||
/*epoch_number*/ 4);
|
||||
Add(0, 5U, "240", "290", 2 * kFileSize, 0, 201, 250, 0, true,
|
||||
/* temperature*/ Temperature::kUnknown,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncesterTime,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncestorTime,
|
||||
/*newest_key_time*/ kUnknownNewestKeyTime,
|
||||
/*ts_of_smallest*/ Slice(), /*ts_of_largest*/ Slice(),
|
||||
/*epoch_number*/ 3);
|
||||
Add(0, 3U, "301", "350", 4 * kFileSize, 0, 101, 150,
|
||||
/*compensated_file_size*/ 0, /*marked_for_compact*/ false,
|
||||
/* temperature*/ Temperature::kUnknown,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncesterTime,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncestorTime,
|
||||
/*newest_key_time*/ kUnknownNewestKeyTime,
|
||||
/*ts_of_smallest*/ Slice(), /*ts_of_largest*/ Slice(),
|
||||
/*epoch_number*/ 2);
|
||||
Add(0, 6U, "501", "750", 8 * kFileSize, 0, 50, 100,
|
||||
/*compensated_file_size*/ 0, /*marked_for_compact*/ false,
|
||||
/* temperature*/ Temperature::kUnknown,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncesterTime,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncestorTime,
|
||||
/*newest_key_time*/ kUnknownNewestKeyTime,
|
||||
/*ts_of_smallest*/ Slice(), /*ts_of_largest*/ Slice(),
|
||||
/*epoch_number*/ 1);
|
||||
@@ -3904,14 +3906,14 @@ TEST_F(CompactionPickerTest, UniversalMarkedL0Overlap2) {
|
||||
Add(0, 1U, "150", "200", kFileSize, 0, 500, 550, /*compensated_file_size*/ 0,
|
||||
/*marked_for_compact*/ false,
|
||||
/* temperature*/ Temperature::kUnknown,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncesterTime,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncestorTime,
|
||||
/*newest_key_time*/ kUnknownNewestKeyTime,
|
||||
/*ts_of_smallest*/ Slice(), /*ts_of_largest*/ Slice(),
|
||||
/*epoch_number*/ 6);
|
||||
Add(0, 2U, "201", "250", kFileSize, 0, 401, 450, /*compensated_file_size*/ 0,
|
||||
/*marked_for_compact*/ false,
|
||||
/* temperature*/ Temperature::kUnknown,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncesterTime,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncestorTime,
|
||||
/*newest_key_time*/ kUnknownNewestKeyTime,
|
||||
/*ts_of_smallest*/ Slice(), /*ts_of_largest*/ Slice(),
|
||||
/*epoch_number*/ 5);
|
||||
@@ -4147,7 +4149,7 @@ TEST_F(CompactionPickerU64TsTest, Overlap) {
|
||||
/*file_size=*/1U, /*path_id=*/0,
|
||||
/*smallest_seq=*/100, /*largest_seq=*/100, /*compensated_file_size=*/0,
|
||||
/*marked_for_compact=*/false, /*temperature=*/Temperature::kUnknown,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncesterTime,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncestorTime,
|
||||
/*newest_key_time*/ kUnknownNewestKeyTime, ts1, ts2);
|
||||
UpdateVersionStorageInfo();
|
||||
}
|
||||
@@ -4162,6 +4164,18 @@ TEST_F(CompactionPickerU64TsTest, Overlap) {
|
||||
CompactionOptions(), input_files, level, vstorage_.get(),
|
||||
mutable_cf_options_, mutable_db_options_, /*output_path_id=*/0));
|
||||
|
||||
{
|
||||
std::string range_start("400");
|
||||
PutFixed64(&range_start, ts_of_smallest);
|
||||
std::string range_limit(smallest);
|
||||
PutFixed64(&range_limit, ts_of_smallest);
|
||||
ASSERT_FALSE(level_compaction_picker.RangeOverlapWithCompaction(
|
||||
range_start, range_limit, level, /*range_limit_exclusive=*/true));
|
||||
ASSERT_TRUE(level_compaction_picker.RangeOverlapWithCompaction(
|
||||
range_start, range_limit, level,
|
||||
/*range_limit_exclusive=*/false));
|
||||
}
|
||||
|
||||
{
|
||||
// [600, ts=50000] to [600, ts=50000] is the range to check.
|
||||
// ucmp->Compare(smallest_user_key, c->GetLargestUserKey()) > 0, but
|
||||
@@ -4173,7 +4187,8 @@ TEST_F(CompactionPickerU64TsTest, Overlap) {
|
||||
std::string user_key_with_ts2(largest);
|
||||
PutFixed64(&user_key_with_ts2, ts_of_largest - 1);
|
||||
ASSERT_TRUE(level_compaction_picker.RangeOverlapWithCompaction(
|
||||
user_key_with_ts1, user_key_with_ts2, level));
|
||||
user_key_with_ts1, user_key_with_ts2, level,
|
||||
/*range_limit_exclusive=*/false));
|
||||
}
|
||||
{
|
||||
// [500, ts=60000] to [500, ts=60000] is the range to check.
|
||||
@@ -4186,7 +4201,8 @@ TEST_F(CompactionPickerU64TsTest, Overlap) {
|
||||
std::string user_key_with_ts2(smallest);
|
||||
PutFixed64(&user_key_with_ts2, ts_of_smallest + 1);
|
||||
ASSERT_TRUE(level_compaction_picker.RangeOverlapWithCompaction(
|
||||
user_key_with_ts1, user_key_with_ts2, level));
|
||||
user_key_with_ts1, user_key_with_ts2, level,
|
||||
/*range_limit_exclusive=*/false));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4215,12 +4231,12 @@ TEST_F(CompactionPickerU64TsTest, CannotTrivialMoveUniversal) {
|
||||
Add(1, 1U, "150", "150", kFileSize, /*path_id=*/0, /*smallest_seq=*/100,
|
||||
/*largest_seq=*/100, /*compensated_file_size=*/kFileSize,
|
||||
/*marked_for_compact=*/false, Temperature::kUnknown,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncesterTime,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncestorTime,
|
||||
/*newest_key_time*/ kUnknownNewestKeyTime, ts1, ts2);
|
||||
Add(2, 2U, "150", "150", kFileSize, /*path_id=*/0, /*smallest_seq=*/100,
|
||||
/*largest_seq=*/100, /*compensated_file_size=*/kFileSize,
|
||||
/*marked_for_compact=*/false, Temperature::kUnknown,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncesterTime,
|
||||
/*oldest_ancestor_time*/ kUnknownOldestAncestorTime,
|
||||
/*newest_key_time*/ kUnknownNewestKeyTime, ts3, ts4);
|
||||
UpdateVersionStorageInfo();
|
||||
|
||||
@@ -5017,12 +5033,12 @@ TEST_F(CompactionPickerTest, StandaloneRangeDeletionOnlyPicksOlderFiles) {
|
||||
// Create L0 files with overlapping ranges
|
||||
// File 1: newest regular file (epoch 5), keys [100, 200]
|
||||
Add(0, 1U, "100", "200", 1U, 0, 100, 100, 0, false, Temperature::kUnknown,
|
||||
kUnknownOldestAncesterTime, kUnknownNewestKeyTime, Slice(), Slice(), 5);
|
||||
kUnknownOldestAncestorTime, kUnknownNewestKeyTime, Slice(), Slice(), 5);
|
||||
|
||||
// File 2: standalone range deletion (epoch 4), keys [150, 250]
|
||||
// This file should be marked as having only range deletions
|
||||
Add(0, 2U, "150", "250", 1U, 0, 200, 200, 0, true, Temperature::kUnknown,
|
||||
kUnknownOldestAncesterTime, kUnknownNewestKeyTime, Slice(), Slice(), 4);
|
||||
kUnknownOldestAncestorTime, kUnknownNewestKeyTime, Slice(), Slice(), 4);
|
||||
|
||||
// Manually set file 2 as standalone range deletion
|
||||
FileMetaData* range_del_file = file_map_[2U].first;
|
||||
@@ -5058,6 +5074,41 @@ TEST_F(CompactionPickerTest, StandaloneRangeDeletionOnlyPicksOlderFiles) {
|
||||
ASSERT_EQ(10U, compaction->input(1, 0)->fd.GetNumber());
|
||||
}
|
||||
|
||||
// Tests for the seqno->time preserve window controlling bottommost file
|
||||
// marking. A bottommost file whose largest seqno is still within the preserve
|
||||
// window cannot have its seqno zeroed, so it must not be marked (otherwise the
|
||||
// rewrite makes no progress and the file is re-marked forever -- an infinite
|
||||
// loop).
|
||||
TEST_F(CompactionPickerTest, BottommostFileNotMarkedWithinPreserveWindow) {
|
||||
NewVersionStorage(6, kCompactionStyleLevel);
|
||||
Add(5, 1U, "100", "200", /*file_size=*/1000, /*path_id=*/0,
|
||||
/*smallest_seq=*/90, /*largest_seq=*/100);
|
||||
// preserve_time_min_seqno = 100 => preserve_seqno_after = 99; largest_seqno
|
||||
// 100 is within the window (> 99) and cannot be zeroed.
|
||||
vstorage_->SetPreserveTimeMinSeqno(100);
|
||||
UpdateVersionStorageInfo();
|
||||
vstorage_->UpdateOldestSnapshot(/*oldest_snapshot_seqnum=*/200,
|
||||
/*allow_ingest_behind=*/false, /*ucmp=*/ucmp_,
|
||||
/*full_history_ts_low=*/"");
|
||||
ASSERT_EQ(0U, vstorage_->BottommostFilesMarkedForCompaction().size());
|
||||
}
|
||||
|
||||
TEST_F(CompactionPickerTest, BottommostFileMarkedBelowPreserveWindow) {
|
||||
NewVersionStorage(6, kCompactionStyleLevel);
|
||||
Add(5, 1U, "100", "200", /*file_size=*/1000, /*path_id=*/0,
|
||||
/*smallest_seq=*/90, /*largest_seq=*/100);
|
||||
// preserve_time_min_seqno = 150 => preserve_seqno_after = 149; largest_seqno
|
||||
// 100 <= 149 so it can be zeroed and the file is marked as usual.
|
||||
vstorage_->SetPreserveTimeMinSeqno(150);
|
||||
UpdateVersionStorageInfo();
|
||||
vstorage_->UpdateOldestSnapshot(/*oldest_snapshot_seqnum=*/200,
|
||||
/*allow_ingest_behind=*/false, /*ucmp=*/ucmp_,
|
||||
/*full_history_ts_low=*/"");
|
||||
ASSERT_EQ(1U, vstorage_->BottommostFilesMarkedForCompaction().size());
|
||||
ASSERT_EQ(1U, vstorage_->BottommostFilesMarkedForCompaction()[0]
|
||||
.second->fd.GetNumber());
|
||||
}
|
||||
|
||||
// Tests for full_history_ts_low parameter in compaction picker.
|
||||
// The full_history_ts_low parameter is used to control bottommost file marking
|
||||
// for compaction when user-defined timestamps (UDT) are enabled.
|
||||
@@ -5118,7 +5169,7 @@ TEST_F(CompactionPickerU64TsTest,
|
||||
/*smallest_seq=*/10, /*largest_seq=*/40,
|
||||
/*compensated_file_size=*/1000,
|
||||
/*marked_for_compact=*/false, Temperature::kUnknown,
|
||||
kUnknownOldestAncesterTime, kUnknownNewestKeyTime, ts_small, ts_large);
|
||||
kUnknownOldestAncestorTime, kUnknownNewestKeyTime, ts_small, ts_large);
|
||||
|
||||
// Update version storage with empty full_history_ts_low
|
||||
UpdateVersionStorageInfo();
|
||||
@@ -5137,6 +5188,90 @@ TEST_F(CompactionPickerU64TsTest,
|
||||
ASSERT_EQ(0U, vstorage_->BottommostFilesMarkedForCompaction().size());
|
||||
}
|
||||
|
||||
TEST_F(CompactionPickerU64TsTest,
|
||||
BottommostNotMarkedWithEmptyFullHistoryTsLowAndUnknownMaxTs) {
|
||||
// Regression test for an infinite bottommost compaction loop. A bottommost
|
||||
// UDT file whose max_timestamp was not recorded in its FileMetaData (e.g. a
|
||||
// file written by an older version, or one whose timestamp property is
|
||||
// otherwise absent) must NOT be marked for compaction when
|
||||
// full_history_ts_low is unset. Under UDT the only progress a bottommost
|
||||
// compaction can make here is zeroing sequence numbers, which
|
||||
// CompactionIterator does only when full_history_ts_low is set. With it unset
|
||||
// the compaction cannot advance the file, so the rewritten output
|
||||
// re-qualifies forever.
|
||||
NewVersionStorage(6, kCompactionStyleLevel);
|
||||
|
||||
std::string ts_small = MakeU64Timestamp(50);
|
||||
std::string ts_large = MakeU64Timestamp(100);
|
||||
|
||||
// Add a bottommost file with seqno < oldest_snapshot.
|
||||
Add(5, 1U, "100", "200", /*file_size=*/1000, /*path_id=*/0,
|
||||
/*smallest_seq=*/10, /*largest_seq=*/40,
|
||||
/*compensated_file_size=*/1000,
|
||||
/*marked_for_compact=*/false, Temperature::kUnknown,
|
||||
kUnknownOldestAncestorTime, kUnknownNewestKeyTime, ts_small, ts_large);
|
||||
|
||||
// Simulate a file whose min/max timestamp was never recorded.
|
||||
ASSERT_EQ(1U, vstorage_->LevelFiles(5).size());
|
||||
FileMetaData* f = vstorage_->LevelFiles(5)[0];
|
||||
f->min_timestamp.clear();
|
||||
f->max_timestamp.clear();
|
||||
|
||||
UpdateVersionStorageInfo();
|
||||
|
||||
vstorage_->UpdateOldestSnapshot(
|
||||
/*oldest_snapshot_seqnum=*/50,
|
||||
/*allow_ingest_behind=*/false,
|
||||
/*ucmp=*/ucmp_,
|
||||
/*full_history_ts_low=*/"");
|
||||
|
||||
// No bottommost file can make progress with empty full_history_ts_low, so
|
||||
// nothing is marked even though max_timestamp is unknown. Before the fix this
|
||||
// file was marked, producing an infinite compaction loop.
|
||||
ASSERT_EQ(0U, vstorage_->BottommostFilesMarkedForCompaction().size());
|
||||
}
|
||||
|
||||
TEST_F(CompactionPickerU64TsTest,
|
||||
BottommostMarkedWithSetFullHistoryTsLowAndUnknownMaxTs) {
|
||||
// A bottommost UDT file whose max_timestamp was not recorded (e.g. written by
|
||||
// an older version) must still be marked for a one-time backfill compaction
|
||||
// when full_history_ts_low IS set: that compaction can collapse timestamp
|
||||
// history / zero seqnos and record max_timestamp, so it makes progress
|
||||
// (bounded, not a loop). This complements
|
||||
// BottommostNotMarkedWithEmptyFullHistoryTsLowAndUnknownMaxTs, which covers
|
||||
// the unset case where no progress is possible.
|
||||
NewVersionStorage(6, kCompactionStyleLevel);
|
||||
|
||||
std::string ts_small = MakeU64Timestamp(50);
|
||||
std::string ts_large = MakeU64Timestamp(100);
|
||||
|
||||
Add(5, 1U, "100", "200", /*file_size=*/1000, /*path_id=*/0,
|
||||
/*smallest_seq=*/10, /*largest_seq=*/40,
|
||||
/*compensated_file_size=*/1000,
|
||||
/*marked_for_compact=*/false, Temperature::kUnknown,
|
||||
kUnknownOldestAncestorTime, kUnknownNewestKeyTime, ts_small, ts_large);
|
||||
|
||||
// Simulate a file whose min/max timestamp was never recorded.
|
||||
ASSERT_EQ(1U, vstorage_->LevelFiles(5).size());
|
||||
FileMetaData* f = vstorage_->LevelFiles(5)[0];
|
||||
f->min_timestamp.clear();
|
||||
f->max_timestamp.clear();
|
||||
|
||||
UpdateVersionStorageInfo();
|
||||
|
||||
std::string full_history_ts_low = MakeU64Timestamp(500);
|
||||
vstorage_->UpdateOldestSnapshot(
|
||||
/*oldest_snapshot_seqnum=*/50,
|
||||
/*allow_ingest_behind=*/false,
|
||||
/*ucmp=*/ucmp_, full_history_ts_low);
|
||||
|
||||
// With full_history_ts_low set, the unknown-max_timestamp file is marked so a
|
||||
// bounded compaction can backfill its metadata and reclaim obsolete data.
|
||||
ASSERT_EQ(1U, vstorage_->BottommostFilesMarkedForCompaction().size());
|
||||
ASSERT_EQ(1U, vstorage_->BottommostFilesMarkedForCompaction()[0]
|
||||
.second->fd.GetNumber());
|
||||
}
|
||||
|
||||
TEST_F(CompactionPickerU64TsTest, LevelPickCompactionWithFullHistoryTsLow) {
|
||||
// Test that level compaction correctly passes full_history_ts_low
|
||||
// and picks compaction appropriately
|
||||
@@ -5580,13 +5715,13 @@ TEST_F(CompactionPickerTest, FIFOTTLBlobEstimationSingleLevel) {
|
||||
|
||||
uint64_t recent_time = static_cast<uint64_t>(time(nullptr));
|
||||
Add(0, 1U, "100", "200", 50 * 1024, 0, 100, 100, 0, false,
|
||||
Temperature::kUnknown, kUnknownOldestAncesterTime, recent_time);
|
||||
Temperature::kUnknown, kUnknownOldestAncestorTime, recent_time);
|
||||
Add(0, 2U, "200", "300", 50 * 1024, 0, 100, 100, 0, false,
|
||||
Temperature::kUnknown, kUnknownOldestAncesterTime, recent_time);
|
||||
Temperature::kUnknown, kUnknownOldestAncestorTime, recent_time);
|
||||
Add(0, 3U, "300", "400", 50 * 1024, 0, 100, 100, 0, false,
|
||||
Temperature::kUnknown, kUnknownOldestAncesterTime, 1);
|
||||
Temperature::kUnknown, kUnknownOldestAncestorTime, 1);
|
||||
Add(0, 4U, "400", "500", 50 * 1024, 0, 100, 100, 0, false,
|
||||
Temperature::kUnknown, kUnknownOldestAncesterTime, 1);
|
||||
Temperature::kUnknown, kUnknownOldestAncestorTime, 1);
|
||||
if (blob_total > 0) {
|
||||
AddBlobFile(100, blob_total / 2);
|
||||
AddBlobFile(101, blob_total / 2);
|
||||
@@ -5659,13 +5794,13 @@ TEST_F(CompactionPickerTest, FIFOTTLBlobEstimationMultiLevel) {
|
||||
uint64_t recent_time = static_cast<uint64_t>(time(nullptr));
|
||||
// L0 files: 2 recent, 2 expired
|
||||
Add(0, 1U, "100", "200", 50 * 1024, 0, 100, 100, 0, false,
|
||||
Temperature::kUnknown, kUnknownOldestAncesterTime, recent_time);
|
||||
Temperature::kUnknown, kUnknownOldestAncestorTime, recent_time);
|
||||
Add(0, 2U, "200", "300", 50 * 1024, 0, 100, 100, 0, false,
|
||||
Temperature::kUnknown, kUnknownOldestAncesterTime, recent_time);
|
||||
Temperature::kUnknown, kUnknownOldestAncestorTime, recent_time);
|
||||
Add(0, 3U, "300", "400", 50 * 1024, 0, 100, 100, 0, false,
|
||||
Temperature::kUnknown, kUnknownOldestAncesterTime, 1);
|
||||
Temperature::kUnknown, kUnknownOldestAncestorTime, 1);
|
||||
Add(0, 4U, "400", "500", 50 * 1024, 0, 100, 100, 0, false,
|
||||
Temperature::kUnknown, kUnknownOldestAncesterTime, 1);
|
||||
Temperature::kUnknown, kUnknownOldestAncestorTime, 1);
|
||||
// L2 legacy migration file
|
||||
Add(2, 10U, "100", "600", 200 * 1024);
|
||||
// Blob files (associated with ALL levels)
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
#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;
|
||||
@@ -49,6 +50,8 @@ CompactionJob::ProcessKeyValueCompactionWithCompactionService(
|
||||
compaction_input.end =
|
||||
compaction_input.has_end ? sub_compact->end->ToString() : "";
|
||||
compaction_input.options_file_number = options_file_number_;
|
||||
compaction_input.min_manifest_file_number = min_manifest_file_number_;
|
||||
compaction_input.min_manifest_file_size = min_manifest_file_size_;
|
||||
|
||||
TEST_SYNC_POINT_CALLBACK(
|
||||
"CompactionServiceJob::ProcessKeyValueCompactionWithCompactionService",
|
||||
@@ -81,7 +84,6 @@ CompactionJob::ProcessKeyValueCompactionWithCompactionService(
|
||||
compaction->is_full_compaction(), compaction->is_manual_compaction(),
|
||||
compaction->bottommost_level(), compaction->start_level(),
|
||||
compaction->output_level());
|
||||
|
||||
CompactionServiceScheduleResponse response =
|
||||
db_options_.compaction_service->Schedule(info, compaction_input_binary);
|
||||
switch (response.status) {
|
||||
@@ -114,9 +116,6 @@ 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
|
||||
@@ -129,18 +128,29 @@ 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 =
|
||||
db_options_.compaction_service->Wait(response.scheduled_job_id,
|
||||
&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);
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
@@ -261,7 +271,7 @@ CompactionJob::ProcessKeyValueCompactionWithCompactionService(
|
||||
file.smallest_seqno, file.largest_seqno);
|
||||
meta.smallest.DecodeFrom(file.smallest_internal_key);
|
||||
meta.largest.DecodeFrom(file.largest_internal_key);
|
||||
meta.oldest_ancester_time = file.oldest_ancester_time;
|
||||
meta.oldest_ancestor_time = file.oldest_ancestor_time;
|
||||
meta.file_creation_time = file.file_creation_time;
|
||||
meta.epoch_number = file.epoch_number;
|
||||
meta.file_checksum = file.file_checksum;
|
||||
@@ -459,7 +469,7 @@ Status CompactionServiceCompactionJob::Run() {
|
||||
MakeTableFileName(meta.fd.GetNumber()), meta.fd.GetFileSize(),
|
||||
meta.fd.smallest_seqno, meta.fd.largest_seqno,
|
||||
meta.smallest.Encode().ToString(), meta.largest.Encode().ToString(),
|
||||
meta.oldest_ancester_time, meta.file_creation_time, meta.epoch_number,
|
||||
meta.oldest_ancestor_time, meta.file_creation_time, meta.epoch_number,
|
||||
meta.file_checksum, meta.file_checksum_func_name,
|
||||
output_file.validator.GetHash(), meta.marked_for_compaction,
|
||||
meta.unique_id, *output_file.table_properties,
|
||||
@@ -555,6 +565,14 @@ static std::unordered_map<std::string, OptionTypeInfo> cs_input_type_info = {
|
||||
{offsetof(struct CompactionServiceInput, options_file_number),
|
||||
OptionType::kUInt64T, OptionVerificationType::kNormal,
|
||||
OptionTypeFlags::kNone}},
|
||||
{"min_manifest_file_number",
|
||||
{offsetof(struct CompactionServiceInput, min_manifest_file_number),
|
||||
OptionType::kUInt64T, OptionVerificationType::kNormal,
|
||||
OptionTypeFlags::kNone}},
|
||||
{"min_manifest_file_size",
|
||||
{offsetof(struct CompactionServiceInput, min_manifest_file_size),
|
||||
OptionType::kUInt64T, OptionVerificationType::kNormal,
|
||||
OptionTypeFlags::kNone}},
|
||||
};
|
||||
|
||||
static std::unordered_map<std::string, OptionTypeInfo>
|
||||
@@ -583,8 +601,9 @@ static std::unordered_map<std::string, OptionTypeInfo>
|
||||
{offsetof(struct CompactionServiceOutputFile, largest_internal_key),
|
||||
OptionType::kEncodedString, OptionVerificationType::kNormal,
|
||||
OptionTypeFlags::kNone}},
|
||||
// Misspelled key kept for compatibility with other versions
|
||||
{"oldest_ancester_time",
|
||||
{offsetof(struct CompactionServiceOutputFile, oldest_ancester_time),
|
||||
{offsetof(struct CompactionServiceOutputFile, oldest_ancestor_time),
|
||||
OptionType::kUInt64T, OptionVerificationType::kNormal,
|
||||
OptionTypeFlags::kNone}},
|
||||
{"file_creation_time",
|
||||
@@ -902,24 +921,11 @@ 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<
|
||||
int, static_cast<int>(CompactionReason::kNumOfReasons) - 1>(
|
||||
offsetof(struct InternalStats::CompactionStats, counts),
|
||||
OptionVerificationType::kNormal, OptionTypeFlags::kNone,
|
||||
{0, OptionType::kInt})},
|
||||
{"counts", SizeTolerantDeserializeArray<
|
||||
int, static_cast<int>(CompactionReason::kNumOfReasons)>(
|
||||
offsetof(struct InternalStats::CompactionStats, counts),
|
||||
OptionVerificationType::kNormal, OptionTypeFlags::kNone,
|
||||
{0, OptionType::kInt})},
|
||||
};
|
||||
|
||||
static std::unordered_map<std::string, OptionTypeInfo>
|
||||
@@ -1066,9 +1072,19 @@ Status CompactionServiceInput::Read(const std::string& data_str,
|
||||
ConfigOptions cf;
|
||||
cf.invoke_prepare_options = false;
|
||||
cf.ignore_unknown_options = true;
|
||||
return OptionTypeInfo::ParseType(
|
||||
Status s = OptionTypeInfo::ParseType(
|
||||
cf, data_str.substr(sizeof(BinaryFormatVersion)), cs_input_type_info,
|
||||
obj);
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
for (size_t i = 1; i < obj->snapshots.size(); ++i) {
|
||||
if (obj->snapshots[i - 1] >= obj->snapshots[i]) {
|
||||
return Status::InvalidArgument(
|
||||
"CompactionServiceInput snapshots must be strictly increasing");
|
||||
}
|
||||
}
|
||||
return Status::OK();
|
||||
} else {
|
||||
return Status::NotSupported(
|
||||
"Compaction Service Input data version not supported: " +
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -68,11 +68,11 @@ class FileTtlBooster {
|
||||
if (!enabled_) {
|
||||
return 1;
|
||||
}
|
||||
uint64_t oldest_ancester_time = f->TryGetOldestAncesterTime();
|
||||
if (oldest_ancester_time >= current_time_) {
|
||||
uint64_t oldest_ancestor_time = f->TryGetOldestAncestorTime();
|
||||
if (oldest_ancestor_time >= current_time_) {
|
||||
return 1;
|
||||
}
|
||||
uint64_t age = current_time_ - oldest_ancester_time;
|
||||
uint64_t age = current_time_ - oldest_ancestor_time;
|
||||
if (age > boost_age_start_) {
|
||||
// Use integer just for convenience.
|
||||
// We could make all file_to_order double if we want.
|
||||
|
||||
@@ -25,6 +25,18 @@ SstPartitionerFixedPrefixFactory::SstPartitionerFixedPrefixFactory(size_t len)
|
||||
RegisterOptions("Length", &len_, &sst_fixed_prefix_type_info);
|
||||
}
|
||||
|
||||
OptSlice SstPartitionerFixedPrefix::ShouldPartitionByPrefix(
|
||||
const Slice& user_key) {
|
||||
if (user_key.size() >= len_) {
|
||||
return {user_key.data(), len_};
|
||||
} else {
|
||||
// ShouldPartition() cuts a partition for EVERY UNIQUE KEY outside the
|
||||
// prefix length domain, for better or worse. We can't directly represent
|
||||
// that so we defer to ShouldPartition().
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
PartitionerResult SstPartitionerFixedPrefix::ShouldPartition(
|
||||
const PartitionerRequest& request) {
|
||||
Slice last_key_fixed(*request.prev_user_key);
|
||||
|
||||
@@ -1339,9 +1339,13 @@ TEST_F(TieredCompactionTest, SequenceBasedTieredStorageLevel) {
|
||||
// This test was essentially for a hacked-up version on future functionality.
|
||||
// It can be resurrected if/when a form of range-based tiering is properly
|
||||
// implemented.
|
||||
// FIXME: aside from that, this test reproduces a near-endless compaction
|
||||
// cycle that needs to be reproduced independently and fixed before
|
||||
// leveled compaction can be used with the preclude feature in production.
|
||||
// The near-endless compaction cycle this used to reproduce (a bottommost file
|
||||
// whose seqno could not be zeroed within the preserve window being re-marked
|
||||
// forever) is now prevented by sharing the seqno-zeroability decision between
|
||||
// the compaction output path and bottommost-file marking (see
|
||||
// BottommostSeqnoCanBeZeroed and CompactionPickerTest.BottommostFile*
|
||||
// PreserveWindow). This test remains disabled only because range-based tiering
|
||||
// is not implemented.
|
||||
TEST_F(TieredCompactionTest, DISABLED_RangeBasedTieredStorageLevel) {
|
||||
const int kNumTrigger = 4;
|
||||
const int kNumLevels = 7;
|
||||
@@ -1558,6 +1562,188 @@ class PrecludeLastLevelTest : public PrecludeLastLevelTestBase,
|
||||
}
|
||||
};
|
||||
|
||||
// Regression test for an infinite kBottommostFiles compaction loop on a
|
||||
// leveled column family that has the seqno->time preserve feature enabled. A
|
||||
// bottommost file whose largest sequence number is still within the preserve
|
||||
// window cannot have its seqno zeroed by compaction, so it must not be marked
|
||||
// for bottommost compaction; otherwise each rewrite makes no progress and the
|
||||
// file is re-marked forever. This exercises the DBImpl plumbing that feeds
|
||||
// VersionStorageInfo::preserve_time_min_seqno_ (DBImpl::
|
||||
// MaybeUpdatePreserveTimeMinSeqno) end to end, complementing the isolated
|
||||
// marking-predicate coverage in compaction_picker_test.cc.
|
||||
class PrecludeBottommostLoopTest : public PrecludeLastLevelTestBase {};
|
||||
|
||||
TEST_F(PrecludeBottommostLoopTest, LeveledPreserveTimeNoBottommostLoop) {
|
||||
const int kNumLevels = 7;
|
||||
Options options = CurrentOptions();
|
||||
options.compaction_style = kCompactionStyleLevel;
|
||||
options.preserve_internal_time_seconds = 10000;
|
||||
options.env = mock_env_.get();
|
||||
options.num_levels = kNumLevels;
|
||||
// Prevent the extra L0 file below from auto-triggering an L0 compaction.
|
||||
options.level0_file_num_compaction_trigger = 4;
|
||||
SyncPoint::GetInstance()->EnableProcessing();
|
||||
DestroyAndReopen(options);
|
||||
|
||||
// Populate the seqno->time mapping with recent samples so the preserve window
|
||||
// maps the file's (recent) largest seqno as non-zeroable. Total elapsed mock
|
||||
// time stays far below preserve_internal_time_seconds, so nothing ages out.
|
||||
for (int i = 0; i < 10; i++) {
|
||||
ASSERT_OK(Put("infinite", "v" + std::to_string(i)));
|
||||
dbfull()->TEST_WaitForPeriodicTaskRun(
|
||||
[&] { mock_clock_->MockSleepForSeconds(10); });
|
||||
}
|
||||
ASSERT_OK(Flush());
|
||||
// Push the file with the hot key down to the bottommost level.
|
||||
MoveFilesToLevel(kNumLevels - 1);
|
||||
ASSERT_EQ(1, NumTableFilesAtLevel(kNumLevels - 1));
|
||||
|
||||
// Confirm the bottommost file's largest seqno was not zeroed (it is within
|
||||
// the preserve window), so it is a genuine marking candidate that only the
|
||||
// preserve-window guard should protect -- this keeps the test from passing
|
||||
// vacuously.
|
||||
{
|
||||
std::vector<LiveFileMetaData> files;
|
||||
db_->GetLiveFilesMetaData(&files);
|
||||
bool found_bottommost = false;
|
||||
for (const auto& f : files) {
|
||||
if (f.level == kNumLevels - 1) {
|
||||
ASSERT_GT(f.largest_seqno, 0U);
|
||||
found_bottommost = true;
|
||||
}
|
||||
}
|
||||
ASSERT_TRUE(found_bottommost);
|
||||
}
|
||||
|
||||
// Bump the sequence number above the bottommost file so that releasing a
|
||||
// snapshot advances oldest_snapshot_seqnum_ past the file's largest seqno,
|
||||
// which makes the file a candidate for bottommost marking (the snapshot gate
|
||||
// passes). Only the preserve-window guard should keep it from being marked.
|
||||
ASSERT_OK(Put("bumpseqnum", ""));
|
||||
ASSERT_OK(Flush());
|
||||
|
||||
std::atomic<int> bottommost_compactions{0};
|
||||
SyncPoint::GetInstance()->SetCallBack(
|
||||
"LevelCompactionPicker::PickCompaction:Return", [&](void* arg) {
|
||||
auto* c = static_cast<Compaction*>(arg);
|
||||
if (c != nullptr &&
|
||||
c->compaction_reason() == CompactionReason::kBottommostFiles) {
|
||||
bottommost_compactions.fetch_add(1);
|
||||
}
|
||||
});
|
||||
|
||||
const Snapshot* snapshot = db_->GetSnapshot();
|
||||
db_->ReleaseSnapshot(snapshot);
|
||||
|
||||
// The bottommost file's largest seqno is within the preserve window, so it is
|
||||
// not marked and the DB quiesces. Before the fix the file was marked and the
|
||||
// rewrite re-qualified it forever (this wait would hang).
|
||||
ASSERT_OK(dbfull()->TEST_WaitForCompact());
|
||||
ASSERT_EQ(0, bottommost_compactions.load());
|
||||
|
||||
SyncPoint::GetInstance()->DisableProcessing();
|
||||
SyncPoint::GetInstance()->ClearAllCallBacks();
|
||||
// Close explicitly because mock_env_ is destroyed before the DB otherwise.
|
||||
Close();
|
||||
}
|
||||
|
||||
// Regression test for the empty-mapping variant of the same loop: a bottommost
|
||||
// file that predates a preserve/preclude rollout has an EMPTY persisted
|
||||
// seqno->time mapping. Once the live, DB-wide mapping ages the file out of the
|
||||
// preserve window, the marker (which reads the live mapping) marks it. The
|
||||
// compaction that rewrites it must use the same version-carried preserve
|
||||
// boundary rather than the file's own empty mapping; otherwise it computes
|
||||
// preserve_seqno_after_ = 0, zeroes nothing, and re-marks the file forever.
|
||||
// With the fix the file's seqno is zeroed in one bounded compaction.
|
||||
TEST_F(PrecludeBottommostLoopTest, EmptyMappingAgedOutNoBottommostLoop) {
|
||||
const int kNumLevels = 7;
|
||||
Options options = CurrentOptions();
|
||||
options.compaction_style = kCompactionStyleLevel;
|
||||
options.env = mock_env_.get();
|
||||
options.num_levels = kNumLevels;
|
||||
options.level0_file_num_compaction_trigger = 4;
|
||||
// Start with preserve/preclude disabled so the bottommost file below is
|
||||
// written with an EMPTY persisted seqno->time mapping, mimicking a file that
|
||||
// predates a preserve/preclude rollout.
|
||||
options.preserve_internal_time_seconds = 0;
|
||||
options.preclude_last_level_data_seconds = 0;
|
||||
SyncPoint::GetInstance()->EnableProcessing();
|
||||
DestroyAndReopen(options);
|
||||
|
||||
// Hold a snapshot below the "aged" key so moving it to the bottommost level
|
||||
// does not zero its seqno (there is no preserve window yet to protect it).
|
||||
ASSERT_OK(Put("keeplow", "v"));
|
||||
const Snapshot* protect = db_->GetSnapshot();
|
||||
ASSERT_OK(Put("aged", "v"));
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(kNumLevels - 1);
|
||||
ASSERT_EQ(1, NumTableFilesAtLevel(kNumLevels - 1));
|
||||
|
||||
SequenceNumber aged_seqno = 0;
|
||||
{
|
||||
std::vector<LiveFileMetaData> files;
|
||||
db_->GetLiveFilesMetaData(&files);
|
||||
for (const auto& f : files) {
|
||||
if (f.level == kNumLevels - 1) {
|
||||
aged_seqno = f.largest_seqno;
|
||||
}
|
||||
}
|
||||
}
|
||||
ASSERT_GT(aged_seqno, 0U);
|
||||
|
||||
// Roll out the preserve feature dynamically and let the live, DB-wide
|
||||
// seqno->time mapping accumulate samples while mock time advances well past
|
||||
// preserve_internal_time_seconds, so the pre-existing file's seqno ages out
|
||||
// of the preserve window per the live mapping (even though the file's own
|
||||
// persisted mapping is empty). The protecting snapshot keeps the file from
|
||||
// being marked during this loop (oldest_snapshot_seqnum_ stays below it).
|
||||
ASSERT_OK(db_->SetOptions({{"preserve_internal_time_seconds", "10000"}}));
|
||||
for (int i = 0; i < 100; i++) {
|
||||
ASSERT_OK(Put("hot", "v" + std::to_string(i)));
|
||||
dbfull()->TEST_WaitForPeriodicTaskRun(
|
||||
[&] { mock_clock_->MockSleepForSeconds(200); });
|
||||
}
|
||||
|
||||
std::atomic<int> bottommost_compactions{0};
|
||||
SyncPoint::GetInstance()->SetCallBack(
|
||||
"LevelCompactionPicker::PickCompaction:Return", [&](void* arg) {
|
||||
auto* c = static_cast<Compaction*>(arg);
|
||||
if (c != nullptr &&
|
||||
c->compaction_reason() == CompactionReason::kBottommostFiles) {
|
||||
bottommost_compactions.fetch_add(1);
|
||||
}
|
||||
});
|
||||
|
||||
// Release the protecting snapshot so oldest_snapshot_seqnum_ advances past
|
||||
// the file's largest seqno, making it a bottommost marking candidate. The
|
||||
// marker (using the live mapping) marks it; the compaction that rewrites it
|
||||
// must use the same version-carried preserve boundary (not the file's empty
|
||||
// mapping) to actually zero the seqno, otherwise it makes no progress and
|
||||
// loops.
|
||||
db_->ReleaseSnapshot(protect);
|
||||
|
||||
// With the fix the file's seqno is zeroed in a bounded number of bottommost
|
||||
// compactions and the DB quiesces. Before the fix this wait would hang.
|
||||
ASSERT_OK(dbfull()->TEST_WaitForCompact());
|
||||
|
||||
{
|
||||
std::vector<LiveFileMetaData> files;
|
||||
db_->GetLiveFilesMetaData(&files);
|
||||
for (const auto& f : files) {
|
||||
if (f.level == kNumLevels - 1) {
|
||||
ASSERT_EQ(0U, f.largest_seqno);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The file was genuinely marked and rewritten (not vacuously skipped), and
|
||||
// the rewrite made progress instead of looping.
|
||||
ASSERT_GE(bottommost_compactions.load(), 1);
|
||||
|
||||
SyncPoint::GetInstance()->DisableProcessing();
|
||||
SyncPoint::GetInstance()->ClearAllCallBacks();
|
||||
Close();
|
||||
}
|
||||
|
||||
TEST_P(PrecludeLastLevelTest, MigrationFromPreserveTimeManualCompaction) {
|
||||
const int kNumTrigger = 4;
|
||||
const int kNumLevels = 7;
|
||||
|
||||
+366
@@ -0,0 +1,366 @@
|
||||
// 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 <utility>
|
||||
#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 "rocksdb/sst_file_reader.h"
|
||||
#include "table/multiget_context.h"
|
||||
#include "table/sst_file_reader_impl.h"
|
||||
#include "util/coro_stats_util.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();
|
||||
CoroutineStatsConfig stats_config = CaptureAndDisableCoroutineStatsConfig();
|
||||
|
||||
Status status;
|
||||
if (coro_db == nullptr || read_event_base == nullptr) {
|
||||
CoroutineStatsContextScope stats_scope(std::move(stats_config),
|
||||
db->GetEnv());
|
||||
status = db->Get(options, column_family, key, value, timestamp);
|
||||
} else {
|
||||
auto task = [](CoroutineStatsConfig task_stats_config, Env* task_env,
|
||||
CoroDB* task_db, const ReadOptions& task_options,
|
||||
ColumnFamilyHandle* task_column_family, Slice task_key,
|
||||
PinnableSlice* task_value,
|
||||
std::string* task_timestamp) -> folly::coro::Task<Status> {
|
||||
CoroutineStatsContextScope stats_scope(std::move(task_stats_config),
|
||||
task_env);
|
||||
co_return co_await folly::coro::co_nothrow(
|
||||
task_db->GetCoroutine(task_options, task_column_family, task_key,
|
||||
task_value, task_timestamp));
|
||||
}(std::move(stats_config), db->GetEnv(), coro_db, options, column_family,
|
||||
key, value, timestamp);
|
||||
status = co_await folly::coro::co_nothrow(folly::coro::co_withExecutor(
|
||||
folly::Executor::getKeepAliveToken(read_event_base), std::move(task)));
|
||||
}
|
||||
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<Status> CoroDB::CoGet(SstFileReader* reader,
|
||||
const ReadOptions& options,
|
||||
const Slice& key,
|
||||
PinnableSlice* value) {
|
||||
assert(reader != nullptr);
|
||||
SstFileReader::Rep* rep = reader->rep_.get();
|
||||
auto* read_executor = rep->read_executor;
|
||||
auto* read_event_base =
|
||||
read_executor == nullptr ? nullptr : read_executor->getEventBase();
|
||||
CoroutineStatsConfig stats_config = CaptureAndDisableCoroutineStatsConfig();
|
||||
|
||||
Status status;
|
||||
if (read_event_base == nullptr) {
|
||||
CoroutineStatsContextScope stats_scope(std::move(stats_config),
|
||||
rep->options.env);
|
||||
status = reader->Get(options, key, value);
|
||||
} else {
|
||||
auto task = [](CoroutineStatsConfig task_stats_config, Env* task_env,
|
||||
SstFileReader* task_reader, const ReadOptions& task_options,
|
||||
Slice task_key,
|
||||
PinnableSlice* task_value) -> folly::coro::Task<Status> {
|
||||
CoroutineStatsContextScope stats_scope(std::move(task_stats_config),
|
||||
task_env);
|
||||
co_return co_await folly::coro::co_nothrow(
|
||||
task_reader->rep_->GetCoroutine(task_options, task_key, task_value));
|
||||
}(std::move(stats_config), rep->options.env, reader, options, key, value);
|
||||
status = co_await folly::coro::co_nothrow(folly::coro::co_withExecutor(
|
||||
folly::Executor::getKeepAliveToken(read_event_base), std::move(task)));
|
||||
}
|
||||
co_return status;
|
||||
}
|
||||
|
||||
folly::coro::Task<Status> CoroDB::CoGet(SstFileReader* reader,
|
||||
const ReadOptions& options,
|
||||
const Slice& key, std::string* value) {
|
||||
assert(value != nullptr);
|
||||
PinnableSlice pinnable_value(value);
|
||||
assert(!pinnable_value.IsPinned());
|
||||
Status status = co_await folly::coro::co_nothrow(
|
||||
CoGet(reader, options, key, &pinnable_value));
|
||||
if (status.ok() && pinnable_value.IsPinned()) {
|
||||
value->assign(pinnable_value.data(), pinnable_value.size());
|
||||
}
|
||||
co_return status;
|
||||
}
|
||||
|
||||
folly::coro::Task<Status> CoroDB::CoGetEntity(DB* db,
|
||||
const ReadOptions& options,
|
||||
ColumnFamilyHandle* column_family,
|
||||
const Slice& key,
|
||||
PinnableWideColumns* columns) {
|
||||
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();
|
||||
CoroutineStatsConfig stats_config = CaptureAndDisableCoroutineStatsConfig();
|
||||
|
||||
Status status;
|
||||
if (coro_db == nullptr || read_event_base == nullptr) {
|
||||
CoroutineStatsContextScope stats_scope(std::move(stats_config),
|
||||
db->GetEnv());
|
||||
status = db->GetEntity(options, column_family, key, columns);
|
||||
} else {
|
||||
auto task =
|
||||
[](CoroutineStatsConfig task_stats_config, Env* task_env,
|
||||
CoroDB* task_db, const ReadOptions& task_options,
|
||||
ColumnFamilyHandle* task_column_family, Slice task_key,
|
||||
PinnableWideColumns* task_columns) -> folly::coro::Task<Status> {
|
||||
CoroutineStatsContextScope stats_scope(std::move(task_stats_config),
|
||||
task_env);
|
||||
co_return co_await folly::coro::co_nothrow(task_db->GetEntityCoroutine(
|
||||
task_options, task_column_family, task_key, task_columns));
|
||||
}(std::move(stats_config), db->GetEnv(), coro_db, options, column_family,
|
||||
key, columns);
|
||||
status = co_await folly::coro::co_nothrow(folly::coro::co_withExecutor(
|
||||
folly::Executor::getKeepAliveToken(read_event_base), std::move(task)));
|
||||
}
|
||||
co_return status;
|
||||
}
|
||||
|
||||
folly::coro::Task<Status> CoroDB::CoGetEntity(DB* db,
|
||||
const ReadOptions& options,
|
||||
const Slice& key,
|
||||
PinnableWideColumns* columns) {
|
||||
assert(db != nullptr);
|
||||
return CoGetEntity(db, options, db->DefaultColumnFamily(), key, columns);
|
||||
}
|
||||
|
||||
folly::coro::Task<Status> CoroDB::CoGetEntity(DB* db,
|
||||
const ReadOptions& options,
|
||||
const Slice& key,
|
||||
PinnableAttributeGroups* result) {
|
||||
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();
|
||||
CoroutineStatsConfig stats_config = CaptureAndDisableCoroutineStatsConfig();
|
||||
|
||||
Status status;
|
||||
if (coro_db == nullptr || read_event_base == nullptr) {
|
||||
CoroutineStatsContextScope stats_scope(std::move(stats_config),
|
||||
db->GetEnv());
|
||||
status = db->GetEntity(options, key, result);
|
||||
} else {
|
||||
auto task =
|
||||
[](CoroutineStatsConfig task_stats_config, Env* task_env,
|
||||
CoroDB* task_db, const ReadOptions& task_options, Slice task_key,
|
||||
PinnableAttributeGroups* task_result) -> folly::coro::Task<Status> {
|
||||
CoroutineStatsContextScope stats_scope(std::move(task_stats_config),
|
||||
task_env);
|
||||
co_return co_await folly::coro::co_nothrow(
|
||||
task_db->GetEntityCoroutine(task_options, task_key, task_result));
|
||||
}(std::move(stats_config), db->GetEnv(), coro_db, options, key, result);
|
||||
status = co_await folly::coro::co_nothrow(folly::coro::co_withExecutor(
|
||||
folly::Executor::getKeepAliveToken(read_event_base), std::move(task)));
|
||||
}
|
||||
co_return status;
|
||||
}
|
||||
|
||||
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<std::vector<Status>> CoroDB::CoMultiGet(
|
||||
SstFileReader* reader, const ReadOptions& options,
|
||||
const std::vector<Slice>& keys, std::vector<PinnableSlice>* values) {
|
||||
assert(reader != nullptr);
|
||||
SstFileReader::Rep* rep = reader->rep_.get();
|
||||
auto* read_executor = rep->read_executor;
|
||||
auto* read_event_base =
|
||||
read_executor == nullptr ? nullptr : read_executor->getEventBase();
|
||||
CoroutineStatsConfig stats_config = CaptureAndDisableCoroutineStatsConfig();
|
||||
|
||||
std::vector<Status> statuses;
|
||||
if (read_event_base == nullptr) {
|
||||
CoroutineStatsContextScope stats_scope(std::move(stats_config),
|
||||
rep->options.env);
|
||||
statuses = reader->MultiGet(options, keys, values);
|
||||
} else {
|
||||
auto task = [](CoroutineStatsConfig task_stats_config, Env* task_env,
|
||||
SstFileReader* task_reader, const ReadOptions& task_options,
|
||||
const std::vector<Slice>& task_keys,
|
||||
std::vector<PinnableSlice>* task_values)
|
||||
-> folly::coro::Task<std::vector<Status>> {
|
||||
CoroutineStatsContextScope stats_scope(std::move(task_stats_config),
|
||||
task_env);
|
||||
co_return co_await folly::coro::co_nothrow(
|
||||
task_reader->rep_->MultiGetCoroutine(task_options, task_keys,
|
||||
task_values));
|
||||
}(std::move(stats_config), rep->options.env, reader, options, keys, values);
|
||||
statuses = co_await folly::coro::co_nothrow(folly::coro::co_withExecutor(
|
||||
folly::Executor::getKeepAliveToken(read_event_base), std::move(task)));
|
||||
}
|
||||
co_return statuses;
|
||||
}
|
||||
|
||||
folly::coro::Task<std::vector<Status>> CoroDB::CoMultiGet(
|
||||
SstFileReader* reader, const ReadOptions& options,
|
||||
const std::vector<Slice>& keys, std::vector<std::string>* values) {
|
||||
std::vector<PinnableSlice> pinnable_values;
|
||||
std::vector<Status> statuses = co_await folly::coro::co_nothrow(
|
||||
CoMultiGet(reader, options, keys, &pinnable_values));
|
||||
values->resize(keys.size());
|
||||
for (size_t i = 0; i < keys.size(); ++i) {
|
||||
if (statuses[i].ok()) {
|
||||
(*values)[i].assign(pinnable_values[i].data(), pinnable_values[i].size());
|
||||
}
|
||||
}
|
||||
co_return statuses;
|
||||
}
|
||||
|
||||
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();
|
||||
CoroutineStatsConfig stats_config = CaptureAndDisableCoroutineStatsConfig();
|
||||
|
||||
if (coro_db == nullptr || read_event_base == nullptr) {
|
||||
CoroutineStatsContextScope stats_scope(std::move(stats_config),
|
||||
db->GetEnv());
|
||||
db->MultiGet(options, num_keys, column_families, keys, values, timestamps,
|
||||
statuses, sorted_input);
|
||||
} else {
|
||||
auto task = [](CoroutineStatsConfig task_stats_config, Env* task_env,
|
||||
CoroDB* task_db, const ReadOptions& task_options,
|
||||
size_t task_num_keys,
|
||||
ColumnFamilyHandle** task_column_families,
|
||||
const Slice* task_keys, PinnableSlice* task_values,
|
||||
std::string* task_timestamps, Status* task_statuses,
|
||||
bool task_sorted_input) -> folly::coro::Task<void> {
|
||||
CoroutineStatsContextScope stats_scope(std::move(task_stats_config),
|
||||
task_env);
|
||||
co_await folly::coro::co_nothrow(task_db->MultiGetCoroutine(
|
||||
task_options, task_num_keys, task_column_families, task_keys,
|
||||
task_values, task_timestamps, task_statuses, task_sorted_input));
|
||||
}(std::move(stats_config), db->GetEnv(), coro_db, options, num_keys,
|
||||
column_families, keys, values,
|
||||
timestamps, statuses, sorted_input);
|
||||
co_await folly::coro::co_nothrow(folly::coro::co_withExecutor(
|
||||
folly::Executor::getKeepAliveToken(read_event_base), std::move(task)));
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
+770
-35
@@ -11,6 +11,7 @@
|
||||
|
||||
#include "db/db_test_util.h"
|
||||
#include "db/log_writer.h"
|
||||
#include "db/manifest_ops.h"
|
||||
#include "db/version_edit.h"
|
||||
#include "file/writable_file_writer.h"
|
||||
#include "options/options_helper.h"
|
||||
@@ -20,10 +21,14 @@
|
||||
#include "rocksdb/merge_operator.h"
|
||||
#include "rocksdb/perf_context.h"
|
||||
#include "rocksdb/table.h"
|
||||
#include "rocksdb/utilities/checkpoint.h"
|
||||
#include "rocksdb/utilities/debug.h"
|
||||
#include "rocksdb/write_buffer_manager.h"
|
||||
#include "table/block_based/block_based_table_reader.h"
|
||||
#include "table/block_based/block_builder.h"
|
||||
#include "table/format.h"
|
||||
#include "test_util/sync_point.h"
|
||||
#include "util/defer.h"
|
||||
#include "util/file_checksum_helper.h"
|
||||
#include "util/random.h"
|
||||
#include "utilities/counted_fs.h"
|
||||
@@ -34,6 +39,19 @@
|
||||
|
||||
namespace ROCKSDB_NAMESPACE {
|
||||
namespace {
|
||||
|
||||
OutputMetadata NewerVersionOutputMetadata() {
|
||||
OutputMetadata output_metadata;
|
||||
output_metadata.WantNewerVersionPresent();
|
||||
return output_metadata;
|
||||
}
|
||||
|
||||
MultiGetOutputMetadata NewerVersionMultiGetOutputMetadata() {
|
||||
MultiGetOutputMetadata output_metadata;
|
||||
output_metadata.WantNewerVersionPresent();
|
||||
return output_metadata;
|
||||
}
|
||||
|
||||
class MyFlushBlockPolicy : public FlushBlockPolicy {
|
||||
public:
|
||||
explicit MyFlushBlockPolicy(const int num_keys_in_block,
|
||||
@@ -141,6 +159,7 @@ struct RecoveryOptimizationCounters {
|
||||
sp->ClearAllCallBacks();
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
// optimize_manifest_for_recovery=true: a clean reopen of a flushed DB must
|
||||
@@ -351,6 +370,82 @@ TEST_F(DBBasicTest,
|
||||
synthetic_number);
|
||||
}
|
||||
|
||||
TEST_F(DBBasicTest,
|
||||
OptimizeManifestForRecoveryKeepsCurrentOptionsFileWithStaleOptions) {
|
||||
Options options = CurrentOptions();
|
||||
options.create_if_missing = true;
|
||||
options.optimize_manifest_for_recovery = true;
|
||||
options.avoid_unnecessary_blocking_io = false;
|
||||
DestroyAndReopen(options);
|
||||
ASSERT_OK(Put("k", "v"));
|
||||
ASSERT_OK(Flush());
|
||||
|
||||
const uint64_t next_before_close =
|
||||
dbfull()->GetVersionSet()->current_next_file_number();
|
||||
Close();
|
||||
|
||||
const uint64_t stale_options_number = next_before_close + 100;
|
||||
ASSERT_OK(WriteStringToFile(
|
||||
env_, "" /*data*/, dbname_ + "/" + OptionsFileName(stale_options_number),
|
||||
/*should_sync=*/true));
|
||||
ASSERT_OK(WriteStringToFile(
|
||||
env_, "" /*data*/,
|
||||
dbname_ + "/" + OptionsFileName(stale_options_number + 1),
|
||||
/*should_sync=*/true));
|
||||
|
||||
RecoveryOptimizationCounters counters;
|
||||
counters.Install();
|
||||
Reopen(options);
|
||||
counters.Uninstall();
|
||||
|
||||
const uint64_t current_options_number =
|
||||
dbfull()->GetVersionSet()->options_file_number();
|
||||
ASSERT_EQ(1, counters.next_file_number.load());
|
||||
ASSERT_GT(dbfull()->GetVersionSet()->current_next_file_number(),
|
||||
stale_options_number + 1);
|
||||
ASSERT_GT(current_options_number, 0u);
|
||||
ASSERT_OK(env_->FileExists(OptionsFileName(dbname_, current_options_number)));
|
||||
|
||||
const std::string checkpoint_dir = dbname_ + "_checkpoint";
|
||||
ASSERT_OK(DestroyDir(env_, checkpoint_dir));
|
||||
Checkpoint* checkpoint = nullptr;
|
||||
ASSERT_OK(Checkpoint::Create(db_.get(), &checkpoint));
|
||||
std::unique_ptr<Checkpoint> checkpoint_guard(checkpoint);
|
||||
ASSERT_OK(checkpoint_guard->CreateCheckpoint(checkpoint_dir));
|
||||
ASSERT_OK(DestroyDir(env_, checkpoint_dir));
|
||||
ASSERT_EQ("v", Get("k"));
|
||||
}
|
||||
|
||||
TEST_F(DBBasicTest,
|
||||
OptimizeManifestForRecoveryReservesTempOptionsFileNumbersInMemory) {
|
||||
Options options = CurrentOptions();
|
||||
options.create_if_missing = true;
|
||||
options.optimize_manifest_for_recovery = true;
|
||||
DestroyAndReopen(options);
|
||||
ASSERT_OK(Put("k", "v"));
|
||||
ASSERT_OK(Flush());
|
||||
|
||||
const uint64_t next_before_close =
|
||||
dbfull()->GetVersionSet()->current_next_file_number();
|
||||
Close();
|
||||
|
||||
const uint64_t stale_temp_options_number = next_before_close + 100;
|
||||
ASSERT_OK(
|
||||
WriteStringToFile(env_, "" /*data*/,
|
||||
TempOptionsFileName(dbname_, stale_temp_options_number),
|
||||
/*should_sync=*/true));
|
||||
|
||||
RecoveryOptimizationCounters counters;
|
||||
counters.Install();
|
||||
Reopen(options);
|
||||
counters.Uninstall();
|
||||
|
||||
ASSERT_EQ(1, counters.next_file_number.load());
|
||||
ASSERT_GT(dbfull()->GetVersionSet()->current_next_file_number(),
|
||||
stale_temp_options_number);
|
||||
ASSERT_EQ("v", Get("k"));
|
||||
}
|
||||
|
||||
// optimize_manifest_for_recovery=true: after a clean Put + Flush + Close, the
|
||||
// next Open's min_log_number_to_keep equals (max_wal_before_close + 1),
|
||||
// proving the close-time MANIFEST write took effect.
|
||||
@@ -978,27 +1073,19 @@ TEST_F(DBBasicTest, WritableFileWriterInitialFileSizeAdoptsExistingSize) {
|
||||
TEST_F(DBBasicTest, ReuseManifestOnOpenSkipsOnTailCorruption) {
|
||||
Options options = CurrentOptions();
|
||||
options.create_if_missing = true;
|
||||
options.optimize_manifest_for_recovery = true;
|
||||
options.reuse_manifest_on_open = true;
|
||||
options.write_dbid_to_manifest = false;
|
||||
DestroyAndReopen(options);
|
||||
ASSERT_OK(Put("k", "v"));
|
||||
ASSERT_OK(Flush());
|
||||
Close();
|
||||
|
||||
// Find the MANIFEST file and append garbage to it.
|
||||
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());
|
||||
uint64_t manifest_file_number = 0;
|
||||
ASSERT_OK(GetCurrentManifestPath(dbname_, env_->GetFileSystem().get(),
|
||||
/*is_retry=*/false, &manifest_path,
|
||||
&manifest_file_number));
|
||||
{
|
||||
std::string contents;
|
||||
ASSERT_OK(ReadFileToString(env_, manifest_path, &contents));
|
||||
@@ -1007,9 +1094,13 @@ TEST_F(DBBasicTest, ReuseManifestOnOpenSkipsOnTailCorruption) {
|
||||
}
|
||||
|
||||
std::atomic<int> reopened{0};
|
||||
std::atomic<int> new_manifest{0};
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
|
||||
"VersionSet::ReopenManifestForAppend:Reopened",
|
||||
[&](void* /*arg*/) { reopened.fetch_add(1); });
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
|
||||
"VersionSet::ProcessManifestWrites:BeforeNewManifest",
|
||||
[&](void* /*arg*/) { new_manifest.fetch_add(1); });
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
|
||||
|
||||
Reopen(options);
|
||||
@@ -1018,6 +1109,12 @@ TEST_F(DBBasicTest, ReuseManifestOnOpenSkipsOnTailCorruption) {
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearAllCallBacks();
|
||||
|
||||
ASSERT_EQ(0, reopened.load());
|
||||
ASSERT_EQ(1, new_manifest.load());
|
||||
std::string manifest_path_after;
|
||||
ASSERT_OK(GetCurrentManifestPath(dbname_, env_->GetFileSystem().get(),
|
||||
/*is_retry=*/false, &manifest_path_after,
|
||||
&manifest_file_number));
|
||||
ASSERT_NE(manifest_path, manifest_path_after);
|
||||
ASSERT_EQ("v", Get("k"));
|
||||
}
|
||||
|
||||
@@ -1030,27 +1127,19 @@ TEST_F(DBBasicTest, ReuseManifestOnOpenSkipsOnTailCorruption) {
|
||||
TEST_F(DBBasicTest, ReuseManifestOnOpenIncompleteAtomicGroupAtTail) {
|
||||
Options options = CurrentOptions();
|
||||
options.create_if_missing = true;
|
||||
options.optimize_manifest_for_recovery = true;
|
||||
options.reuse_manifest_on_open = true;
|
||||
options.write_dbid_to_manifest = false;
|
||||
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());
|
||||
uint64_t manifest_file_number = 0;
|
||||
ASSERT_OK(GetCurrentManifestPath(dbname_, env_->GetFileSystem().get(),
|
||||
/*is_retry=*/false, &manifest_path,
|
||||
&manifest_file_number));
|
||||
|
||||
// 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
|
||||
@@ -1088,11 +1177,29 @@ TEST_F(DBBasicTest, ReuseManifestOnOpenIncompleteAtomicGroupAtTail) {
|
||||
// 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).
|
||||
std::atomic<int> reopened{0};
|
||||
std::atomic<int> new_manifest{0};
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
|
||||
"VersionSet::ReopenManifestForAppend:Reopened",
|
||||
[&](void* /*arg*/) { reopened.fetch_add(1); });
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
|
||||
"VersionSet::ProcessManifestWrites:BeforeNewManifest",
|
||||
[&](void* /*arg*/) { new_manifest.fetch_add(1); });
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
|
||||
|
||||
// Reopen: recovery should succeed, but ReopenManifestForAppend must not
|
||||
// reuse a MANIFEST ending with an incomplete atomic group.
|
||||
Reopen(options);
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->DisableProcessing();
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->ClearAllCallBacks();
|
||||
|
||||
ASSERT_EQ(0, reopened.load());
|
||||
ASSERT_EQ(1, new_manifest.load());
|
||||
std::string manifest_path_after;
|
||||
ASSERT_OK(GetCurrentManifestPath(dbname_, env_->GetFileSystem().get(),
|
||||
/*is_retry=*/false, &manifest_path_after,
|
||||
&manifest_file_number));
|
||||
ASSERT_NE(manifest_path, manifest_path_after);
|
||||
ASSERT_EQ("v", Get("k"));
|
||||
|
||||
// Write new data to create new MANIFEST records.
|
||||
@@ -1228,6 +1335,24 @@ TEST_F(DBBasicTest, ReadOnlyDB) {
|
||||
ASSERT_OK(EnforcedReadOnlyReopen(options));
|
||||
ASSERT_EQ("v3", Get("foo"));
|
||||
ASSERT_EQ("v2", Get("bar"));
|
||||
std::string metadata_value;
|
||||
ReadOptions metadata_read_options;
|
||||
OutputMetadata output_metadata = NewerVersionOutputMetadata();
|
||||
ASSERT_OK(db_->GetWithMetadata(metadata_read_options, "foo", &metadata_value,
|
||||
&output_metadata));
|
||||
ASSERT_EQ("v3", metadata_value);
|
||||
ASSERT_FALSE(*output_metadata.newer_version_present);
|
||||
std::vector<Slice> metadata_keys{Slice("foo")};
|
||||
std::vector<std::string> metadata_values;
|
||||
MultiGetOutputMetadata multiget_output_metadata =
|
||||
NewerVersionMultiGetOutputMetadata();
|
||||
std::vector<Status> metadata_statuses =
|
||||
db_->MultiGetWithMetadata(metadata_read_options, metadata_keys,
|
||||
&metadata_values, &multiget_output_metadata);
|
||||
ASSERT_EQ(1, metadata_statuses.size());
|
||||
ASSERT_OK(metadata_statuses[0]);
|
||||
ASSERT_EQ("v3", metadata_values[0]);
|
||||
ASSERT_FALSE((*multiget_output_metadata.newer_version_present)[0]);
|
||||
verify_all_iters();
|
||||
ASSERT_EQ(db_->SyncWAL().code(), Status::Code::kNotSupported);
|
||||
|
||||
@@ -1409,6 +1534,35 @@ TEST_F(DBBasicTest, CompactedDB) {
|
||||
ASSERT_EQ(DummyString(kFileSize / 2, 'j'), Get("jjj"));
|
||||
ASSERT_EQ("NOT_FOUND", Get("kkk"));
|
||||
|
||||
std::string metadata_value;
|
||||
ReadOptions metadata_read_options;
|
||||
const Snapshot* metadata_snapshot = db_->GetSnapshot();
|
||||
metadata_read_options.snapshot = metadata_snapshot;
|
||||
OutputMetadata output_metadata = NewerVersionOutputMetadata();
|
||||
ASSERT_OK(db_->GetWithMetadata(metadata_read_options, "aaa", &metadata_value,
|
||||
&output_metadata));
|
||||
ASSERT_EQ(DummyString(kFileSize / 2, 'a'), metadata_value);
|
||||
ASSERT_FALSE(*output_metadata.newer_version_present);
|
||||
std::vector<Slice> metadata_keys{Slice("aaa"), Slice("ccc")};
|
||||
std::vector<std::string> metadata_values;
|
||||
MultiGetOutputMetadata multiget_output_metadata =
|
||||
NewerVersionMultiGetOutputMetadata();
|
||||
std::vector<Status> metadata_statuses =
|
||||
db_->MultiGetWithMetadata(metadata_read_options, metadata_keys,
|
||||
&metadata_values, &multiget_output_metadata);
|
||||
ASSERT_EQ(metadata_keys.size(), metadata_statuses.size());
|
||||
ASSERT_OK(metadata_statuses[0]);
|
||||
ASSERT_EQ(DummyString(kFileSize / 2, 'a'), metadata_values[0]);
|
||||
ASSERT_FALSE((*multiget_output_metadata.newer_version_present)[0]);
|
||||
ASSERT_TRUE(metadata_statuses[1].IsNotFound());
|
||||
ASSERT_FALSE((*multiget_output_metadata.newer_version_present)[1]);
|
||||
db_->ReleaseSnapshot(metadata_snapshot);
|
||||
|
||||
ASSERT_TRUE(db_->GetWithMetadata(ReadOptions(), db_->DefaultColumnFamily(),
|
||||
"aaa", static_cast<PinnableSlice*>(nullptr),
|
||||
&output_metadata)
|
||||
.IsInvalidArgument());
|
||||
|
||||
// TODO: validate that other write ops return NotImplemented
|
||||
// (CompactedDB is missing some overrides)
|
||||
|
||||
@@ -1596,6 +1750,430 @@ TEST_P(DBBasicGetWithParam, GetSnapshot) {
|
||||
} while (ChangeOptions());
|
||||
}
|
||||
|
||||
TEST_F(DBBasicTest, GetNewerVersionPresent) {
|
||||
// Snapshot reads report later point and range-delete writes without changing
|
||||
// the snapshot-visible value.
|
||||
Options options = CurrentOptions();
|
||||
options.merge_operator = MergeOperators::CreateStringAppendOperator();
|
||||
CreateAndReopenWithCF({"pikachu"}, options);
|
||||
|
||||
ASSERT_OK(Put(1, "key", "v1"));
|
||||
ASSERT_OK(Put(1, "merge_key", "base"));
|
||||
ASSERT_OK(Put(1, "stable", "s1"));
|
||||
ASSERT_OK(Put(1, "range_key", "r1"));
|
||||
const Snapshot* snapshot = db_->GetSnapshot();
|
||||
|
||||
ReadOptions snapshot_read;
|
||||
snapshot_read.snapshot = snapshot;
|
||||
|
||||
std::string value;
|
||||
OutputMetadata output_metadata = NewerVersionOutputMetadata();
|
||||
ASSERT_OK(db_->GetWithMetadata(snapshot_read, handles_[1], "key", &value,
|
||||
&output_metadata));
|
||||
ASSERT_EQ("v1", value);
|
||||
ASSERT_FALSE(*output_metadata.newer_version_present);
|
||||
|
||||
ASSERT_OK(Put(1, "other", "v2"));
|
||||
ASSERT_OK(Put(1, "created_after_put", "new"));
|
||||
ASSERT_OK(Merge(1, "created_after_merge", "new"));
|
||||
ASSERT_OK(
|
||||
db_->DeleteRange(WriteOptions(), handles_[1], "range_key", "range_key~"));
|
||||
ASSERT_OK(Merge(1, "merge_key", "new"));
|
||||
value.clear();
|
||||
*output_metadata.newer_version_present = true;
|
||||
ASSERT_OK(db_->GetWithMetadata(snapshot_read, handles_[1], "stable", &value,
|
||||
&output_metadata));
|
||||
ASSERT_EQ("s1", value);
|
||||
ASSERT_FALSE(*output_metadata.newer_version_present);
|
||||
|
||||
value.clear();
|
||||
*output_metadata.newer_version_present = true;
|
||||
ASSERT_TRUE(db_->GetWithMetadata(snapshot_read, handles_[1],
|
||||
"created_after_put", &value,
|
||||
&output_metadata)
|
||||
.IsNotFound());
|
||||
ASSERT_TRUE(*output_metadata.newer_version_present);
|
||||
|
||||
value.clear();
|
||||
*output_metadata.newer_version_present = false;
|
||||
ASSERT_TRUE(db_->GetWithMetadata(snapshot_read, handles_[1],
|
||||
"created_after_merge", &value,
|
||||
&output_metadata)
|
||||
.IsNotFound());
|
||||
ASSERT_TRUE(*output_metadata.newer_version_present);
|
||||
|
||||
value.clear();
|
||||
*output_metadata.newer_version_present = false;
|
||||
ASSERT_OK(db_->GetWithMetadata(snapshot_read, handles_[1], "range_key",
|
||||
&value, &output_metadata));
|
||||
ASSERT_EQ("r1", value);
|
||||
ASSERT_TRUE(*output_metadata.newer_version_present);
|
||||
|
||||
value.clear();
|
||||
*output_metadata.newer_version_present = false;
|
||||
ASSERT_OK(db_->GetWithMetadata(snapshot_read, handles_[1], "merge_key",
|
||||
&value, &output_metadata));
|
||||
ASSERT_EQ("base", value);
|
||||
ASSERT_TRUE(*output_metadata.newer_version_present);
|
||||
|
||||
ASSERT_OK(Put(1, "key", "v2"));
|
||||
value.clear();
|
||||
ASSERT_OK(db_->GetWithMetadata(snapshot_read, handles_[1], "key", &value,
|
||||
&output_metadata));
|
||||
ASSERT_EQ("v1", value);
|
||||
ASSERT_TRUE(*output_metadata.newer_version_present);
|
||||
|
||||
ASSERT_OK(Flush(1));
|
||||
value.clear();
|
||||
*output_metadata.newer_version_present = false;
|
||||
ASSERT_OK(db_->GetWithMetadata(snapshot_read, handles_[1], "key", &value,
|
||||
&output_metadata));
|
||||
ASSERT_EQ("v1", value);
|
||||
ASSERT_TRUE(*output_metadata.newer_version_present);
|
||||
|
||||
value.clear();
|
||||
*output_metadata.newer_version_present = false;
|
||||
ASSERT_OK(db_->GetWithMetadata(snapshot_read, handles_[1], "range_key",
|
||||
&value, &output_metadata));
|
||||
ASSERT_EQ("r1", value);
|
||||
ASSERT_TRUE(*output_metadata.newer_version_present);
|
||||
|
||||
ReadOptions latest_read;
|
||||
value.clear();
|
||||
*output_metadata.newer_version_present = true;
|
||||
ASSERT_OK(db_->GetWithMetadata(latest_read, handles_[1], "key", &value,
|
||||
&output_metadata));
|
||||
ASSERT_EQ("v2", value);
|
||||
ASSERT_FALSE(*output_metadata.newer_version_present);
|
||||
|
||||
db_->ReleaseSnapshot(snapshot);
|
||||
}
|
||||
|
||||
TEST_F(DBBasicTest, NewerVersionPresentRequestedByOutputMetadata) {
|
||||
// Newer-version tracking is opt-in through OutputMetadata and
|
||||
// MultiGetOutputMetadata.
|
||||
Options options = CurrentOptions();
|
||||
CreateAndReopenWithCF({"pikachu"}, options);
|
||||
|
||||
ASSERT_OK(Put(1, "key", "old"));
|
||||
const Snapshot* snapshot = db_->GetSnapshot();
|
||||
ASSERT_OK(Put(1, "key", "new"));
|
||||
|
||||
ReadOptions read_options;
|
||||
read_options.snapshot = snapshot;
|
||||
|
||||
std::string value;
|
||||
OutputMetadata output_metadata = NewerVersionOutputMetadata();
|
||||
ASSERT_OK(db_->GetWithMetadata(read_options, handles_[1], "key", &value,
|
||||
&output_metadata));
|
||||
ASSERT_EQ("old", value);
|
||||
ASSERT_TRUE(*output_metadata.newer_version_present);
|
||||
|
||||
std::vector<Slice> keys{"key"};
|
||||
std::vector<ColumnFamilyHandle*> cfs(keys.size(), handles_[1]);
|
||||
std::vector<std::string> values;
|
||||
MultiGetOutputMetadata multiget_output_metadata =
|
||||
NewerVersionMultiGetOutputMetadata();
|
||||
std::vector<Status> statuses = db_->MultiGetWithMetadata(
|
||||
read_options, cfs, keys, &values, &multiget_output_metadata);
|
||||
ASSERT_EQ(1, statuses.size());
|
||||
ASSERT_OK(statuses[0]);
|
||||
ASSERT_EQ("old", values[0]);
|
||||
ASSERT_EQ(1, multiget_output_metadata.newer_version_present->size());
|
||||
ASSERT_TRUE((*multiget_output_metadata.newer_version_present)[0]);
|
||||
|
||||
db_->ReleaseSnapshot(snapshot);
|
||||
}
|
||||
|
||||
TEST_F(DBBasicTest, NewerVersionPresentIgnoreRangeDeletions) {
|
||||
// ignore_range_deletions affects the returned value, not newer-version
|
||||
// metadata about covering range tombstones.
|
||||
Options options = CurrentOptions();
|
||||
CreateAndReopenWithCF({"pikachu"}, options);
|
||||
|
||||
ASSERT_OK(Put(1, "range_key", "old"));
|
||||
const Snapshot* snapshot = db_->GetSnapshot();
|
||||
ASSERT_OK(
|
||||
db_->DeleteRange(WriteOptions(), handles_[1], "range_key", "range_key~"));
|
||||
|
||||
ReadOptions read_options;
|
||||
read_options.snapshot = snapshot;
|
||||
read_options.ignore_range_deletions = true;
|
||||
|
||||
std::string value;
|
||||
OutputMetadata output_metadata = NewerVersionOutputMetadata();
|
||||
ASSERT_OK(db_->GetWithMetadata(read_options, handles_[1], "range_key", &value,
|
||||
&output_metadata));
|
||||
ASSERT_EQ("old", value);
|
||||
ASSERT_TRUE(*output_metadata.newer_version_present);
|
||||
|
||||
std::vector<Slice> keys{"range_key"};
|
||||
std::vector<ColumnFamilyHandle*> cfs(keys.size(), handles_[1]);
|
||||
std::vector<std::string> values;
|
||||
MultiGetOutputMetadata multiget_output_metadata =
|
||||
NewerVersionMultiGetOutputMetadata();
|
||||
std::vector<Status> statuses = db_->MultiGetWithMetadata(
|
||||
read_options, cfs, keys, &values, &multiget_output_metadata);
|
||||
ASSERT_EQ(1, statuses.size());
|
||||
ASSERT_OK(statuses[0]);
|
||||
ASSERT_EQ("old", values[0]);
|
||||
ASSERT_TRUE((*multiget_output_metadata.newer_version_present)[0]);
|
||||
|
||||
ASSERT_OK(Flush(1));
|
||||
value.clear();
|
||||
*output_metadata.newer_version_present = false;
|
||||
ASSERT_OK(db_->GetWithMetadata(read_options, handles_[1], "range_key", &value,
|
||||
&output_metadata));
|
||||
ASSERT_EQ("old", value);
|
||||
ASSERT_TRUE(*output_metadata.newer_version_present);
|
||||
|
||||
values.clear();
|
||||
multiget_output_metadata.newer_version_present->clear();
|
||||
statuses = db_->MultiGetWithMetadata(read_options, cfs, keys, &values,
|
||||
&multiget_output_metadata);
|
||||
ASSERT_EQ(1, statuses.size());
|
||||
ASSERT_OK(statuses[0]);
|
||||
ASSERT_EQ("old", values[0]);
|
||||
ASSERT_TRUE((*multiget_output_metadata.newer_version_present)[0]);
|
||||
|
||||
db_->ReleaseSnapshot(snapshot);
|
||||
}
|
||||
|
||||
TEST_F(DBBasicTest, NewerVersionPresentFromImmutableMemTable) {
|
||||
Options options = CurrentOptions();
|
||||
CreateAndReopenWithCF({"pikachu"}, options);
|
||||
|
||||
ASSERT_OK(Put(1, "point_key", "old_point"));
|
||||
ASSERT_OK(Put(1, "range_key", "old_range"));
|
||||
ManagedSnapshot snapshot(db_.get());
|
||||
|
||||
ASSERT_OK(Put(1, "point_key", "new_point"));
|
||||
ASSERT_OK(
|
||||
db_->DeleteRange(WriteOptions(), handles_[1], "range_key", "range_key~"));
|
||||
|
||||
auto* cfd =
|
||||
static_cast_with_check<ColumnFamilyHandleImpl>(handles_[1])->cfd();
|
||||
Status resume_status;
|
||||
{
|
||||
ASSERT_OK(db_->PauseBackgroundWork());
|
||||
Defer resume_background(
|
||||
[&] { resume_status = db_->ContinueBackgroundWork(); });
|
||||
ASSERT_OK(dbfull()->TEST_SwitchMemtable(cfd));
|
||||
|
||||
ReadOptions read_options;
|
||||
read_options.snapshot = snapshot.snapshot();
|
||||
|
||||
std::string value;
|
||||
OutputMetadata output_metadata = NewerVersionOutputMetadata();
|
||||
ASSERT_OK(db_->GetWithMetadata(read_options, handles_[1], "point_key",
|
||||
&value, &output_metadata));
|
||||
ASSERT_EQ("old_point", value);
|
||||
ASSERT_TRUE(*output_metadata.newer_version_present);
|
||||
|
||||
value.clear();
|
||||
*output_metadata.newer_version_present = false;
|
||||
ASSERT_OK(db_->GetWithMetadata(read_options, handles_[1], "range_key",
|
||||
&value, &output_metadata));
|
||||
ASSERT_EQ("old_range", value);
|
||||
ASSERT_TRUE(*output_metadata.newer_version_present);
|
||||
|
||||
std::vector<Slice> keys{"point_key", "range_key"};
|
||||
std::vector<ColumnFamilyHandle*> cfs(keys.size(), handles_[1]);
|
||||
std::vector<std::string> values;
|
||||
MultiGetOutputMetadata multiget_output_metadata =
|
||||
NewerVersionMultiGetOutputMetadata();
|
||||
const std::vector<Status> statuses = db_->MultiGetWithMetadata(
|
||||
read_options, cfs, keys, &values, &multiget_output_metadata);
|
||||
ASSERT_EQ(2, statuses.size());
|
||||
ASSERT_OK(statuses[0]);
|
||||
ASSERT_OK(statuses[1]);
|
||||
ASSERT_EQ(std::vector<std::string>({"old_point", "old_range"}), values);
|
||||
ASSERT_TRUE((*multiget_output_metadata.newer_version_present)[0]);
|
||||
ASSERT_TRUE((*multiget_output_metadata.newer_version_present)[1]);
|
||||
}
|
||||
ASSERT_OK(resume_status);
|
||||
ASSERT_OK(Flush(1));
|
||||
}
|
||||
|
||||
TEST_F(DBBasicTest, NewerVersionPresentBypassesRowCacheWhileTracking) {
|
||||
// Prime row-cache entries for the snapshot values, then verify metadata
|
||||
// reads still inspect SST sequence numbers instead of replaying those
|
||||
// entries.
|
||||
option_config_ = kRowCache;
|
||||
Options options = CurrentOptions();
|
||||
options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
|
||||
CreateAndReopenWithCF({"pikachu"}, options);
|
||||
|
||||
ASSERT_OK(Put(1, "get_key", "old_get"));
|
||||
ASSERT_OK(Put(1, "multiget_key", "old_multiget"));
|
||||
ASSERT_OK(Flush(1));
|
||||
ManagedSnapshot snapshot(db_.get());
|
||||
ASSERT_OK(Put(1, "get_key", "new_get"));
|
||||
ASSERT_OK(Put(1, "multiget_key", "new_multiget"));
|
||||
ASSERT_OK(Flush(1));
|
||||
|
||||
ReadOptions read_options;
|
||||
read_options.snapshot = snapshot.snapshot();
|
||||
|
||||
std::string primed_value;
|
||||
ASSERT_OK(db_->Get(read_options, handles_[1], "get_key", &primed_value));
|
||||
ASSERT_EQ("old_get", primed_value);
|
||||
std::vector<Slice> primed_keys{"multiget_key"};
|
||||
std::vector<ColumnFamilyHandle*> primed_cfs(primed_keys.size(), handles_[1]);
|
||||
std::vector<std::string> primed_values;
|
||||
const std::vector<Status> primed_statuses =
|
||||
db_->MultiGet(read_options, primed_cfs, primed_keys, &primed_values);
|
||||
ASSERT_OK(primed_statuses[0]);
|
||||
ASSERT_EQ("old_multiget", primed_values[0]);
|
||||
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
SCOPED_TRACE(i);
|
||||
std::string value;
|
||||
OutputMetadata output_metadata = NewerVersionOutputMetadata();
|
||||
ASSERT_OK(db_->GetWithMetadata(read_options, handles_[1], "get_key", &value,
|
||||
&output_metadata));
|
||||
ASSERT_EQ("old_get", value);
|
||||
ASSERT_TRUE(*output_metadata.newer_version_present);
|
||||
}
|
||||
|
||||
std::vector<Slice> keys{"multiget_key"};
|
||||
std::vector<ColumnFamilyHandle*> cfs(keys.size(), handles_[1]);
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
SCOPED_TRACE(i);
|
||||
std::vector<std::string> values;
|
||||
MultiGetOutputMetadata multiget_output_metadata =
|
||||
NewerVersionMultiGetOutputMetadata();
|
||||
std::vector<Status> statuses = db_->MultiGetWithMetadata(
|
||||
read_options, cfs, keys, &values, &multiget_output_metadata);
|
||||
ASSERT_EQ(1, statuses.size());
|
||||
ASSERT_OK(statuses[0]);
|
||||
ASSERT_EQ("old_multiget", values[0]);
|
||||
ASSERT_TRUE((*multiget_output_metadata.newer_version_present)[0]);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(DBBasicTest, NewerVersionPresentUsesRowCacheAfterObservation) {
|
||||
option_config_ = kRowCache;
|
||||
Options options = CurrentOptions();
|
||||
options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
|
||||
CreateAndReopenWithCF({"pikachu"}, options);
|
||||
|
||||
ASSERT_OK(Put(1, "key", "old"));
|
||||
ASSERT_OK(Flush(1));
|
||||
ManagedSnapshot snapshot(db_.get());
|
||||
|
||||
ReadOptions read_options;
|
||||
read_options.snapshot = snapshot.snapshot();
|
||||
std::vector<Slice> keys{"key"};
|
||||
std::vector<ColumnFamilyHandle*> cfs(keys.size(), handles_[1]);
|
||||
std::vector<std::string> values;
|
||||
std::vector<Status> statuses =
|
||||
db_->MultiGet(read_options, cfs, keys, &values);
|
||||
ASSERT_OK(statuses[0]);
|
||||
ASSERT_EQ("old", values[0]);
|
||||
|
||||
ASSERT_OK(Put(1, "key", "new"));
|
||||
const uint64_t row_cache_hits = TestGetTickerCount(options, ROW_CACHE_HIT);
|
||||
|
||||
values.clear();
|
||||
MultiGetOutputMetadata output_metadata = NewerVersionMultiGetOutputMetadata();
|
||||
statuses = db_->MultiGetWithMetadata(read_options, cfs, keys, &values,
|
||||
&output_metadata);
|
||||
ASSERT_OK(statuses[0]);
|
||||
ASSERT_EQ("old", values[0]);
|
||||
ASSERT_TRUE((*output_metadata.newer_version_present)[0]);
|
||||
ASSERT_EQ(row_cache_hits + 1, TestGetTickerCount(options, ROW_CACHE_HIT));
|
||||
}
|
||||
|
||||
TEST_F(DBBasicTest, NewerVersionPresentPersistedTierNotSupported) {
|
||||
// kPersistedTier is incompatible with snapshot newer-version tracking but not
|
||||
// with untracked latest-version reads.
|
||||
Options options = CurrentOptions();
|
||||
CreateAndReopenWithCF({"pikachu"}, options);
|
||||
|
||||
ASSERT_OK(Put(1, "key", "old"));
|
||||
const Snapshot* snapshot = db_->GetSnapshot();
|
||||
ASSERT_OK(Put(1, "key", "new"));
|
||||
|
||||
ReadOptions read_options;
|
||||
read_options.snapshot = snapshot;
|
||||
read_options.read_tier = kPersistedTier;
|
||||
|
||||
std::string value;
|
||||
OutputMetadata output_metadata = NewerVersionOutputMetadata();
|
||||
ASSERT_TRUE(db_->GetWithMetadata(read_options, handles_[1], "key", &value,
|
||||
&output_metadata)
|
||||
.IsNotSupported());
|
||||
|
||||
std::vector<Slice> keys{"key"};
|
||||
std::vector<ColumnFamilyHandle*> cfs(keys.size(), handles_[1]);
|
||||
std::vector<std::string> values;
|
||||
MultiGetOutputMetadata multiget_output_metadata =
|
||||
NewerVersionMultiGetOutputMetadata();
|
||||
std::vector<Status> statuses = db_->MultiGetWithMetadata(
|
||||
read_options, cfs, keys, &values, &multiget_output_metadata);
|
||||
ASSERT_EQ(1, statuses.size());
|
||||
ASSERT_TRUE(statuses[0].IsNotSupported());
|
||||
ASSERT_FALSE((*multiget_output_metadata.newer_version_present)[0]);
|
||||
|
||||
read_options.snapshot = nullptr;
|
||||
value.clear();
|
||||
*output_metadata.newer_version_present = true;
|
||||
ASSERT_OK(db_->GetWithMetadata(read_options, handles_[1], "key", &value,
|
||||
&output_metadata));
|
||||
ASSERT_EQ("new", value);
|
||||
ASSERT_FALSE(*output_metadata.newer_version_present);
|
||||
|
||||
values.clear();
|
||||
multiget_output_metadata.newer_version_present->clear();
|
||||
statuses = db_->MultiGetWithMetadata(read_options, cfs, keys, &values,
|
||||
&multiget_output_metadata);
|
||||
ASSERT_EQ(1, statuses.size());
|
||||
ASSERT_OK(statuses[0]);
|
||||
ASSERT_EQ("new", values[0]);
|
||||
ASSERT_FALSE((*multiget_output_metadata.newer_version_present)[0]);
|
||||
|
||||
db_->ReleaseSnapshot(snapshot);
|
||||
}
|
||||
|
||||
TEST_F(DBBasicTest, ReadOnlyNewerVersionPresentReturnsFalse) {
|
||||
// Read-only DBs do not widen snapshot reads, so requested metadata remains
|
||||
// false.
|
||||
Options options = CurrentOptions();
|
||||
CreateAndReopenWithCF({"pikachu"}, options);
|
||||
|
||||
ASSERT_OK(Put(1, "key", "value"));
|
||||
ASSERT_OK(Flush(1));
|
||||
ASSERT_OK(
|
||||
TryReopenReadOnlyWithColumnFamilies({"default", "pikachu"}, options));
|
||||
|
||||
const Snapshot* snapshot = db_->GetSnapshot();
|
||||
ReadOptions read_options;
|
||||
read_options.snapshot = snapshot;
|
||||
|
||||
std::string value;
|
||||
OutputMetadata output_metadata = NewerVersionOutputMetadata();
|
||||
ASSERT_OK(db_->GetWithMetadata(read_options, handles_[1], "key", &value,
|
||||
&output_metadata));
|
||||
ASSERT_EQ("value", value);
|
||||
ASSERT_FALSE(*output_metadata.newer_version_present);
|
||||
|
||||
std::vector<Slice> keys{"key"};
|
||||
std::vector<ColumnFamilyHandle*> cfs(keys.size(), handles_[1]);
|
||||
std::vector<std::string> values;
|
||||
MultiGetOutputMetadata multiget_output_metadata =
|
||||
NewerVersionMultiGetOutputMetadata();
|
||||
std::vector<Status> statuses = db_->MultiGetWithMetadata(
|
||||
read_options, cfs, keys, &values, &multiget_output_metadata);
|
||||
ASSERT_EQ(1, statuses.size());
|
||||
ASSERT_OK(statuses[0]);
|
||||
ASSERT_EQ("value", values[0]);
|
||||
ASSERT_EQ(1, multiget_output_metadata.newer_version_present->size());
|
||||
ASSERT_FALSE((*multiget_output_metadata.newer_version_present)[0]);
|
||||
|
||||
db_->ReleaseSnapshot(snapshot);
|
||||
}
|
||||
|
||||
TEST_F(DBBasicTest, CheckLock) {
|
||||
do {
|
||||
std::unique_ptr<DB> localdb;
|
||||
@@ -2188,6 +2766,151 @@ TEST_F(DBBasicTest, MultiGetSimple) {
|
||||
} while (ChangeCompactOptions());
|
||||
}
|
||||
|
||||
TEST_F(DBBasicTest, MultiGetNewerVersionPresent) {
|
||||
// A mixed MultiGet batch reports newer writes independently for each key in
|
||||
// input order.
|
||||
Options options = CurrentOptions();
|
||||
options.merge_operator = MergeOperators::CreateStringAppendOperator();
|
||||
CreateAndReopenWithCF({"pikachu"}, options);
|
||||
|
||||
ASSERT_OK(Put(1, "updated", "old"));
|
||||
ASSERT_OK(Put(1, "unchanged", "same"));
|
||||
ASSERT_OK(Put(1, "deleted", "old"));
|
||||
ASSERT_OK(Put(1, "merged", "old"));
|
||||
ASSERT_OK(Put(1, "range_deleted", "old"));
|
||||
const Snapshot* snapshot = db_->GetSnapshot();
|
||||
|
||||
ASSERT_OK(Put(1, "updated", "new"));
|
||||
ASSERT_OK(Put(1, "created_after_put", "new"));
|
||||
ASSERT_OK(Merge(1, "created_after_merge", "new"));
|
||||
ASSERT_OK(Delete(1, "deleted"));
|
||||
ASSERT_OK(Merge(1, "merged", "new"));
|
||||
ASSERT_OK(db_->DeleteRange(WriteOptions(), handles_[1], "range_deleted",
|
||||
"range_deleted~"));
|
||||
|
||||
ReadOptions read_options;
|
||||
read_options.snapshot = snapshot;
|
||||
std::vector<Slice> keys({"updated", "unchanged", "deleted", "merged",
|
||||
"range_deleted", "created_after_put",
|
||||
"created_after_merge", "missing"});
|
||||
std::vector<ColumnFamilyHandle*> cfs(keys.size(), handles_[1]);
|
||||
std::vector<std::string> values;
|
||||
MultiGetOutputMetadata output_metadata = NewerVersionMultiGetOutputMetadata();
|
||||
|
||||
std::vector<Status> statuses = db_->MultiGetWithMetadata(
|
||||
read_options, cfs, keys, &values, &output_metadata);
|
||||
|
||||
ASSERT_EQ(keys.size(), statuses.size());
|
||||
ASSERT_OK(statuses[0]);
|
||||
ASSERT_EQ("old", values[0]);
|
||||
ASSERT_TRUE((*output_metadata.newer_version_present)[0]);
|
||||
|
||||
ASSERT_OK(statuses[1]);
|
||||
ASSERT_EQ("same", values[1]);
|
||||
ASSERT_FALSE((*output_metadata.newer_version_present)[1]);
|
||||
|
||||
ASSERT_OK(statuses[2]);
|
||||
ASSERT_EQ("old", values[2]);
|
||||
ASSERT_TRUE((*output_metadata.newer_version_present)[2]);
|
||||
|
||||
ASSERT_OK(statuses[3]);
|
||||
ASSERT_EQ("old", values[3]);
|
||||
ASSERT_TRUE((*output_metadata.newer_version_present)[3]);
|
||||
|
||||
ASSERT_OK(statuses[4]);
|
||||
ASSERT_EQ("old", values[4]);
|
||||
ASSERT_TRUE((*output_metadata.newer_version_present)[4]);
|
||||
|
||||
ASSERT_TRUE(statuses[5].IsNotFound());
|
||||
ASSERT_TRUE((*output_metadata.newer_version_present)[5]);
|
||||
|
||||
ASSERT_TRUE(statuses[6].IsNotFound());
|
||||
ASSERT_TRUE((*output_metadata.newer_version_present)[6]);
|
||||
|
||||
ASSERT_TRUE(statuses[7].IsNotFound());
|
||||
ASSERT_FALSE((*output_metadata.newer_version_present)[7]);
|
||||
|
||||
db_->ReleaseSnapshot(snapshot);
|
||||
}
|
||||
|
||||
TEST_F(DBBasicTest, MultiGetNewerVersionPresentAcrossColumnFamilies) {
|
||||
// Unsorted mixed-CF reads keep metadata aligned with input order after each
|
||||
// CF is processed independently.
|
||||
Options options = CurrentOptions();
|
||||
CreateAndReopenWithCF({"one", "two"}, options);
|
||||
|
||||
ASSERT_OK(Put(1, "updated_one", "old_one"));
|
||||
ASSERT_OK(Put(2, "updated_two", "old_two"));
|
||||
ASSERT_OK(Put(2, "stable_two", "stable"));
|
||||
const Snapshot* snapshot = db_->GetSnapshot();
|
||||
ASSERT_OK(Put(1, "updated_one", "new_one"));
|
||||
ASSERT_OK(Put(2, "updated_two", "new_two"));
|
||||
ASSERT_OK(Flush(1));
|
||||
ASSERT_OK(Flush(2));
|
||||
|
||||
ReadOptions read_options;
|
||||
read_options.snapshot = snapshot;
|
||||
std::vector<Slice> keys{"updated_two", "updated_one", "stable_two"};
|
||||
std::vector<ColumnFamilyHandle*> column_families{handles_[2], handles_[1],
|
||||
handles_[2]};
|
||||
std::vector<std::string> values;
|
||||
MultiGetOutputMetadata output_metadata = NewerVersionMultiGetOutputMetadata();
|
||||
const std::vector<Status> statuses = db_->MultiGetWithMetadata(
|
||||
read_options, column_families, keys, &values, &output_metadata);
|
||||
|
||||
for (const Status& status : statuses) {
|
||||
ASSERT_OK(status);
|
||||
}
|
||||
ASSERT_EQ(std::vector<std::string>({"old_two", "old_one", "stable"}), values);
|
||||
ASSERT_TRUE((*output_metadata.newer_version_present)[0]);
|
||||
ASSERT_TRUE((*output_metadata.newer_version_present)[1]);
|
||||
ASSERT_FALSE((*output_metadata.newer_version_present)[2]);
|
||||
|
||||
db_->ReleaseSnapshot(snapshot);
|
||||
}
|
||||
|
||||
TEST_F(DBBasicTest, MultiGetWithMetadataColumnFamiliesKeysSizeMismatch) {
|
||||
CreateAndReopenWithCF({"pikachu"}, CurrentOptions());
|
||||
|
||||
std::vector<Slice> keys({"k1", "k2"});
|
||||
std::vector<ColumnFamilyHandle*> cfs({handles_[1]});
|
||||
std::vector<std::string> values({"stale"});
|
||||
MultiGetOutputMetadata output_metadata;
|
||||
output_metadata.timestamps.emplace();
|
||||
output_metadata.newer_version_present = std::vector<uint8_t>({1});
|
||||
|
||||
std::vector<Status> statuses = db_->MultiGetWithMetadata(
|
||||
ReadOptions(), cfs, keys, &values, &output_metadata);
|
||||
|
||||
ASSERT_EQ(keys.size(), statuses.size());
|
||||
ASSERT_EQ(keys.size(), values.size());
|
||||
for (const Status& status : statuses) {
|
||||
ASSERT_TRUE(status.IsInvalidArgument());
|
||||
}
|
||||
ASSERT_EQ(keys.size(), output_metadata.timestamps->size());
|
||||
ASSERT_EQ(keys.size(), output_metadata.newer_version_present->size());
|
||||
ASSERT_FALSE((*output_metadata.newer_version_present)[0]);
|
||||
ASSERT_FALSE((*output_metadata.newer_version_present)[1]);
|
||||
}
|
||||
|
||||
TEST_F(DBBasicTest, GetWithMetadataNullValueInvalidArgument) {
|
||||
CreateAndReopenWithCF({"pikachu"}, CurrentOptions());
|
||||
|
||||
OutputMetadata output_metadata = NewerVersionOutputMetadata();
|
||||
ASSERT_TRUE(db_->GetWithMetadata(ReadOptions(), handles_[1], "key",
|
||||
static_cast<PinnableSlice*>(nullptr),
|
||||
&output_metadata)
|
||||
.IsInvalidArgument());
|
||||
ASSERT_FALSE(*output_metadata.newer_version_present);
|
||||
|
||||
*output_metadata.newer_version_present = true;
|
||||
ASSERT_TRUE(db_->GetWithMetadata(ReadOptions(), "key",
|
||||
static_cast<std::string*>(nullptr),
|
||||
&output_metadata)
|
||||
.IsInvalidArgument());
|
||||
ASSERT_FALSE(*output_metadata.newer_version_present);
|
||||
}
|
||||
|
||||
TEST_F(DBBasicTest, MultiGetEmpty) {
|
||||
do {
|
||||
CreateAndReopenWithCF({"pikachu"}, CurrentOptions());
|
||||
@@ -2227,6 +2950,9 @@ INSTANTIATE_TEST_CASE_P(FormatVersions, DBBlockChecksumTest,
|
||||
TEST_P(DBBlockChecksumTest, BlockChecksumTest) {
|
||||
BlockBasedTableOptions table_options;
|
||||
table_options.format_version = GetParam();
|
||||
// kFooterFormatVersionsToTest includes the unpublished draft format_version
|
||||
// 8; writing it requires this opt-in.
|
||||
SaveAndRestore<bool> allow_draft(&TEST_AllowUnsupportedFormatVersion(), true);
|
||||
Options options = CurrentOptions();
|
||||
const int kNumPerFile = 2;
|
||||
|
||||
@@ -4020,7 +4746,8 @@ TEST_P(DBMultiGetAsyncIOTest, GetFromL0) {
|
||||
AssertMultiGetIOBatchSize(3, 1);
|
||||
}
|
||||
#else // ROCKSDB_IOURING_PRESENT
|
||||
ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT), 0);
|
||||
ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT),
|
||||
UseCoroutineRead() ? 3 : 0);
|
||||
#endif // ROCKSDB_IOURING_PRESENT
|
||||
}
|
||||
|
||||
@@ -4047,7 +4774,8 @@ TEST_P(DBMultiGetAsyncIOTest, GetFromL1) {
|
||||
ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT),
|
||||
UseCoroutineRead() ? 6 : 3);
|
||||
#else // ROCKSDB_IOURING_PRESENT
|
||||
ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT), 0);
|
||||
ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT),
|
||||
UseCoroutineRead() ? 6 : 0);
|
||||
#endif // ROCKSDB_IOURING_PRESENT
|
||||
}
|
||||
|
||||
@@ -4200,7 +4928,8 @@ TEST_P(DBMultiGetAsyncIOTest, GetFromL2WithRangeOverlapL0L1) {
|
||||
ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT),
|
||||
UseCoroutineRead() ? 3 : 2);
|
||||
#else // ROCKSDB_IOURING_PRESENT
|
||||
ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT), 0);
|
||||
ASSERT_EQ(statistics()->getTickerCount(MULTIGET_COROUTINE_COUNT),
|
||||
UseCoroutineRead() ? 3 : 0);
|
||||
#endif // ROCKSDB_IOURING_PRESENT
|
||||
}
|
||||
|
||||
@@ -5039,6 +5768,9 @@ INSTANTIATE_TEST_CASE_P(BestEffortsRecoverIncompleteVersionTest,
|
||||
TEST_F(DBBasicTest, BestEffortsRecoveryTryMultipleManifests) {
|
||||
Options options = CurrentOptions();
|
||||
options.env = env_;
|
||||
options.write_buffer_manager = std::make_shared<WriteBufferManager>(
|
||||
64 << 20, nullptr /* cache */, false /* allow_stall */,
|
||||
WriteBufferFlushPolicy::kFlushLargestAcrossDBs);
|
||||
DestroyAndReopen(options);
|
||||
ASSERT_OK(Put("foo", "value0"));
|
||||
ASSERT_OK(Flush());
|
||||
@@ -5060,6 +5792,9 @@ TEST_F(DBBasicTest, BestEffortsRecoveryTryMultipleManifests) {
|
||||
|
||||
Reopen(options);
|
||||
ASSERT_OK(Put("bar", "value"));
|
||||
options.write_buffer_manager->TEST_RefreshFlushInitiatorCandidate();
|
||||
ASSERT_TRUE(
|
||||
options.write_buffer_manager->TEST_ScheduleFlushOnLargestDB(nullptr));
|
||||
}
|
||||
|
||||
TEST_F(DBBasicTest, RecoverWithNoCurrentFile) {
|
||||
|
||||
@@ -1800,6 +1800,7 @@ static std::map<TableFileCreationReason, std::string>
|
||||
{TableFileCreationReason::kFlush, "kFlush"},
|
||||
{TableFileCreationReason::kMisc, "kMisc"},
|
||||
{TableFileCreationReason::kRecovery, "kRecovery"},
|
||||
{TableFileCreationReason::kSstFileWriter, "kSstFileWriter"},
|
||||
};
|
||||
|
||||
class TestingContextCustomFilterPolicy
|
||||
@@ -1814,6 +1815,15 @@ 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];
|
||||
@@ -1836,8 +1846,13 @@ 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
|
||||
|
||||
@@ -1859,6 +1874,13 @@ 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++) {
|
||||
@@ -1867,17 +1889,13 @@ 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(),
|
||||
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");
|
||||
EXPECT_EQ(policy->DumpTestReport(), expected_flush_report);
|
||||
|
||||
for (int i = maxKey / 2; i < maxKey; i++) {
|
||||
ASSERT_OK(Put(1, Key(i), Key(i)));
|
||||
}
|
||||
ASSERT_OK(Flush(1));
|
||||
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");
|
||||
EXPECT_EQ(policy->DumpTestReport(), expected_flush_report);
|
||||
|
||||
// Check that they can be found
|
||||
for (int i = 0; i < maxKey; i++) {
|
||||
@@ -1904,7 +1922,8 @@ TEST_F(DBBloomFilterTest, ContextCustomFilterPolicy) {
|
||||
ASSERT_OK(db_->CompactRange(CompactRangeOptions(), handles_[1], nullptr,
|
||||
nullptr));
|
||||
EXPECT_EQ(policy->DumpTestReport(),
|
||||
"cf=bob,s=kCompactionStyleLevel,n=7,l=1,b=1,r=kCompaction\n");
|
||||
"cf=bob,db=expected,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++) {
|
||||
@@ -1926,7 +1945,8 @@ TEST_F(DBBloomFilterTest, ContextCustomFilterPolicy) {
|
||||
}
|
||||
// Note: kCompactionStyleLevel is default, ignored if num_levels == -1
|
||||
EXPECT_EQ(policy->DumpTestReport(),
|
||||
"cf=abe,s=kCompactionStyleLevel,n=-1,l=-1,b=0,r=kMisc\n");
|
||||
"cf=abe,db=none,s=kCompactionStyleLevel,n=-1,l=-1,b=0,r="
|
||||
"kSstFileWriter\n");
|
||||
}
|
||||
|
||||
// Destroy
|
||||
@@ -2522,9 +2542,13 @@ TEST_P(DBBloomFilterTestVaryPrefixAndFormatVer, PartitionedMultiGet) {
|
||||
values[i] = PinnableSlice();
|
||||
}
|
||||
|
||||
get_perf_context()->Reset();
|
||||
const PerfLevel previous_perf_level = GetPerfLevel();
|
||||
SetPerfLevel(PerfLevel::kEnableTime);
|
||||
db_->MultiGet(ropts, Q, column_families.data(), key_slices.data(),
|
||||
values.data(),
|
||||
/*timestamps=*/nullptr, statuses.data(), true);
|
||||
SetPerfLevel(previous_perf_level);
|
||||
|
||||
// Confirm correct status results
|
||||
uint32_t number_not_found = 0;
|
||||
@@ -2554,6 +2578,8 @@ TEST_P(DBBloomFilterTestVaryPrefixAndFormatVer, PartitionedMultiGet) {
|
||||
// Confirm no duplicate loading same filter partition
|
||||
uint64_t filter_accesses = PopTicker(options, BLOCK_CACHE_FILTER_HIT) +
|
||||
PopTicker(options, BLOCK_CACHE_FILTER_MISS);
|
||||
// Partition reads must contribute to the filter-block timing metric.
|
||||
EXPECT_GT(get_perf_context()->read_filter_block_nanos, 0);
|
||||
if (stride == 1) {
|
||||
EXPECT_EQ(filter_accesses, 1);
|
||||
} else {
|
||||
@@ -3978,7 +4004,8 @@ static std::vector<std::string> RangeQueryKeys(
|
||||
ReadOptions ro;
|
||||
ro.iterate_lower_bound = &lb;
|
||||
ro.iterate_upper_bound = &ub;
|
||||
ro.table_filter = factory.GetTableFilterForRangeQuery(lb, ub);
|
||||
auto filter = factory.GetTableFilterForRangeQuery(lb, ub);
|
||||
ro.table_filter = &filter;
|
||||
auto it = db.NewIterator(ro);
|
||||
std::vector<std::string> ret;
|
||||
for (it->Seek(lb); it->Valid(); it->Next()) {
|
||||
|
||||
@@ -3,8 +3,11 @@
|
||||
// COPYING file in the root directory) and Apache 2.0 License
|
||||
// (found in the LICENSE.Apache file in the root directory).
|
||||
|
||||
#include <atomic>
|
||||
|
||||
#include "db/db_test_util.h"
|
||||
#include "port/port.h"
|
||||
#include "test_util/sync_point.h"
|
||||
#include "util/random.h"
|
||||
|
||||
namespace ROCKSDB_NAMESPACE {
|
||||
@@ -14,6 +17,62 @@ class DBClipTest : public DBTestBase {
|
||||
DBClipTest() : DBTestBase("db_clip_test", /*env_do_fsync=*/true) {}
|
||||
};
|
||||
|
||||
// ClipColumnFamily reads the CF's boundary keys under the DB mutex, then drops
|
||||
// it and issues several writes with those keys. Those keys must not point into
|
||||
// Version-owned FileMetaData, which a background job can replace and free in
|
||||
// that window. Here a full compaction runs inside the window and obsoletes the
|
||||
// Version the keys were read from.
|
||||
TEST_F(DBClipTest, BoundaryKeysSurviveConcurrentVersionChange) {
|
||||
Options options = CurrentOptions();
|
||||
options.disable_auto_compactions = true;
|
||||
options.num_levels = 3;
|
||||
DestroyAndReopen(options);
|
||||
|
||||
Random rnd(301);
|
||||
std::map<int32_t, std::string> values;
|
||||
for (int i = 0; i < 10; i++) {
|
||||
for (int j = 0; j < 100; j++) {
|
||||
int k = i * 100 + j;
|
||||
values[k] = rnd.RandomString(1024);
|
||||
ASSERT_OK(Put(Key(k), values[k]));
|
||||
}
|
||||
ASSERT_OK(Flush());
|
||||
}
|
||||
|
||||
std::atomic<bool> fired{false};
|
||||
SyncPoint::GetInstance()->SetCallBack(
|
||||
"DBImpl::ClipColumnFamily:PostBoundaryKeys", [&](void*) {
|
||||
if (fired.exchange(true)) {
|
||||
return;
|
||||
}
|
||||
// Replace and free the Version the boundary keys were read from, on
|
||||
// another thread so this does not re-enter Clip's own call stack.
|
||||
port::Thread compactor([&] {
|
||||
ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
|
||||
ASSERT_OK(dbfull()->TEST_WaitForPurge());
|
||||
});
|
||||
compactor.join();
|
||||
});
|
||||
SyncPoint::GetInstance()->EnableProcessing();
|
||||
|
||||
const auto begin_key = Key(251);
|
||||
const auto end_key = Key(751);
|
||||
ASSERT_OK(
|
||||
db_->ClipColumnFamily(db_->DefaultColumnFamily(), begin_key, end_key));
|
||||
|
||||
SyncPoint::GetInstance()->DisableProcessing();
|
||||
SyncPoint::GetInstance()->ClearAllCallBacks();
|
||||
ASSERT_TRUE(fired.load());
|
||||
|
||||
for (int i = 251; i < 751; i++) {
|
||||
ASSERT_EQ(Get(Key(i)), values[i]);
|
||||
}
|
||||
for (int i : {0, 250, 751, 999}) {
|
||||
std::string result;
|
||||
ASSERT_TRUE(db_->Get(ReadOptions(), Key(i), &result).IsNotFound());
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(DBClipTest, TestClipRange) {
|
||||
Options options = CurrentOptions();
|
||||
options.write_buffer_size = 10 * 1024 * 1024;
|
||||
@@ -133,6 +192,28 @@ TEST_F(DBClipTest, TestClipRange) {
|
||||
ASSERT_TRUE(in_range);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(DBClipTest, KeepFileEndingAtBeginKey) {
|
||||
Options options = CurrentOptions();
|
||||
options.disable_auto_compactions = true;
|
||||
DestroyAndReopen(options);
|
||||
|
||||
ASSERT_OK(Put("a", "va"));
|
||||
ASSERT_OK(Put("b", "vb"));
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(1);
|
||||
ASSERT_OK(Put("c", "vc"));
|
||||
ASSERT_OK(Put("d", "vd"));
|
||||
ASSERT_OK(Flush());
|
||||
MoveFilesToLevel(1);
|
||||
ASSERT_EQ("0,2", FilesPerLevel(0));
|
||||
|
||||
ASSERT_OK(db_->ClipColumnFamily(db_->DefaultColumnFamily(), "b", "d"));
|
||||
ASSERT_EQ("NOT_FOUND", Get("a"));
|
||||
ASSERT_EQ("vb", Get("b"));
|
||||
ASSERT_EQ("vc", Get("c"));
|
||||
ASSERT_EQ("NOT_FOUND", Get("d"));
|
||||
}
|
||||
} // namespace ROCKSDB_NAMESPACE
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
// (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>
|
||||
@@ -14,6 +17,7 @@
|
||||
#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"
|
||||
@@ -91,6 +95,19 @@ 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.
|
||||
@@ -459,6 +476,483 @@ 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;
|
||||
|
||||
+335
-12
@@ -14,6 +14,7 @@
|
||||
#include "db/blob/blob_index.h"
|
||||
#include "db/db_test_util.h"
|
||||
#include "db/dbformat.h"
|
||||
#include "db/periodic_compaction_phaser.h"
|
||||
#include "db/table_cache.h"
|
||||
#include "env/mock_env.h"
|
||||
#include "file/filename.h"
|
||||
@@ -29,6 +30,8 @@
|
||||
#include "test_util/sync_point.h"
|
||||
#include "test_util/testutil.h"
|
||||
#include "util/concurrent_task_limiter_impl.h"
|
||||
#include "util/fastrange.h"
|
||||
#include "util/hash.h"
|
||||
#include "util/random.h"
|
||||
#include "utilities/fault_injection_env.h"
|
||||
#include "utilities/fault_injection_fs.h"
|
||||
@@ -813,6 +816,23 @@ 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) {
|
||||
@@ -838,6 +858,7 @@ 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
|
||||
@@ -1316,6 +1337,118 @@ TEST_F(DBCompactionTest, CompactionSstPartitionerNonTrivial) {
|
||||
ASSERT_EQ("B", Get("bbbb1"));
|
||||
}
|
||||
|
||||
TEST_F(DBCompactionTest, CompactionSstPartitionerPrefixFastPath) {
|
||||
// Exercises the ShouldPartitionByPrefix() fast path in CompactionOutputs:
|
||||
// multiple keys sharing a fixed prefix must stay together in one output file
|
||||
// (no spurious cuts), with boundaries landing exactly at prefix changes.
|
||||
Options options = CurrentOptions();
|
||||
options.compaction_style = kCompactionStyleLevel;
|
||||
options.level0_file_num_compaction_trigger = 3;
|
||||
options.sst_partitioner_factory = NewSstPartitionerFixedPrefixFactory(4);
|
||||
DestroyAndReopen(options);
|
||||
|
||||
// Three prefixes with multiple keys each, spread across two flushed files so
|
||||
// that a non-trivial compaction merges them.
|
||||
ASSERT_OK(Put("aaaa1", "v"));
|
||||
ASSERT_OK(Put("aaaa3", "v"));
|
||||
ASSERT_OK(Put("bbbb1", "v"));
|
||||
ASSERT_OK(Put("cccc2", "v"));
|
||||
ASSERT_OK(Flush());
|
||||
ASSERT_OK(dbfull()->TEST_WaitForFlushMemTable());
|
||||
|
||||
ASSERT_OK(Put("aaaa2", "v"));
|
||||
ASSERT_OK(Put("bbbb2", "v"));
|
||||
ASSERT_OK(Put("cccc1", "v"));
|
||||
ASSERT_OK(Flush());
|
||||
ASSERT_OK(dbfull()->TEST_WaitForFlushMemTable());
|
||||
|
||||
ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr));
|
||||
|
||||
// Exactly one output file per distinct 4-byte prefix.
|
||||
std::vector<LiveFileMetaData> files;
|
||||
dbfull()->GetLiveFilesMetaData(&files);
|
||||
ASSERT_EQ(3, files.size());
|
||||
// Each file holds a whole prefix group (multiple keys => the fast path
|
||||
// correctly did NOT cut within a shared prefix).
|
||||
for (const auto& f : files) {
|
||||
ASSERT_EQ(f.smallestkey.substr(0, 4), f.largestkey.substr(0, 4));
|
||||
}
|
||||
for (const std::string k :
|
||||
{"aaaa1", "aaaa2", "aaaa3", "bbbb1", "bbbb2", "cccc1", "cccc2"}) {
|
||||
ASSERT_EQ("v", Get(k));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(DBCompactionTest, CompactionSstPartitionerPrefixShortKeyFallback) {
|
||||
// Keys shorter than the fixed prefix length cannot be represented as a
|
||||
// prefix, so ShouldPartitionByPrefix() returns no value and CompactionOutputs
|
||||
// falls back to per-key ShouldPartition(). This also exercises short->long
|
||||
// and long->short mode transitions across output file boundaries.
|
||||
Options options = CurrentOptions();
|
||||
options.compaction_style = kCompactionStyleLevel;
|
||||
options.level0_file_num_compaction_trigger = 3;
|
||||
options.sst_partitioner_factory = NewSstPartitionerFixedPrefixFactory(4);
|
||||
DestroyAndReopen(options);
|
||||
|
||||
// "a" and "bb" are shorter than len 4 (fallback, each in its own file);
|
||||
// "cccc1"/"cccc2" share prefix "cccc" (fast path, one file); "dd" is short
|
||||
// again (fallback, own file).
|
||||
ASSERT_OK(Put("a", "v"));
|
||||
ASSERT_OK(Put("bb", "v"));
|
||||
ASSERT_OK(Put("cccc1", "v"));
|
||||
ASSERT_OK(Put("dd", "v"));
|
||||
ASSERT_OK(Flush());
|
||||
ASSERT_OK(dbfull()->TEST_WaitForFlushMemTable());
|
||||
|
||||
// Second file overlaps to force a non-trivial (rewriting) compaction.
|
||||
ASSERT_OK(Put("cccc2", "v"));
|
||||
ASSERT_OK(Put("a", "v2"));
|
||||
ASSERT_OK(Flush());
|
||||
ASSERT_OK(dbfull()->TEST_WaitForFlushMemTable());
|
||||
|
||||
ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr));
|
||||
|
||||
// "a" | "bb" | {"cccc1","cccc2"} | "dd" => 4 files.
|
||||
std::vector<LiveFileMetaData> files;
|
||||
dbfull()->GetLiveFilesMetaData(&files);
|
||||
ASSERT_EQ(4, files.size());
|
||||
ASSERT_EQ("v2", Get("a"));
|
||||
for (const std::string k : {"bb", "cccc1", "cccc2", "dd"}) {
|
||||
ASSERT_EQ("v", Get(k));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(DBCompactionTest, CompactionSstPartitionerZeroLenNoSplit) {
|
||||
// A zero-length fixed prefix yields an empty (but present) prefix from
|
||||
// ShouldPartitionByPrefix(), which means "no further partitions": every key
|
||||
// "starts with" the empty prefix, so the fast path never cuts.
|
||||
Options options = CurrentOptions();
|
||||
options.compaction_style = kCompactionStyleLevel;
|
||||
options.level0_file_num_compaction_trigger = 3;
|
||||
options.sst_partitioner_factory = NewSstPartitionerFixedPrefixFactory(0);
|
||||
DestroyAndReopen(options);
|
||||
|
||||
ASSERT_OK(Put("aaaa1", "v1"));
|
||||
ASSERT_OK(Put("bbbb1", "v1"));
|
||||
ASSERT_OK(Flush());
|
||||
ASSERT_OK(dbfull()->TEST_WaitForFlushMemTable());
|
||||
|
||||
// Overlapping key forces a non-trivial compaction (not a trivial move).
|
||||
ASSERT_OK(Put("aaaa1", "v2"));
|
||||
ASSERT_OK(Put("cccc1", "v2"));
|
||||
ASSERT_OK(Flush());
|
||||
ASSERT_OK(dbfull()->TEST_WaitForFlushMemTable());
|
||||
|
||||
ASSERT_OK(dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr));
|
||||
|
||||
std::vector<LiveFileMetaData> files;
|
||||
dbfull()->GetLiveFilesMetaData(&files);
|
||||
ASSERT_EQ(1, files.size());
|
||||
ASSERT_EQ("v2", Get("aaaa1"));
|
||||
ASSERT_EQ("v1", Get("bbbb1"));
|
||||
ASSERT_EQ("v2", Get("cccc1"));
|
||||
}
|
||||
|
||||
TEST_F(DBCompactionTest, ZeroSeqIdCompaction) {
|
||||
Options options = CurrentOptions();
|
||||
options.compaction_style = kCompactionStyleLevel;
|
||||
@@ -5217,10 +5350,10 @@ TEST_F(DBCompactionTest, LevelTtlCascadingCompactions) {
|
||||
*max_open_files = 2;
|
||||
});
|
||||
// In the case where all files are opened and doing DB restart
|
||||
// forcing the oldest ancester time in manifest file to be 0 to
|
||||
// forcing the oldest ancestor time in manifest file to be 0 to
|
||||
// simulate the case of reading from an old version.
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->SetCallBack(
|
||||
"VersionEdit::EncodeTo:VarintOldestAncesterTime", [&](void* arg) {
|
||||
"VersionEdit::EncodeTo:VarintOldestAncestorTime", [&](void* arg) {
|
||||
if (if_restart && if_open_all_files) {
|
||||
std::string* encoded_field = static_cast<std::string*>(arg);
|
||||
*encoded_field = "";
|
||||
@@ -5257,7 +5390,7 @@ TEST_F(DBCompactionTest, LevelTtlCascadingCompactions) {
|
||||
std::vector<std::vector<FileMetaData>> level_to_files;
|
||||
dbfull()->TEST_GetFilesMetaData(dbfull()->DefaultColumnFamily(),
|
||||
&level_to_files);
|
||||
uint64_t oldest_time = level_to_files[0][0].oldest_ancester_time;
|
||||
uint64_t oldest_time = level_to_files[0][0].oldest_ancestor_time;
|
||||
// Add 1 hour and do another flush.
|
||||
env_->MockSleepForSeconds(1 * 60 * 60);
|
||||
for (int i = 101; i <= 200; ++i) {
|
||||
@@ -5325,7 +5458,7 @@ TEST_F(DBCompactionTest, LevelTtlCascadingCompactions) {
|
||||
|
||||
dbfull()->TEST_GetFilesMetaData(dbfull()->DefaultColumnFamily(),
|
||||
&level_to_files);
|
||||
ASSERT_EQ(oldest_time, level_to_files[6][0].oldest_ancester_time);
|
||||
ASSERT_EQ(oldest_time, level_to_files[6][0].oldest_ancestor_time);
|
||||
|
||||
env_->MockSleepForSeconds(25 * 60 * 60);
|
||||
ASSERT_OK(Put(Key(2), "1"));
|
||||
@@ -5353,6 +5486,7 @@ TEST_F(DBCompactionTest, LevelPeriodicCompaction) {
|
||||
for (bool if_open_all_files : {false, true}) {
|
||||
Options options = CurrentOptions();
|
||||
options.periodic_compaction_seconds = 48 * 60 * 60; // 2 days
|
||||
options.periodic_compaction_phase_recovery_percent = 0;
|
||||
if (if_open_all_files) {
|
||||
options.max_open_files = -1; // needed for ttl compaction
|
||||
} else {
|
||||
@@ -5448,6 +5582,169 @@ TEST_F(DBCompactionTest, LevelPeriodicCompaction) {
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(DBCompactionTest, PeriodicCompactionPhaseTriggerTime) {
|
||||
// Unit-tests PeriodicCompactionPhaser::TriggerTime, the core of
|
||||
// preferred-phase periodic compaction (see
|
||||
// DBOptions::periodic_compaction_phase_recovery_percent).
|
||||
using Params = PeriodicCompactionPhaseParams;
|
||||
const uint64_t kN = 1000; // periodic_compaction_seconds
|
||||
|
||||
// The trigger-time helper treats seed_hash as an opaque value; use a fixed
|
||||
// constant and derive the resulting preferred-phase target the same way
|
||||
// production does (FastRange64 of the seed over the interval).
|
||||
const uint64_t kSeed = 0x9e3779b97f4a7c15ULL;
|
||||
const uint64_t target = FastRange64(kSeed, kN);
|
||||
ASSERT_LT(target, kN);
|
||||
|
||||
// recovery_percent == 0 => classic behavior: trigger at file_mod + N.
|
||||
{
|
||||
Params p;
|
||||
p.seed_hash = kSeed;
|
||||
p.recovery_percent = 0;
|
||||
for (uint64_t fm : {uint64_t{1}, uint64_t{7}, uint64_t{12345}}) {
|
||||
ASSERT_EQ(PeriodicCompactionPhaser::TriggerTime(fm, kN, p), fm + kN);
|
||||
}
|
||||
}
|
||||
|
||||
// Steady state (anchor in the distant past): trigger is pulled earlier by
|
||||
// recovery_percent% of the phase offset, and never later than the deadline.
|
||||
{
|
||||
Params p;
|
||||
p.seed_hash = kSeed;
|
||||
p.recovery_percent = 50;
|
||||
p.anchor_time = 0;
|
||||
const uint64_t fm = 500;
|
||||
const uint64_t natural = fm + kN;
|
||||
const uint64_t offset = (fm % kN + kN - target) % kN;
|
||||
const uint64_t expected = natural - offset * 50 / 100;
|
||||
ASSERT_EQ(PeriodicCompactionPhaser::TriggerTime(fm, kN, p), expected);
|
||||
ASSERT_LE(expected, natural);
|
||||
}
|
||||
|
||||
// Geometric convergence: repeatedly re-stamp the file at its trigger time and
|
||||
// confirm the phase error is non-increasing and converges to (near) zero.
|
||||
for (int recovery_percent : {50, 100}) {
|
||||
Params p;
|
||||
p.seed_hash = kSeed;
|
||||
p.recovery_percent = recovery_percent;
|
||||
p.anchor_time = 0;
|
||||
uint64_t fm = 123;
|
||||
uint64_t prev_error = kN;
|
||||
for (int cycle = 0; cycle < 64; ++cycle) {
|
||||
const uint64_t trig = PeriodicCompactionPhaser::TriggerTime(fm, kN, p);
|
||||
ASSERT_LE(trig, fm + kN); // never later than the deadline
|
||||
const uint64_t error = (trig % kN + kN - target) % kN;
|
||||
ASSERT_LE(error, prev_error);
|
||||
prev_error = error;
|
||||
fm = trig;
|
||||
}
|
||||
// rp=100 pulls the whole gap so it reaches the phase exactly; smaller rates
|
||||
// decay geometrically and leave a tiny integer-rounding residue.
|
||||
if (recovery_percent == 100) {
|
||||
ASSERT_EQ(prev_error, uint64_t{0});
|
||||
} else {
|
||||
ASSERT_LE(prev_error, uint64_t{1});
|
||||
}
|
||||
}
|
||||
|
||||
// Already past the hard deadline when phasing took effect (e.g. the DB was
|
||||
// down, or periodic_compaction_seconds was turned down): instead of firing
|
||||
// the whole cohort immediately, spread it over the first quarter-period after
|
||||
// the anchor on an absolute (epoch-aligned) grid of period N/4.
|
||||
{
|
||||
Params p;
|
||||
p.seed_hash = kSeed;
|
||||
p.recovery_percent = 50;
|
||||
p.anchor_time = 200;
|
||||
const uint64_t n = 100;
|
||||
const uint64_t grid = n / 4; // 25
|
||||
const uint64_t phase = FastRange64(kSeed, grid);
|
||||
// natural deadline (10 + 100 = 110) is before the anchor (200).
|
||||
const uint64_t expected = 200 + (phase + grid - 200 % grid) % grid;
|
||||
const uint64_t trig = PeriodicCompactionPhaser::TriggerTime(10, n, p);
|
||||
ASSERT_EQ(trig, expected);
|
||||
ASSERT_GE(trig, uint64_t{200}); // never before the anchor
|
||||
ASSERT_LT(trig, 200 + grid); // within N/4 of the anchor
|
||||
}
|
||||
|
||||
// Past due against the recovery target but not yet at the deadline => spread
|
||||
// across [anchor, deadline] using the phase; never later than the deadline.
|
||||
{
|
||||
const uint64_t n = 100;
|
||||
const uint64_t small_target = FastRange64(kSeed, n);
|
||||
const uint64_t fm = small_target + 50 + 3 * n; // phase offset == 50
|
||||
const uint64_t natural = fm + n;
|
||||
const uint64_t anchor =
|
||||
natural - 25; // recovery target (natural-50) < anchor
|
||||
Params p;
|
||||
p.seed_hash = kSeed;
|
||||
p.recovery_percent = 100;
|
||||
p.anchor_time = anchor;
|
||||
ASSERT_EQ((fm % n + n - small_target) % n, uint64_t{50});
|
||||
const uint64_t expected = anchor + FastRange64(kSeed, natural - anchor);
|
||||
const uint64_t trig = PeriodicCompactionPhaser::TriggerTime(fm, n, p);
|
||||
ASSERT_EQ(trig, expected);
|
||||
ASSERT_GE(trig, anchor);
|
||||
ASSERT_LT(trig, natural);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(DBCompactionTest, PeriodicCompactionPhaseCfSpread) {
|
||||
// Unit-tests PeriodicCompactionPhaser::CfPhaseSeedHash: a DB's column
|
||||
// families are spread quasi-uniformly around the DB base phase via the
|
||||
// golden-ratio recurrence, for any base and any number of CFs.
|
||||
using Phaser = PeriodicCompactionPhaser;
|
||||
|
||||
// cf_id 0 leaves the base phase unchanged; distinct cf_ids -> distinct
|
||||
// phases.
|
||||
for (uint64_t base : {uint64_t{0}, uint64_t{0x9e3779b97f4a7c15ULL},
|
||||
uint64_t{12345678901234567ULL}, ~uint64_t{0}}) {
|
||||
ASSERT_EQ(Phaser::CfPhaseSeedHash(base, 0), base);
|
||||
std::vector<uint64_t> hs;
|
||||
for (uint32_t id = 0; id < 64; ++id) {
|
||||
hs.push_back(Phaser::CfPhaseSeedHash(base, id));
|
||||
}
|
||||
std::sort(hs.begin(), hs.end());
|
||||
for (size_t i = 1; i < hs.size(); ++i) {
|
||||
ASSERT_NE(hs[i], hs[i - 1]) << "duplicate CF phase seed at base=" << base;
|
||||
}
|
||||
}
|
||||
|
||||
// Low-discrepancy: for N CFs the phases over an interval are well spread --
|
||||
// no gap larger than ~2x the average (a hash would allow chance clustering).
|
||||
for (uint64_t base : {uint64_t{0}, uint64_t{0xdeadbeefcafef00dULL}}) {
|
||||
for (uint32_t N : {uint32_t{3}, uint32_t{8}, uint32_t{16}, uint32_t{40}}) {
|
||||
const uint64_t n = 100000;
|
||||
std::vector<uint64_t> phases;
|
||||
for (uint32_t id = 0; id < N; ++id) {
|
||||
phases.push_back(FastRange64(Phaser::CfPhaseSeedHash(base, id), n));
|
||||
}
|
||||
std::sort(phases.begin(), phases.end());
|
||||
uint64_t max_gap = n - phases.back() + phases.front(); // wrap-around gap
|
||||
for (size_t i = 1; i < phases.size(); ++i) {
|
||||
max_gap = std::max(max_gap, phases[i] - phases[i - 1]);
|
||||
}
|
||||
ASSERT_LE(max_gap, 2 * (n / N))
|
||||
<< "base=" << base << " N=" << N << " max_gap=" << max_gap;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(DBCompactionTest, PeriodicCompactionPhaseOptions) {
|
||||
// Verifies periodic_compaction_phase_recovery_percent is plumbed and
|
||||
// dynamically settable.
|
||||
Options options = CurrentOptions();
|
||||
options.periodic_compaction_phase_recovery_percent = 25;
|
||||
DestroyAndReopen(options);
|
||||
ASSERT_EQ(dbfull()->GetDBOptions().periodic_compaction_phase_recovery_percent,
|
||||
25);
|
||||
|
||||
ASSERT_OK(dbfull()->SetDBOptions(
|
||||
{{"periodic_compaction_phase_recovery_percent", "0"}}));
|
||||
ASSERT_EQ(dbfull()->GetDBOptions().periodic_compaction_phase_recovery_percent,
|
||||
0);
|
||||
}
|
||||
|
||||
TEST_F(DBCompactionTest, LevelPeriodicCompactionOffpeak) {
|
||||
// This test simply checks if offpeak adjustment works in Leveled
|
||||
// Compactions. For testing offpeak periodic compactions in various
|
||||
@@ -5465,6 +5762,7 @@ TEST_F(DBCompactionTest, LevelPeriodicCompactionOffpeak) {
|
||||
Options options = CurrentOptions();
|
||||
options.ttl = 0;
|
||||
options.periodic_compaction_seconds = 5 * kSecondsPerDay; // 5 days
|
||||
options.periodic_compaction_phase_recovery_percent = 0;
|
||||
// In the case where all files are opened and doing DB restart
|
||||
// forcing the file creation time in manifest file to be 0 to
|
||||
// simulate the case of reading from an old version.
|
||||
@@ -5583,7 +5881,7 @@ TEST_F(DBCompactionTest, LevelPeriodicCompactionWithOldDB) {
|
||||
props->file_creation_time = 0;
|
||||
}
|
||||
if (set_creation_time_to_zero) {
|
||||
props->creation_time = 0;
|
||||
props->oldest_ancestor_time = 0;
|
||||
}
|
||||
});
|
||||
ROCKSDB_NAMESPACE::SyncPoint::GetInstance()->EnableProcessing();
|
||||
@@ -5612,6 +5910,7 @@ TEST_F(DBCompactionTest, LevelPeriodicCompactionWithOldDB) {
|
||||
// Forward the clock by 2 days.
|
||||
env_->MockSleepForSeconds(2 * 24 * 60 * 60);
|
||||
options.periodic_compaction_seconds = 1 * 24 * 60 * 60; // 1 day
|
||||
options.periodic_compaction_phase_recovery_percent = 0;
|
||||
|
||||
Reopen(options);
|
||||
ASSERT_OK(dbfull()->TEST_WaitForCompact());
|
||||
@@ -5630,6 +5929,7 @@ TEST_F(DBCompactionTest, LevelPeriodicAndTtlCompaction) {
|
||||
Options options = CurrentOptions();
|
||||
options.ttl = 10 * 60 * 60; // 10 hours
|
||||
options.periodic_compaction_seconds = 48 * 60 * 60; // 2 days
|
||||
options.periodic_compaction_phase_recovery_percent = 0;
|
||||
options.max_open_files = -1; // needed for both periodic and ttl compactions
|
||||
env_->SetMockSleep();
|
||||
options.env = env_;
|
||||
@@ -5712,6 +6012,7 @@ TEST_F(DBCompactionTest, LevelTtlBooster) {
|
||||
Options options = CurrentOptions();
|
||||
options.ttl = 10 * 60 * 60; // 10 hours
|
||||
options.periodic_compaction_seconds = 480 * 60 * 60; // very long
|
||||
options.periodic_compaction_phase_recovery_percent = 0;
|
||||
options.level0_file_num_compaction_trigger = 2;
|
||||
options.max_bytes_for_level_base = 5 * uint64_t{kNumKeysPerFile * kValueSize};
|
||||
options.max_open_files = -1; // needed for both periodic and ttl compactions
|
||||
@@ -6156,6 +6457,7 @@ 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);
|
||||
@@ -6163,9 +6465,13 @@ 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_EQ(num_running_compactions, 0);
|
||||
ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kNumRunningBottomCompactions,
|
||||
&num_running_bottom_compactions));
|
||||
ASSERT_EQ(0, num_running_compactions);
|
||||
ASSERT_EQ(0, num_running_bottom_compactions);
|
||||
uint64_t num_running_compaction_sorted_runs = 0;
|
||||
ASSERT_TRUE(
|
||||
db_->GetIntProperty(DB::Properties::kNumRunningCompactionSortedRuns,
|
||||
@@ -6174,6 +6480,18 @@ 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; });
|
||||
@@ -6197,11 +6515,15 @@ TEST_F(DBCompactionTest, CompactionStatsTest) {
|
||||
// to process
|
||||
ASSERT_TRUE(db_->GetIntProperty(DB::Properties::kNumRunningCompactions,
|
||||
&num_running_compactions));
|
||||
ASSERT_EQ(num_running_compactions, 0);
|
||||
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_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();
|
||||
@@ -12095,7 +12417,7 @@ TEST_F(DBCompactionTest, RecordNewestKeyTimeForTtlCompaction) {
|
||||
ASSERT_EQ(newest_key_time, file_metadatas[idx]
|
||||
->fd.pinned_reader.Get()
|
||||
->GetTableProperties()
|
||||
->creation_time);
|
||||
->oldest_ancestor_time);
|
||||
}
|
||||
// The delta between the first and last newest_key_times is 15s
|
||||
uint64_t last_newest_key_time = prev_newest_key_time;
|
||||
@@ -12114,14 +12436,14 @@ TEST_F(DBCompactionTest, RecordNewestKeyTimeForTtlCompaction) {
|
||||
->GetTableProperties()
|
||||
->newest_key_time,
|
||||
first_newest_key_time);
|
||||
// Contrast newest_key_time with creation_time, which records the oldest
|
||||
// ancestor time (15s older than newest_key_time)
|
||||
// Contrast newest_key_time with oldest_ancestor_time (15s older than
|
||||
// newest_key_time)
|
||||
ASSERT_EQ(file_metadatas[0]
|
||||
->fd.pinned_reader.Get()
|
||||
->GetTableProperties()
|
||||
->creation_time,
|
||||
->oldest_ancestor_time,
|
||||
last_newest_key_time);
|
||||
ASSERT_EQ(file_metadatas[0]->oldest_ancester_time, last_newest_key_time);
|
||||
ASSERT_EQ(file_metadatas[0]->oldest_ancestor_time, last_newest_key_time);
|
||||
|
||||
// Make sure TTL of 5s causes compaction
|
||||
env_->MockSleepForSeconds(6);
|
||||
@@ -12240,6 +12562,7 @@ TEST_F(DBCompactionTest, PeriodicTask) {
|
||||
options.statistics = CreateDBStatistics();
|
||||
int kPeriodicCompactionSeconds = 7 * 24 * 60 * 60; // 1 week
|
||||
options.periodic_compaction_seconds = kPeriodicCompactionSeconds;
|
||||
options.periodic_compaction_phase_recovery_percent = 0;
|
||||
options.num_levels = 50;
|
||||
auto listener = std::make_shared<PeriodicCompactionListener>();
|
||||
options.listeners.push_back(listener);
|
||||
|
||||
@@ -4271,6 +4271,147 @@ TEST_F(DBTest2, TraceWithLimit) {
|
||||
ASSERT_OK(DestroyDB(dbname2, options));
|
||||
}
|
||||
|
||||
namespace {
|
||||
Status ReplayTraceFile(Env* env, const std::string& trace_filename, DB* db,
|
||||
const std::vector<ColumnFamilyHandle*>& handles,
|
||||
uint32_t num_threads,
|
||||
TraceExecutionResultHandler* res_handler = nullptr) {
|
||||
std::unique_ptr<TraceReader> trace_reader;
|
||||
Status s =
|
||||
NewFileTraceReader(env, EnvOptions(), trace_filename, &trace_reader);
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
std::unique_ptr<Replayer> replayer;
|
||||
s = db->NewDefaultReplayer(handles, std::move(trace_reader), &replayer);
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
s = replayer->Prepare();
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
// Count the replayed records by type in `res_handler`, if given.
|
||||
std::function<void(Status, std::unique_ptr<TraceRecordResult>&&)> res_cb;
|
||||
if (res_handler != nullptr) {
|
||||
res_cb = [res_handler](const Status& exec_s,
|
||||
std::unique_ptr<TraceRecordResult>&& res) {
|
||||
exec_s.PermitUncheckedError();
|
||||
if (res != nullptr) {
|
||||
EXPECT_OK(res->Accept(res_handler));
|
||||
}
|
||||
};
|
||||
}
|
||||
return replayer->Replay(ReplayOptions(num_threads, 1.0), res_cb);
|
||||
}
|
||||
} // anonymous namespace
|
||||
|
||||
TEST_F(DBTest2, TraceReplayDefaultColumnFamilyWithoutHandles) {
|
||||
Options options = CurrentOptions();
|
||||
std::string trace_filename = dbname_ + "/rocksdb.trace";
|
||||
std::unique_ptr<TraceWriter> trace_writer;
|
||||
ASSERT_OK(
|
||||
NewFileTraceWriter(env_, EnvOptions(), trace_filename, &trace_writer));
|
||||
ASSERT_OK(db_->StartTrace(TraceOptions(), std::move(trace_writer)));
|
||||
ASSERT_OK(Put("a", "1"));
|
||||
ASSERT_OK(Put("b", "2"));
|
||||
ASSERT_EQ("1", Get("a"));
|
||||
std::vector<std::string> values;
|
||||
for (const Status& s :
|
||||
db_->MultiGet(ReadOptions(), {Slice("a"), Slice("b")}, &values)) {
|
||||
ASSERT_OK(s);
|
||||
}
|
||||
std::unique_ptr<Iterator> iter(db_->NewIterator(ReadOptions()));
|
||||
iter->Seek("a");
|
||||
iter->SeekForPrev("b");
|
||||
ASSERT_OK(iter->status());
|
||||
iter.reset();
|
||||
ASSERT_OK(db_->EndTrace());
|
||||
|
||||
std::string dbname2 = test::PerThreadDBPath(env_, "/db_replay2");
|
||||
options.create_if_missing = true;
|
||||
for (uint32_t num_threads : {1U, 2U}) {
|
||||
SCOPED_TRACE("num_threads=" + std::to_string(num_threads));
|
||||
ASSERT_OK(DestroyDB(dbname2, options));
|
||||
std::unique_ptr<DB> db2;
|
||||
ASSERT_OK(DB::Open(options, dbname2, &db2));
|
||||
// No handles: every read record on the default column family must still
|
||||
// replay.
|
||||
TraceExecutionResultHandler res_handler;
|
||||
ASSERT_OK(ReplayTraceFile(env_, trace_filename, db2.get(),
|
||||
/*handles=*/{}, num_threads, &res_handler));
|
||||
// Each record replayed and produced a result.
|
||||
ASSERT_EQ(2, res_handler.GetNumWrites());
|
||||
ASSERT_EQ(1, res_handler.GetNumGets());
|
||||
ASSERT_EQ(1, res_handler.GetNumMultiGets());
|
||||
ASSERT_EQ(2, res_handler.GetNumIterSeeks());
|
||||
std::string value;
|
||||
ASSERT_OK(db2->Get(ReadOptions(), "a", &value));
|
||||
ASSERT_EQ("1", value);
|
||||
ASSERT_OK(db2->Get(ReadOptions(), "b", &value));
|
||||
ASSERT_EQ("2", value);
|
||||
}
|
||||
ASSERT_OK(DestroyDB(dbname2, options));
|
||||
}
|
||||
|
||||
TEST_F(DBTest2, TraceReplayReturnsExecutionError) {
|
||||
Options options = CurrentOptions();
|
||||
CreateAndReopenWithCF({"pikachu"}, options);
|
||||
std::string trace_filename = dbname_ + "/rocksdb.trace";
|
||||
std::unique_ptr<TraceWriter> trace_writer;
|
||||
ASSERT_OK(
|
||||
NewFileTraceWriter(env_, EnvOptions(), trace_filename, &trace_writer));
|
||||
ASSERT_OK(db_->StartTrace(TraceOptions(), std::move(trace_writer)));
|
||||
ASSERT_EQ("NOT_FOUND", Get(1, "a"));
|
||||
ASSERT_EQ("NOT_FOUND", Get(1, "b"));
|
||||
ASSERT_OK(db_->EndTrace());
|
||||
|
||||
// The replay DB has no "pikachu" column family, so both Get records fail.
|
||||
std::string dbname2 = test::PerThreadDBPath(env_, "/db_replay2");
|
||||
options.create_if_missing = true;
|
||||
ASSERT_OK(DestroyDB(dbname2, options));
|
||||
std::unique_ptr<DB> db2;
|
||||
ASSERT_OK(DB::Open(options, dbname2, &db2));
|
||||
for (uint32_t num_threads : {1U, 2U}) {
|
||||
SCOPED_TRACE("num_threads=" + std::to_string(num_threads));
|
||||
Status s = ReplayTraceFile(env_, trace_filename, db2.get(),
|
||||
{db2->DefaultColumnFamily()}, num_threads);
|
||||
ASSERT_TRUE(s.IsCorruption()) << s.ToString();
|
||||
}
|
||||
db2.reset();
|
||||
ASSERT_OK(DestroyDB(dbname2, options));
|
||||
}
|
||||
|
||||
TEST_F(DBTest2, TraceReplayReturnsNotSupportedExecutionError) {
|
||||
Options options = CurrentOptions();
|
||||
std::string trace_filename = dbname_ + "/rocksdb.trace";
|
||||
std::unique_ptr<TraceWriter> trace_writer;
|
||||
ASSERT_OK(
|
||||
NewFileTraceWriter(env_, EnvOptions(), trace_filename, &trace_writer));
|
||||
ASSERT_OK(db_->StartTrace(TraceOptions(), std::move(trace_writer)));
|
||||
ASSERT_OK(Put("a", "1"));
|
||||
ASSERT_OK(
|
||||
db_->DeleteRange(WriteOptions(), db_->DefaultColumnFamily(), "a", "z"));
|
||||
ASSERT_OK(db_->EndTrace());
|
||||
|
||||
// DeleteRange is not compatible with row_cache, so replaying the DeleteRange
|
||||
// write fails with NotSupported. Unlike an unsupported trace type, this must
|
||||
// not be skipped.
|
||||
std::string dbname2 = test::PerThreadDBPath(env_, "/db_replay2");
|
||||
options.create_if_missing = true;
|
||||
options.row_cache = NewLRUCache(1 << 20);
|
||||
for (uint32_t num_threads : {1U, 2U}) {
|
||||
SCOPED_TRACE("num_threads=" + std::to_string(num_threads));
|
||||
ASSERT_OK(DestroyDB(dbname2, options));
|
||||
std::unique_ptr<DB> db2;
|
||||
ASSERT_OK(DB::Open(options, dbname2, &db2));
|
||||
Status s = ReplayTraceFile(env_, trace_filename, db2.get(),
|
||||
/*handles=*/{}, num_threads);
|
||||
ASSERT_TRUE(s.IsNotSupported()) << s.ToString();
|
||||
}
|
||||
ASSERT_OK(DestroyDB(dbname2, options));
|
||||
}
|
||||
|
||||
TEST_F(DBTest2, TraceWithSampling) {
|
||||
Options options = CurrentOptions();
|
||||
ReadOptions ro;
|
||||
@@ -7651,6 +7792,48 @@ TEST_F(DBTest2, TableCacheMissDuringReadFromBlockCacheTier) {
|
||||
ASSERT_EQ(orig_num_file_opens, TestGetTickerCount(options, NO_FILE_OPENS));
|
||||
}
|
||||
|
||||
TEST_F(DBTest2, MultiGetBlockCacheTierSkipsColdSstData) {
|
||||
Options options = CurrentOptions();
|
||||
options.statistics = ROCKSDB_NAMESPACE::CreateDBStatistics();
|
||||
// Use buffered reads to reach the non-mmap RetrieveMultipleBlocks path.
|
||||
options.allow_mmap_reads = false;
|
||||
BlockBasedTableOptions table_options;
|
||||
// Data blocks use the block cache. Index and filter blocks stay in the table
|
||||
// reader (cache_index_and_filter_blocks is false by default), so a
|
||||
// kBlockCacheTier read gets to the data block without metadata I/O.
|
||||
table_options.block_cache = NewLRUCache(1 << 20);
|
||||
options.table_factory.reset(NewBlockBasedTableFactory(table_options));
|
||||
DestroyAndReopen(options);
|
||||
|
||||
ASSERT_OK(Put("k1", "v1"));
|
||||
ASSERT_OK(Put("k2", "v2"));
|
||||
ASSERT_OK(Flush());
|
||||
|
||||
// Open the table reader so that kBlockCacheTier does not fail at table
|
||||
// open. Do not add the data block to the block cache.
|
||||
ReadOptions warm_ro;
|
||||
warm_ro.fill_cache = false;
|
||||
std::string value;
|
||||
ASSERT_OK(db_->Get(warm_ro, "k1", &value));
|
||||
ASSERT_EQ(value, "v1");
|
||||
// Make sure the data block is not in the block cache.
|
||||
table_options.block_cache->EraseUnRefEntries();
|
||||
|
||||
ReadOptions no_io_ro;
|
||||
no_io_ro.read_tier = kBlockCacheTier;
|
||||
|
||||
ASSERT_TRUE(db_->Get(no_io_ro, "k1", &value).IsIncomplete());
|
||||
ASSERT_TRUE(db_->Get(no_io_ro, "k2", &value).IsIncomplete());
|
||||
|
||||
Slice keys[2] = {Slice("k1"), Slice("k2")};
|
||||
PinnableSlice values[2];
|
||||
Status statuses[2];
|
||||
db_->MultiGet(no_io_ro, db_->DefaultColumnFamily(), 2, keys, values,
|
||||
statuses);
|
||||
ASSERT_TRUE(statuses[0].IsIncomplete());
|
||||
ASSERT_TRUE(statuses[1].IsIncomplete());
|
||||
}
|
||||
|
||||
TEST_F(DBTest2, GetFileChecksumsFromCurrentManifest_CRC32) {
|
||||
Options opts = CurrentOptions();
|
||||
opts.create_if_missing = true;
|
||||
|
||||
+79
-2
@@ -8,6 +8,7 @@
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
#include "db/db_impl/db_impl.h"
|
||||
@@ -20,8 +21,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"
|
||||
@@ -195,14 +196,64 @@ 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;
|
||||
@@ -282,6 +333,14 @@ Status DBImpl::GetLiveFilesStorageInfo(
|
||||
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;
|
||||
|
||||
@@ -343,9 +402,27 @@ Status DBImpl::GetLiveFilesStorageInfo(
|
||||
}
|
||||
}
|
||||
|
||||
// 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();
|
||||
uint64_t manifest_size = versions_->manifest_file_size();
|
||||
if (cf_subset && !excluded_cf_ids->empty()) {
|
||||
Status manifest_s = versions_->GetManifestAppendBoundary(&manifest_size);
|
||||
if (!manifest_s.ok()) {
|
||||
mutex_.Unlock();
|
||||
return manifest_s;
|
||||
}
|
||||
}
|
||||
const uint64_t options_number = versions_->options_file_number();
|
||||
const uint64_t options_size = versions_->options_file_size_;
|
||||
const uint64_t min_log_num = MinLogNumberToKeep();
|
||||
|
||||
@@ -20,9 +20,11 @@
|
||||
#include "port/stack_trace.h"
|
||||
#include "rocksdb/utilities/transaction_db.h"
|
||||
#include "table/block_based/block_based_table_builder.h"
|
||||
#include "table/format.h"
|
||||
#include "test_util/sync_point.h"
|
||||
#include "test_util/testutil.h"
|
||||
#include "util/cast_util.h"
|
||||
#include "util/defer.h"
|
||||
#include "util/mutexlock.h"
|
||||
#include "utilities/fault_injection_env.h"
|
||||
#include "utilities/fault_injection_fs.h"
|
||||
@@ -2980,6 +2982,34 @@ TEST_P(DBAtomicFlushTest, ManualAtomicFlush) {
|
||||
}
|
||||
}
|
||||
|
||||
// Two handles naming the same column family make the selected-cfd list longer
|
||||
// than the per-CF memtable-id list, which is keyed by CF. The wait loop must
|
||||
// not read the id list past its own length.
|
||||
TEST_P(DBAtomicFlushTest, ManualAtomicFlushDuplicateColumnFamilyHandles) {
|
||||
if (!GetParam()) {
|
||||
// Only the atomic path reaches the shared wait list; without atomic_flush
|
||||
// each handle is flushed independently.
|
||||
return;
|
||||
}
|
||||
Options options = CurrentOptions();
|
||||
options.create_if_missing = true;
|
||||
options.atomic_flush = true;
|
||||
options.write_buffer_size = (static_cast<size_t>(64) << 20);
|
||||
DestroyAndReopen(options);
|
||||
|
||||
WriteOptions wopts;
|
||||
wopts.disableWAL = true;
|
||||
ASSERT_OK(Put("key", "value", wopts));
|
||||
|
||||
FlushOptions flush_options; // wait == true
|
||||
ASSERT_OK(db_->Flush(
|
||||
flush_options, {db_->DefaultColumnFamily(), db_->DefaultColumnFamily()}));
|
||||
|
||||
auto cfh = static_cast<ColumnFamilyHandleImpl*>(db_->DefaultColumnFamily());
|
||||
ASSERT_EQ(0, cfh->cfd()->imm()->NumNotFlushed());
|
||||
ASSERT_TRUE(cfh->cfd()->mem()->IsEmpty());
|
||||
}
|
||||
|
||||
TEST_P(DBAtomicFlushTest, PrecomputeMinLogNumberToKeepNon2PC) {
|
||||
Options options = CurrentOptions();
|
||||
options.create_if_missing = true;
|
||||
@@ -3723,6 +3753,108 @@ TEST_F(DBFlushTest, NonAtomicNormalFlushAbortWhenBGError) {
|
||||
SyncPoint::GetInstance()->DisableProcessing();
|
||||
}
|
||||
|
||||
TEST_F(DBFlushTest, NonRecoveryFlushDoesNotStarveErrorRecovery) {
|
||||
constexpr uint64_t kRecoveryTimeoutMicros = 15 * 1000 * 1000;
|
||||
constexpr int kLateWriteCount = 32;
|
||||
|
||||
Options opts = CurrentOptions();
|
||||
opts.atomic_flush = true;
|
||||
opts.memtable_factory.reset(test::NewSpecialSkipListFactory(1));
|
||||
opts.max_write_buffer_number = 64;
|
||||
opts.max_background_flushes = 1;
|
||||
DestroyAndReopen(opts);
|
||||
env_->SetBackgroundThreads(1, Env::HIGH);
|
||||
|
||||
std::atomic_int flush_write_table_count{0};
|
||||
port::Mutex wait_mutex;
|
||||
port::CondVar wait_cv(&wait_mutex);
|
||||
bool recovery_wait_started = false;
|
||||
bool recovery_succeeded = false;
|
||||
SyncPoint::GetInstance()->ClearAllCallBacks();
|
||||
SyncPoint::GetInstance()->DisableProcessing();
|
||||
SyncPoint::GetInstance()->SetCallBack(
|
||||
"FlushJob::WriteLevel0Table:s", [&](void* s_ptr) {
|
||||
if (flush_write_table_count.fetch_add(1) == 0) {
|
||||
Status* s = static_cast<Status*>(s_ptr);
|
||||
IOStatus io_error = IOStatus::IOError("injected foobar");
|
||||
io_error.SetRetryable(true);
|
||||
*s = io_error;
|
||||
TEST_SYNC_POINT(
|
||||
"DBFlushTest::NonRecoveryFlushDoesNotStarveErrorRecovery:"
|
||||
"FirstFlushFailed");
|
||||
TEST_SYNC_POINT(
|
||||
"DBFlushTest::NonRecoveryFlushDoesNotStarveErrorRecovery:"
|
||||
"ContinueFirstFlush");
|
||||
}
|
||||
});
|
||||
SyncPoint::GetInstance()->SetCallBack(
|
||||
"DBImpl::ResumeImpl:BeforeWaitForBackgroundWork", [&](void*) {
|
||||
MutexLock l(&wait_mutex);
|
||||
recovery_wait_started = true;
|
||||
wait_cv.SignalAll();
|
||||
});
|
||||
SyncPoint::GetInstance()->SetCallBack(
|
||||
"RecoverFromRetryableBGIOError:RecoverSuccess", [&](void*) {
|
||||
MutexLock l(&wait_mutex);
|
||||
recovery_succeeded = true;
|
||||
wait_cv.SignalAll();
|
||||
});
|
||||
SyncPoint::GetInstance()->LoadDependency(
|
||||
{{"DBFlushTest::NonRecoveryFlushDoesNotStarveErrorRecovery:"
|
||||
"FirstFlushFailed",
|
||||
"DBFlushTest::NonRecoveryFlushDoesNotStarveErrorRecovery:"
|
||||
"FailureObserved"},
|
||||
{"DBFlushTest::NonRecoveryFlushDoesNotStarveErrorRecovery:"
|
||||
"ReleaseFirstFlush",
|
||||
"DBFlushTest::NonRecoveryFlushDoesNotStarveErrorRecovery:"
|
||||
"ContinueFirstFlush"}});
|
||||
SyncPoint::GetInstance()->EnableProcessing();
|
||||
|
||||
auto wait_until = [&](const auto& predicate) {
|
||||
const uint64_t abs_time =
|
||||
SystemClock::Default()->NowMicros() + kRecoveryTimeoutMicros;
|
||||
MutexLock l(&wait_mutex);
|
||||
while (!predicate()) {
|
||||
if (wait_cv.TimedWait(abs_time)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
ASSERT_OK(Put(Key(1), "val1"));
|
||||
ASSERT_OK(Put(Key(2), "val2"));
|
||||
TEST_SYNC_POINT(
|
||||
"DBFlushTest::NonRecoveryFlushDoesNotStarveErrorRecovery:"
|
||||
"FailureObserved");
|
||||
TEST_SYNC_POINT(
|
||||
"DBFlushTest::NonRecoveryFlushDoesNotStarveErrorRecovery:"
|
||||
"ReleaseFirstFlush");
|
||||
|
||||
const bool recovery_wait_reached =
|
||||
wait_until([&] { return recovery_wait_started; });
|
||||
Status late_write_status;
|
||||
if (recovery_wait_reached) {
|
||||
for (int key = 3; key < 3 + kLateWriteCount && late_write_status.ok();
|
||||
++key) {
|
||||
late_write_status = Put(Key(key), "val");
|
||||
}
|
||||
}
|
||||
const bool recovered = wait_until([&] { return recovery_succeeded; });
|
||||
|
||||
if (!recovered) {
|
||||
IOStatus cleanup_error = IOStatus::IOError("stop stuck error recovery");
|
||||
dbfull()->TEST_SetBGError(cleanup_error, BackgroundErrorReason::kFlush);
|
||||
dbfull()->TEST_SignalAllBgCv();
|
||||
}
|
||||
|
||||
SyncPoint::GetInstance()->ClearAllCallBacks();
|
||||
SyncPoint::GetInstance()->DisableProcessing();
|
||||
ASSERT_TRUE(recovery_wait_reached);
|
||||
ASSERT_OK(late_write_status);
|
||||
ASSERT_TRUE(recovered);
|
||||
}
|
||||
|
||||
TEST_F(DBFlushTest, DBStuckAfterAtomicFlushError) {
|
||||
// Test for a bug with atomic flush where DB can become stuck
|
||||
// after a flush error. A repro timeline:
|
||||
@@ -4007,6 +4139,112 @@ INSTANTIATE_TEST_CASE_P(
|
||||
// larger than the max allowed padding size
|
||||
testing::Values(4, kLowSpaceOverheadRatio)));
|
||||
|
||||
// super_block_alignment pads data blocks, giving the padded block's index entry
|
||||
// a non-contiguous handle. At format_version <= 7 the writer forces that index
|
||||
// entry to shared==0 (full key AND full value). format_version 8 instead uses
|
||||
// the index value-delta escape (see IndexValue::EncodeTo), keeping the key
|
||||
// delta-encoded and the restart cadence intact. This verifies that fv8 returns
|
||||
// byte-identical read results to fv7 for the same keys (also with
|
||||
// separate_key_value_in_data_block, the intersection that motivated the
|
||||
// escape), that padding -- and hence the escape -- is actually exercised, and
|
||||
// that fv8 index values are delta encoded.
|
||||
TEST_F(DBFlushTest, SuperBlockAlignmentValueDeltaEscape) {
|
||||
// Writing the unpublished draft format_version 8 requires this opt-in.
|
||||
SaveAndRestore<bool> allow_draft(&TEST_AllowUnsupportedFormatVersion(), true);
|
||||
|
||||
constexpr int kKeyCount = 5000;
|
||||
auto format_key = [](int i) {
|
||||
char buf[16];
|
||||
snprintf(buf, sizeof(buf), "%010d", i);
|
||||
return std::string(buf);
|
||||
};
|
||||
|
||||
// Deterministic values so fv7 and fv8 see identical input.
|
||||
Random rnd(test::RandomSeed());
|
||||
std::vector<std::string> values;
|
||||
values.reserve(kKeyCount);
|
||||
for (int i = 0; i < kKeyCount; ++i) {
|
||||
values.push_back(rnd.RandomString(static_cast<int>(rnd.Uniform(1000))));
|
||||
}
|
||||
|
||||
auto build_and_read = [&](uint32_t format_version, bool separate_kv,
|
||||
std::vector<std::string>* got_get,
|
||||
std::vector<std::string>* got_iter, int* pad_count,
|
||||
bool* index_delta_encoded) {
|
||||
Options options = CurrentOptions();
|
||||
options.compression = kNoCompression;
|
||||
BlockBasedTableOptions bbto;
|
||||
bbto.format_version = format_version;
|
||||
bbto.index_block_restart_interval = 3; // > 1 so value delta encoding is on
|
||||
bbto.super_block_alignment_size = 16 * 1024;
|
||||
bbto.super_block_alignment_space_overhead_ratio = 8;
|
||||
bbto.separate_key_value_in_data_block = separate_kv;
|
||||
options.table_factory.reset(NewBlockBasedTableFactory(bbto));
|
||||
DestroyAndReopen(options);
|
||||
|
||||
int local_pad = 0;
|
||||
SyncPoint::GetInstance()->SetCallBack(
|
||||
"BlockBasedTableBuilder::WriteMaybeCompressedBlock:SuperBlockAlignment",
|
||||
[&local_pad](void*) { local_pad++; });
|
||||
SyncPoint::GetInstance()->EnableProcessing();
|
||||
|
||||
for (int i = 0; i < kKeyCount; ++i) {
|
||||
ASSERT_OK(Put(format_key(i), values[i]));
|
||||
}
|
||||
ASSERT_OK(Flush());
|
||||
|
||||
SyncPoint::GetInstance()->DisableProcessing();
|
||||
SyncPoint::GetInstance()->ClearAllCallBacks();
|
||||
*pad_count = local_pad;
|
||||
|
||||
got_get->clear();
|
||||
for (int i = 0; i < kKeyCount; ++i) {
|
||||
PinnableSlice v;
|
||||
ASSERT_OK(Get(format_key(i), &v));
|
||||
got_get->push_back(v.ToString());
|
||||
}
|
||||
got_iter->clear();
|
||||
{
|
||||
std::unique_ptr<Iterator> it(db_->NewIterator(ReadOptions()));
|
||||
for (it->SeekToFirst(); it->Valid(); it->Next()) {
|
||||
ASSERT_OK(it->status());
|
||||
got_iter->push_back(it->value().ToString());
|
||||
}
|
||||
ASSERT_OK(it->status());
|
||||
}
|
||||
|
||||
// Confirm the index value encoding of the produced SST(s).
|
||||
TablePropertiesCollection props;
|
||||
ASSERT_OK(db_->GetPropertiesOfAllTables(&props));
|
||||
ASSERT_FALSE(props.empty());
|
||||
*index_delta_encoded = true;
|
||||
for (const auto& kv : props) {
|
||||
if (kv.second->index_value_is_delta_encoded == 0) {
|
||||
*index_delta_encoded = false;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
for (bool separate_kv : {false, true}) {
|
||||
SCOPED_TRACE("separate_kv=" + std::to_string(separate_kv));
|
||||
std::vector<std::string> get7, iter7, get8, iter8;
|
||||
int pad7 = 0, pad8 = 0;
|
||||
bool delta7 = false, delta8 = false;
|
||||
build_and_read(7, separate_kv, &get7, &iter7, &pad7, &delta7);
|
||||
build_and_read(/*format_version=*/8, separate_kv, &get8, &iter8, &pad8,
|
||||
&delta8);
|
||||
|
||||
// Reads must be identical across versions.
|
||||
ASSERT_EQ(get7, get8);
|
||||
ASSERT_EQ(iter7, iter8);
|
||||
ASSERT_EQ(static_cast<int>(iter8.size()), kKeyCount);
|
||||
// Padding (the non-contiguity that drives the escape) actually happened.
|
||||
EXPECT_GT(pad8, 0);
|
||||
// fv8 index values are delta encoded, so the escape path was exercised.
|
||||
EXPECT_TRUE(delta8);
|
||||
}
|
||||
}
|
||||
|
||||
// Test that when the table builder's io_status becomes bad during flush
|
||||
// (simulating write fault injection), BuildTable properly propagates the
|
||||
// builder's IO error instead of producing a misleading Corruption from the
|
||||
|
||||
@@ -204,6 +204,19 @@ class DBFollowerTest : public DBTestBase {
|
||||
return result;
|
||||
}
|
||||
|
||||
void VerifyFollowerBatchValue(const std::string& key,
|
||||
const std::string& expected) {
|
||||
std::vector<Iterator*> iterators;
|
||||
ASSERT_OK(follower()->NewIterators(
|
||||
ReadOptions(), {follower()->DefaultColumnFamily()}, &iterators));
|
||||
ASSERT_EQ(1U, iterators.size());
|
||||
std::unique_ptr<Iterator> iterator(iterators[0]);
|
||||
iterator->Seek(key);
|
||||
ASSERT_OK(iterator->status());
|
||||
ASSERT_TRUE(iterator->Valid());
|
||||
ASSERT_EQ(expected, iterator->value());
|
||||
}
|
||||
|
||||
DB* follower() { return follower_.get(); }
|
||||
DBFollowerTestFS* follower_fs() {
|
||||
return static_cast<DBFollowerTestFS*>(follower_env_->GetFileSystem().get());
|
||||
@@ -253,6 +266,32 @@ TEST_F(DBFollowerTest, Basic) {
|
||||
CheckDirs();
|
||||
}
|
||||
|
||||
TEST_F(DBFollowerTest, NewIteratorsRefreshesAfterCatchUp) {
|
||||
ASSERT_OK(Put("key", "v1"));
|
||||
ASSERT_OK(Flush());
|
||||
|
||||
SyncPoint::GetInstance()->LoadDependency({
|
||||
{"DBImplFollower::TryCatchupWithLeader:Begin1", "Leader::Start"},
|
||||
{"Leader::Done", "DBImplFollower::TryCatchupWithLeader:Begin2"},
|
||||
{"DBImplFollower::TryCatchupWithLeader:End", "Follower::WaitForCatchup"},
|
||||
});
|
||||
SyncPoint::GetInstance()->EnableProcessing();
|
||||
|
||||
ASSERT_OK(OpenAsFollower());
|
||||
VerifyFollowerBatchValue("key", "v1");
|
||||
|
||||
TEST_SYNC_POINT("Leader::Start");
|
||||
ASSERT_OK(Put("key", "v2"));
|
||||
ASSERT_OK(Flush());
|
||||
TEST_SYNC_POINT("Leader::Done");
|
||||
TEST_SYNC_POINT("Follower::WaitForCatchup");
|
||||
|
||||
VerifyFollowerBatchValue("key", "v2");
|
||||
|
||||
SyncPoint::GetInstance()->DisableProcessing();
|
||||
SyncPoint::GetInstance()->ClearTrace();
|
||||
}
|
||||
|
||||
TEST_F(DBFollowerTest, Flush) {
|
||||
SyncPoint::GetInstance()->LoadDependency({
|
||||
{"DBImplFollower::TryCatchupWithLeader:Begin1", "Leader::Start"},
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
#include "db/blob/blob_fetcher.h"
|
||||
#include "db/db_impl/db_impl.h"
|
||||
#include "db/db_impl/db_impl_metadata.h"
|
||||
#include "db/version_set.h"
|
||||
#include "logging/logging.h"
|
||||
#include "table/get_context.h"
|
||||
@@ -34,6 +35,46 @@ size_t CompactedDBImpl::FindFile(const Slice& key) {
|
||||
files_.files);
|
||||
}
|
||||
|
||||
Status CompactedDBImpl::GetWithMetadata(const ReadOptions& options,
|
||||
ColumnFamilyHandle* column_family,
|
||||
const Slice& key, PinnableSlice* value,
|
||||
OutputMetadata* output_metadata) {
|
||||
std::string* timestamp = GetOutputTimestamp(output_metadata);
|
||||
bool* newer_version_present = GetOutputNewerVersionPresent(output_metadata);
|
||||
if (newer_version_present != nullptr) {
|
||||
*newer_version_present = false;
|
||||
}
|
||||
if (value == nullptr) {
|
||||
return Status::InvalidArgument(
|
||||
"Cannot call GetWithMetadata with a null value");
|
||||
}
|
||||
return Get(options, column_family, key, value, timestamp);
|
||||
}
|
||||
|
||||
void CompactedDBImpl::MultiGetWithMetadata(
|
||||
const ReadOptions& options, size_t num_keys,
|
||||
ColumnFamilyHandle* const* column_families, const Slice* keys,
|
||||
PinnableSlice* values, Status* statuses,
|
||||
MultiGetOutputMetadata* output_metadata, const bool sorted_input) {
|
||||
std::vector<std::string>* timestamps = GetOutputTimestamps(output_metadata);
|
||||
if (timestamps != nullptr) {
|
||||
timestamps->resize(num_keys);
|
||||
}
|
||||
std::vector<uint8_t>* newer_version_present =
|
||||
GetOutputNewerVersionPresent(output_metadata);
|
||||
if (newer_version_present != nullptr) {
|
||||
newer_version_present->assign(num_keys, false);
|
||||
}
|
||||
autovector<ColumnFamilyHandle*, MultiGetContext::MAX_BATCH_SIZE>
|
||||
stack_column_families;
|
||||
std::vector<ColumnFamilyHandle*> heap_column_families;
|
||||
ColumnFamilyHandle** mutable_column_families = MakeMutableCfHandles(
|
||||
column_families, num_keys, &stack_column_families, &heap_column_families);
|
||||
MultiGet(options, num_keys, mutable_column_families, keys, values,
|
||||
timestamps != nullptr ? timestamps->data() : nullptr, statuses,
|
||||
sorted_input);
|
||||
}
|
||||
|
||||
Status CompactedDBImpl::Init(const Options& options) {
|
||||
SuperVersionContext sv_context(/* create_superversion */ true);
|
||||
mutex_.Lock();
|
||||
|
||||
@@ -31,6 +31,12 @@ class CompactedDBImpl : public DBImpl {
|
||||
const Slice& key, PinnableSlice* value,
|
||||
std::string* timestamp);
|
||||
|
||||
using DB::GetWithMetadata;
|
||||
Status GetWithMetadata(const ReadOptions& options,
|
||||
ColumnFamilyHandle* column_family, const Slice& key,
|
||||
PinnableSlice* value,
|
||||
OutputMetadata* output_metadata) override;
|
||||
|
||||
using DB::MultiGet;
|
||||
// Note that CompactedDBImpl::MultiGet is not the optimized version of
|
||||
// MultiGet to use.
|
||||
@@ -42,6 +48,14 @@ class CompactedDBImpl : public DBImpl {
|
||||
std::string* timestamps, Status* statuses,
|
||||
const bool sorted_input);
|
||||
|
||||
using DB::MultiGetWithMetadata;
|
||||
void MultiGetWithMetadata(const ReadOptions& options, size_t num_keys,
|
||||
ColumnFamilyHandle* const* column_families,
|
||||
const Slice* keys, PinnableSlice* values,
|
||||
Status* statuses,
|
||||
MultiGetOutputMetadata* output_metadata,
|
||||
const bool sorted_input) override;
|
||||
|
||||
using DBImpl::Put;
|
||||
Status Put(const WriteOptions& /*options*/,
|
||||
ColumnFamilyHandle* /*column_family*/, const Slice& /*key*/,
|
||||
|
||||
+1317
-344
File diff suppressed because it is too large.
Load diff
+442
-64
@@ -9,6 +9,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
@@ -21,6 +22,7 @@
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
#include "db/column_family.h"
|
||||
@@ -50,9 +52,11 @@
|
||||
#include "db/write_controller.h"
|
||||
#include "db/write_thread.h"
|
||||
#include "logging/event_logger.h"
|
||||
#include "memtable/flush_initiator.h"
|
||||
#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"
|
||||
@@ -60,10 +64,10 @@
|
||||
#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"
|
||||
@@ -73,11 +77,17 @@
|
||||
#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;
|
||||
@@ -196,14 +206,22 @@ 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.
|
||||
class DBImpl : public DB {
|
||||
#if USE_COROUTINES
|
||||
class DBImpl : public DB,
|
||||
public CoroDB
|
||||
#else
|
||||
class DBImpl : public DB
|
||||
#endif
|
||||
{
|
||||
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 allowed
|
||||
// No copying or moving allowed
|
||||
DBImpl(const DBImpl&) = delete;
|
||||
void operator=(const DBImpl&) = delete;
|
||||
DBImpl(DBImpl&&) = delete;
|
||||
void operator=(DBImpl&&) = delete;
|
||||
|
||||
virtual ~DBImpl();
|
||||
|
||||
@@ -269,21 +287,31 @@ class DBImpl : public DB {
|
||||
bool HasAnyBlobDirectWriteColumnFamily();
|
||||
|
||||
using DB::Get;
|
||||
using DB::GetAsync;
|
||||
DECLARE_SYNC_ASYNC_AND_CALLBACK(
|
||||
Status, Get, GetAsync,
|
||||
(const ReadOptions& options, ColumnFamilyHandle* column_family,
|
||||
const Slice& key, PinnableSlice* value, std::string* timestamp,
|
||||
Status& status, AsyncCallback& callback),
|
||||
const ReadOptions& _read_options, ColumnFamilyHandle* column_family,
|
||||
const Slice& key, PinnableSlice* value, std::string* timestamp);
|
||||
DECLARE_SYNC_AND_ASYNC_OVERRIDE(Status, Get, const ReadOptions& _read_options,
|
||||
ColumnFamilyHandle* column_family,
|
||||
const Slice& key, PinnableSlice* value,
|
||||
std::string* timestamp);
|
||||
|
||||
using DB::GetWithMetadata;
|
||||
Status GetWithMetadata(const ReadOptions& _read_options,
|
||||
ColumnFamilyHandle* column_family, const Slice& key,
|
||||
PinnableSlice* value,
|
||||
OutputMetadata* output_metadata) override;
|
||||
|
||||
using DB::GetEntity;
|
||||
Status GetEntity(const ReadOptions& options,
|
||||
ColumnFamilyHandle* column_family, const Slice& key,
|
||||
PinnableWideColumns* columns) override;
|
||||
Status GetEntity(const ReadOptions& options, const Slice& key,
|
||||
PinnableAttributeGroups* result) override;
|
||||
DECLARE_SYNC_AND_ASYNC_OVERRIDE(Status, GetEntity,
|
||||
const ReadOptions& _read_options,
|
||||
ColumnFamilyHandle* column_family,
|
||||
const Slice& key,
|
||||
PinnableWideColumns* columns);
|
||||
DECLARE_SYNC_AND_ASYNC_OVERRIDE(Status, GetEntity,
|
||||
const ReadOptions& _read_options,
|
||||
const Slice& key,
|
||||
PinnableAttributeGroups* result);
|
||||
|
||||
Status GetEntityLazy(const ReadOptions& options,
|
||||
ColumnFamilyHandle* column_family, const Slice& key,
|
||||
LazyWideColumns* result) override;
|
||||
|
||||
using DB::GetMergeOperands;
|
||||
Status GetMergeOperands(const ReadOptions& options,
|
||||
@@ -301,7 +329,6 @@ class DBImpl : public DB {
|
||||
}
|
||||
|
||||
using DB::MultiGet;
|
||||
using DB::MultiGetAsync;
|
||||
// This MultiGet is a batched version, which may be faster than calling Get
|
||||
// multiple times, especially if the keys have some spatial locality that
|
||||
// enables them to be queried in the same SST files/set of files. The larger
|
||||
@@ -309,16 +336,22 @@ 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_ASYNC_AND_CALLBACK(
|
||||
void, MultiGet, MultiGetAsync,
|
||||
(const ReadOptions& options, const size_t num_keys,
|
||||
ColumnFamilyHandle** column_families, const Slice* keys,
|
||||
PinnableSlice* values, std::string* timestamps, Status* statuses,
|
||||
const bool sorted_input, AsyncCallback& callback),
|
||||
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);
|
||||
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);
|
||||
|
||||
using DB::MultiGetWithMetadata;
|
||||
void MultiGetWithMetadata(const ReadOptions& _read_options,
|
||||
const size_t num_keys,
|
||||
ColumnFamilyHandle* const* column_families,
|
||||
const Slice* keys, PinnableSlice* values,
|
||||
Status* statuses,
|
||||
MultiGetOutputMetadata* output_metadata,
|
||||
const bool sorted_input = false) override;
|
||||
|
||||
void MultiGetWithCallback(
|
||||
const ReadOptions& _read_options, ColumnFamilyHandle* column_family,
|
||||
@@ -340,6 +373,11 @@ 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,
|
||||
@@ -402,6 +440,9 @@ class DBImpl : public DB {
|
||||
Status NewIterators(const ReadOptions& _read_options,
|
||||
const std::vector<ColumnFamilyHandle*>& column_families,
|
||||
std::vector<Iterator*>* iterators) override;
|
||||
Status NewIterators(const std::vector<ReadOptions>& read_options,
|
||||
const std::vector<ColumnFamilyHandle*>& column_families,
|
||||
std::vector<Iterator*>* iterators) override;
|
||||
|
||||
using DB::NewMultiScan;
|
||||
std::unique_ptr<MultiScan> NewMultiScan(
|
||||
@@ -477,6 +518,8 @@ 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(
|
||||
@@ -573,10 +616,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<TransactionLogIterator>* iter,
|
||||
const TransactionLogIterator::ReadOptions& read_options =
|
||||
TransactionLogIterator::ReadOptions()) override;
|
||||
Status GetUpdatesSince(SequenceNumber seq_number,
|
||||
std::unique_ptr<WalIterator>* iter,
|
||||
const WalIterator::ReadOptions& read_options =
|
||||
WalIterator::ReadOptions()) override;
|
||||
Status DeleteFilesInRanges(ColumnFamilyHandle* column_family,
|
||||
const RangeOpt* ranges, size_t n,
|
||||
bool include_end = true);
|
||||
@@ -589,6 +632,35 @@ 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;
|
||||
@@ -717,6 +789,7 @@ class DBImpl : public DB {
|
||||
PinnableSlice* value = nullptr;
|
||||
PinnableWideColumns* columns = nullptr;
|
||||
std::string* timestamp = nullptr;
|
||||
bool* newer_version_present = nullptr;
|
||||
bool* value_found = nullptr;
|
||||
ReadCallback* callback = nullptr;
|
||||
bool* is_blob_index = nullptr;
|
||||
@@ -729,6 +802,36 @@ 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;
|
||||
|
||||
// Batched lazy read (MultiGetEntityLazy). When `lazy_columns_shared_sv` is
|
||||
// non-null, GetImpl reads against this externally-owned SuperVersion at
|
||||
// `lazy_columns_snapshot_seq` (the consistent per-batch sequence number)
|
||||
// instead of acquiring its own SuperVersion and deriving its own sequence
|
||||
// number, and it does NOT transfer a per-key pin -- the batch holds one
|
||||
// shared SuperVersion pin per column family. `lazy_columns_pin` must then
|
||||
// be null; `lazy_columns_version` / `lazy_columns_same_file_reader` are
|
||||
// still filled. (Single-key GetEntityLazy leaves this null and uses
|
||||
// `lazy_columns_pin`.)
|
||||
SuperVersion* lazy_columns_shared_sv = nullptr;
|
||||
SequenceNumber lazy_columns_snapshot_seq = kMaxSequenceNumber;
|
||||
};
|
||||
|
||||
DECLARE_SYNC_AND_ASYNC(Status, GetImpl, const ReadOptions& read_options,
|
||||
@@ -739,6 +842,11 @@ class DBImpl : public DB {
|
||||
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,
|
||||
bool* newer_version_present);
|
||||
|
||||
// Function that Get and KeyMayExist call with no_io true or false
|
||||
// Note: 'value_found' from KeyMayExist propagates here
|
||||
// This function is also called by GetMergeOperands
|
||||
@@ -750,6 +858,29 @@ class DBImpl : public DB {
|
||||
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);
|
||||
|
||||
// Batched-read counterpart of GetEntityLazyImpl for one key of
|
||||
// MultiGetEntityLazy: performs the lazy point lookup against the batch's
|
||||
// shared `super_version` at the batch's consistent `snapshot_seq` (rather
|
||||
// than acquiring its own), and binds the entity's resolver to that Version
|
||||
// without taking a per-key pin (the batch owns one shared pin per column
|
||||
// family).
|
||||
Status GetEntityLazyForBatch(const ReadOptions& read_options,
|
||||
ColumnFamilyHandle* column_family,
|
||||
SuperVersion* super_version,
|
||||
SequenceNumber snapshot_seq, const Slice& key,
|
||||
LazyWideColumns* result);
|
||||
|
||||
// If `snapshot` == kMaxSequenceNumber, set a recent one inside the file.
|
||||
ArenaWrappedDBIter* NewIteratorImpl(const ReadOptions& options,
|
||||
ColumnFamilyHandleImpl* cfh,
|
||||
@@ -901,6 +1032,13 @@ 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_;
|
||||
}
|
||||
@@ -1072,10 +1210,12 @@ class DBImpl : public DB {
|
||||
}
|
||||
};
|
||||
|
||||
using RecoveredTransactionMap =
|
||||
std::unordered_map<std::string, RecoveredTransaction*>;
|
||||
|
||||
bool allow_2pc() const { return immutable_db_options_.allow_2pc; }
|
||||
|
||||
std::unordered_map<std::string, RecoveredTransaction*>
|
||||
recovered_transactions() {
|
||||
RecoveredTransactionMap recovered_transactions() {
|
||||
return recovered_transactions_;
|
||||
}
|
||||
|
||||
@@ -1106,16 +1246,24 @@ class DBImpl : public DB {
|
||||
logs_with_prep_tracker_.MarkLogAsContainingPrepSection(log);
|
||||
}
|
||||
|
||||
void DeleteRecoveredTransaction(const std::string& name) {
|
||||
auto it = recovered_transactions_.find(name);
|
||||
// Deletes the recovered transaction `it` points to and returns the iterator
|
||||
// following it, like std::unordered_map::erase().
|
||||
RecoveredTransactionMap::iterator DeleteRecoveredTransaction(
|
||||
RecoveredTransactionMap::iterator it) {
|
||||
assert(it != recovered_transactions_.end());
|
||||
auto* trx = it->second;
|
||||
recovered_transactions_.erase(it);
|
||||
RecoveredTransactionMap::iterator next = recovered_transactions_.erase(it);
|
||||
for (const auto& info : trx->batches_) {
|
||||
logs_with_prep_tracker_.MarkLogAsHavingPrepSectionFlushed(
|
||||
info.second.log_number_);
|
||||
}
|
||||
delete trx;
|
||||
return next;
|
||||
}
|
||||
|
||||
void DeleteRecoveredTransaction(const std::string& name) {
|
||||
RecoveredTransactionMap::iterator it = recovered_transactions_.find(name);
|
||||
DeleteRecoveredTransaction(it);
|
||||
}
|
||||
|
||||
void DeleteAllRecoveredTransactions() {
|
||||
@@ -1196,6 +1344,9 @@ class DBImpl : public DB {
|
||||
|
||||
Status TEST_SwitchMemtable(ColumnFamilyData* cfd = nullptr);
|
||||
|
||||
size_t TEST_GetWBMFlushableMemUsage();
|
||||
bool TEST_IsWBMFlushInitiatorFlushable() const;
|
||||
|
||||
// Force current memtable contents to be flushed.
|
||||
Status TEST_FlushMemTable(bool wait = true, bool allow_write_stall = false,
|
||||
ColumnFamilyHandle* cfh = nullptr);
|
||||
@@ -1216,7 +1367,10 @@ class DBImpl : public DB {
|
||||
// finishes. For example in CompactRange.
|
||||
Status TEST_AtomicFlushMemTables(
|
||||
const autovector<ColumnFamilyData*>& provided_candidate_cfds,
|
||||
const FlushOptions& flush_opts);
|
||||
const FlushOptions& flush_opts, bool non_blocking_write_thread = false);
|
||||
|
||||
void TEST_BeginWriteStall();
|
||||
void TEST_EndWriteStall();
|
||||
|
||||
// Wait for background threads to complete scheduled work.
|
||||
Status TEST_WaitForBackgroundWork();
|
||||
@@ -1234,6 +1388,8 @@ class DBImpl : public DB {
|
||||
// Get the background error status
|
||||
Status TEST_GetBGError();
|
||||
|
||||
void TEST_SetBGError(const IOStatus& error, BackgroundErrorReason reason);
|
||||
|
||||
bool TEST_IsRecoveryInProgress();
|
||||
|
||||
Status TEST_ResumeImpl(DBRecoverContext context);
|
||||
@@ -1357,6 +1513,20 @@ class DBImpl : public DB {
|
||||
// REQUIRES: DB mutex held or during open
|
||||
void EnsureSeqnoToTimeMapping(const MinAndMaxPreserveSeconds& preserve_secs);
|
||||
|
||||
// Computes the seqno->time preserve-window lower bound from
|
||||
// seqno_to_time_mapping_ and stores it on cfd's current version, so
|
||||
// bottommost file marking does not mark files whose largest seqno cannot be
|
||||
// zeroed yet (which would loop). No-op for column families without
|
||||
// preserve/preclude enabled. Returns true if the stored value changed, so
|
||||
// callers can recompute bottommost marking when the boundary moves.
|
||||
// Note: right after opening an existing DB, seqno_to_time_mapping_ may not be
|
||||
// fully reconstructed, so this bound can be imprecise until the first
|
||||
// periodic RecordSeqnoToTimeMapping. That is safe: CompactionJob folds this
|
||||
// same bound into kBottommostFiles compactions, so any marked file still
|
||||
// makes progress (never loops), and the periodic task self-corrects the
|
||||
// bound. REQUIRES: DB mutex held
|
||||
bool MaybeUpdatePreserveTimeMinSeqno(ColumnFamilyData* cfd);
|
||||
|
||||
// Only called during open
|
||||
void PrepopulateSeqnoToTimeMapping(
|
||||
const MinAndMaxPreserveSeconds& preserve_secs);
|
||||
@@ -1393,6 +1563,21 @@ class DBImpl : public DB {
|
||||
}
|
||||
}
|
||||
|
||||
// Returns false when the wait times out while the DB is still blocked.
|
||||
bool BlockFor(uint64_t timeout_micros) {
|
||||
MutexLock lock(&state_mutex_);
|
||||
const std::chrono::microseconds deadline(
|
||||
SystemClock::Default()->NowMicros() + timeout_micros);
|
||||
while (state_ == State::BLOCKED) {
|
||||
TEST_SYNC_POINT("WBMStallInterface::BlockDB");
|
||||
if (SystemClock::Default()->TimedWait(&state_cv_, deadline) &&
|
||||
state_ == State::BLOCKED) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Called from WriteBufferManager. This function changes the state_
|
||||
// to State::RUNNING indicating the stall is cleared and DB can proceed.
|
||||
void Signal() override {
|
||||
@@ -1413,11 +1598,33 @@ class DBImpl : public DB {
|
||||
State state_;
|
||||
};
|
||||
|
||||
// Adapts DBImpl to the shared WriteBufferManager flush registry.
|
||||
class WBMFlushInitiator : public FlushInitiator {
|
||||
public:
|
||||
WBMFlushInitiator(DBImpl* db, bool atomic_flush)
|
||||
: FlushInitiator(atomic_flush), db_(db) {}
|
||||
|
||||
bool ScheduleFlush() override {
|
||||
return db_->ScheduleWriteBufferManagerFlush();
|
||||
}
|
||||
|
||||
bool TryRefreshMemoryAccounting() override {
|
||||
return db_->TryRefreshFlushableMemAccounting();
|
||||
}
|
||||
|
||||
private:
|
||||
DBImpl* const db_;
|
||||
};
|
||||
|
||||
static void TEST_ResetDbSessionIdGen();
|
||||
static std::string GenerateDbSessionId(Env* env);
|
||||
|
||||
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_;
|
||||
@@ -1426,6 +1633,9 @@ class DBImpl : public DB {
|
||||
// db_session_id_ is an identifier that gets reset
|
||||
// every time the DB is opened
|
||||
std::string db_session_id_;
|
||||
// Declared before versions_ so memtables cannot outlive their allocation
|
||||
// accounting target during destruction.
|
||||
std::unique_ptr<FlushInitiator> wbm_flush_initiator_;
|
||||
std::unique_ptr<VersionSet> versions_;
|
||||
// Flag to check whether we allocated and own the info log file
|
||||
bool own_info_log_;
|
||||
@@ -1437,8 +1647,7 @@ class DBImpl : public DB {
|
||||
FileSystemPtr fs_;
|
||||
MutableDBOptions mutable_db_options_;
|
||||
Statistics* stats_;
|
||||
std::unordered_map<std::string, RecoveredTransaction*>
|
||||
recovered_transactions_;
|
||||
RecoveredTransactionMap recovered_transactions_;
|
||||
std::unique_ptr<Tracer> tracer_;
|
||||
InstrumentedMutex trace_mutex_;
|
||||
BlockCacheTracer block_cache_tracer_;
|
||||
@@ -1539,6 +1748,15 @@ class DBImpl : public DB {
|
||||
edit_lists_[i].emplace_back(new VersionEdit(edit));
|
||||
}
|
||||
|
||||
bool HasVersionEdits() const {
|
||||
for (const auto& edit_list : edit_lists_) {
|
||||
if (!edit_list.empty()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
std::unordered_map<uint32_t, uint32_t> map_; // cf_id to index;
|
||||
autovector<ColumnFamilyData*> cfds_;
|
||||
autovector<autovector<VersionEdit*>> edit_lists_;
|
||||
@@ -1562,7 +1780,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();
|
||||
Status DeleteObsoleteOptionsFiles(bool schedule_only);
|
||||
|
||||
void NotifyOnManualFlushScheduled(autovector<ColumnFamilyData*> cfds,
|
||||
FlushReason flush_reason);
|
||||
@@ -1908,7 +2126,7 @@ class DBImpl : public DB {
|
||||
// LogAndApplyForRecovery should be called only once during recovery and it
|
||||
// should be called when RocksDB writes to a first new MANIFEST since this
|
||||
// recovery.
|
||||
Status LogAndApplyForRecovery(const RecoveryContext& recovery_ctx);
|
||||
Status LogAndApplyForRecovery(RecoveryContext& recovery_ctx);
|
||||
|
||||
// Schedule background work to open and validate SST files asynchronously.
|
||||
// Called when open_files_async is enabled.
|
||||
@@ -2457,7 +2675,7 @@ class DBImpl : public DB {
|
||||
|
||||
// Begin stalling of writes when memory usage increases beyond a certain
|
||||
// threshold.
|
||||
void WriteBufferManagerStallWrites();
|
||||
Status WriteBufferManagerStallWrites(WriteContext* write_context);
|
||||
|
||||
Status ThrottleLowPriWritesIfNeeded(const WriteOptions& write_options,
|
||||
WriteBatch* my_batch);
|
||||
@@ -2485,6 +2703,16 @@ class DBImpl : public DB {
|
||||
ReadOnlyMemTable* new_imm = nullptr,
|
||||
SequenceNumber last_seqno = 0);
|
||||
|
||||
// `refresh_wbm_accounting` can be false when a caller switches a batch of
|
||||
// memtables and refreshes the DB-wide accounting once after the batch.
|
||||
Status SwitchMemtableImpl(ColumnFamilyData* cfd, WriteContext* context,
|
||||
ReadOnlyMemTable* new_imm,
|
||||
SequenceNumber last_seqno,
|
||||
bool refresh_wbm_accounting);
|
||||
|
||||
// REQUIRES: mutex_ is held
|
||||
void UpdateWBMAccountingAfterMemtableSwitch(bool refresh_now);
|
||||
|
||||
// Select and output column families qualified for atomic flush in
|
||||
// `selected_cfds`. If `provided_candidate_cfds` is non-empty, it will be used
|
||||
// as candidate CFs to select qualified ones from. Otherwise, all column
|
||||
@@ -2509,6 +2737,18 @@ class DBImpl : public DB {
|
||||
const autovector<ColumnFamilyData*>& provided_candidate_cfds = {},
|
||||
bool entered_write_thread = false);
|
||||
|
||||
enum class WriteThreadJoinMode { kBlocking, kNonBlocking };
|
||||
|
||||
Status FlushMemTableImpl(ColumnFamilyData* cfd, const FlushOptions& options,
|
||||
FlushReason flush_reason, bool entered_write_thread,
|
||||
WriteThreadJoinMode join_mode, bool* made_progress);
|
||||
|
||||
Status AtomicFlushMemTablesImpl(
|
||||
const FlushOptions& options, FlushReason flush_reason,
|
||||
const autovector<ColumnFamilyData*>& provided_candidate_cfds,
|
||||
bool entered_write_thread, WriteThreadJoinMode join_mode,
|
||||
bool* made_progress);
|
||||
|
||||
// REQUIRES: mutex locked and write queues drained up to the recovery flush
|
||||
// fence that is about to switch memtables.
|
||||
void MaybeSyncLastSequenceWithAllocatedForRecovery(FlushReason flush_reason);
|
||||
@@ -2595,6 +2835,18 @@ class DBImpl : public DB {
|
||||
return static_cast<uint8_t*>(static_cast<void*>(this)) + type;
|
||||
}
|
||||
|
||||
// Checks DB-local write queues; manager-wide stall state would reject healthy
|
||||
// DBs. REQUIRES: mutex_ held.
|
||||
bool WouldBlockJoiningWriteThread() {
|
||||
mutex_.AssertHeld();
|
||||
return write_thread_.GetBegunCountOfOutstandingStall() != 0 ||
|
||||
(two_write_queues_ &&
|
||||
nonmem_write_thread_.GetBegunCountOfOutstandingStall() != 0);
|
||||
}
|
||||
|
||||
Status EnterWriteThreadForNonBlockingFlush(WriteThread::Writer* w,
|
||||
WriteThread::Writer* nonmem_w);
|
||||
|
||||
// REQUIRES: mutex locked and in write thread.
|
||||
void AssignAtomicFlushSeq(const autovector<ColumnFamilyData*>& cfds);
|
||||
|
||||
@@ -2604,6 +2856,31 @@ class DBImpl : public DB {
|
||||
// REQUIRES: mutex locked and in write thread.
|
||||
Status HandleWriteBufferManagerFlush(WriteContext* write_context);
|
||||
|
||||
// Column families and memory eligible for a WriteBufferManager flush.
|
||||
struct FlushableCFs {
|
||||
ColumnFamilyData* largest = nullptr; // most reclaimable memtable memory
|
||||
ColumnFamilyData* oldest = nullptr; // smallest memtable creation seq
|
||||
size_t largest_mem = 0;
|
||||
size_t total_mem = 0;
|
||||
};
|
||||
|
||||
// Shared selection for bidding and flushing. REQUIRES: mutex_ held.
|
||||
FlushableCFs CollectFlushableCFs(bool include_waiting_immutable);
|
||||
|
||||
// Registers an opened read-write DB without holding mutex_.
|
||||
void MaybeRegisterFlushInitiator();
|
||||
|
||||
// Refreshes the published mutable-memory counters after memtables change.
|
||||
// REQUIRES: mutex_ held.
|
||||
void RefreshFlushableMemAccounting();
|
||||
|
||||
bool TryRefreshFlushableMemAccounting();
|
||||
|
||||
// Queues one WBM flush; false lets the coordinator try another DB.
|
||||
bool ScheduleWriteBufferManagerFlush();
|
||||
|
||||
void BackgroundCallWBMFlush();
|
||||
|
||||
// REQUIRES: mutex locked
|
||||
Status PreprocessWrite(const WriteOptions& write_options,
|
||||
WalContext* log_context, WriteContext* write_context);
|
||||
@@ -2642,7 +2919,13 @@ class DBImpl : public DB {
|
||||
|
||||
// Used by WriteImpl to update bg_error_ when IO error happens, e.g., write
|
||||
// WAL, sync WAL fails, if paranoid check is enabled.
|
||||
void WALIOStatusCheck(const IOStatus& status);
|
||||
void WALIOStatusCheck(const IOStatus& status, uint64_t failed_wal_number = 0,
|
||||
SequenceNumber failed_wal_sequence = 0,
|
||||
SequenceNumber failed_wal_sequence_start = 0);
|
||||
|
||||
// Extends the inclusive WAL-number cutoff that must not receive more I/O.
|
||||
// This is lock-free because a WAL error can race with public SyncWAL().
|
||||
void ExtendWALRecoveryCutoff(uint64_t failed_wal_number);
|
||||
|
||||
// Used by WriteImpl to update bg_error_ in case of memtable insert error.
|
||||
void HandleMemTableInsertFailure(const Status& nonok_memtable_insert_status);
|
||||
@@ -2686,7 +2969,11 @@ class DBImpl : public DB {
|
||||
// equal to this per-column-family specified value, this flush request is
|
||||
// considered to have completed its work of flushing this column family.
|
||||
// After completing the work for all column families in this request, this
|
||||
// flush is considered complete.
|
||||
// flush is considered complete. EnqueuePendingFlush() acquires one
|
||||
// reference for each CFD when it successfully queues this request.
|
||||
// PopFirstFromFlushQueue() transfers responsibility for those references
|
||||
// to its caller, which must release each one with UnrefAndTryDelete() after
|
||||
// processing or discarding the request.
|
||||
std::unordered_map<ColumnFamilyData*, uint64_t>
|
||||
cfd_to_max_mem_id_to_persist;
|
||||
|
||||
@@ -2739,6 +3026,9 @@ class DBImpl : public DB {
|
||||
Env::Priority thread_pri);
|
||||
void BackgroundCallFlush(Env::Priority thread_pri);
|
||||
void BackgroundCallPurge();
|
||||
// Recursively removes all children of the DB session temporary directory.
|
||||
// Best effort: errors are logged, not returned. REQUIRES: mutex_ not held.
|
||||
void CleanupSessionTmpDir();
|
||||
Status BackgroundCompaction(bool* madeProgress, JobContext* job_context,
|
||||
LogBuffer* log_buffer,
|
||||
PrepickedCompaction* prepicked_compaction,
|
||||
@@ -2801,9 +3091,24 @@ 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.
|
||||
ColumnFamilyData* PickCompactionFromQueue(
|
||||
CompactionQueuePickResult 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,
|
||||
@@ -2989,7 +3294,9 @@ class DBImpl : public DB {
|
||||
ColumnFamilyHandle** column_families,
|
||||
const Slice* keys, PinnableSlice* values,
|
||||
PinnableWideColumns* columns, std::string* timestamps,
|
||||
Status* statuses, bool sorted_input);
|
||||
Status* statuses,
|
||||
std::vector<uint8_t>* newer_version_present,
|
||||
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
|
||||
@@ -3084,39 +3391,34 @@ 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 ReadOptions& read_options,
|
||||
const Slice& key,
|
||||
const Version* current,
|
||||
ColumnFamilyData* cfd,
|
||||
static Status ResolveDirectWritePlainValue(const Slice& key,
|
||||
const BlobFetcher& blob_fetcher,
|
||||
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 ReadOptions& read_options,
|
||||
const Slice& key,
|
||||
const Version* current,
|
||||
ColumnFamilyData* cfd,
|
||||
static Status ResolveDirectWriteWideColumns(const Slice& key,
|
||||
const BlobFetcher& blob_fetcher,
|
||||
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 Version* current,
|
||||
ColumnFamilyData* cfd, PinnableSlice* value, PinnableWideColumns* columns,
|
||||
Status* s, bool* is_blob_index, bool* value_found = nullptr);
|
||||
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 Version* current, ColumnFamilyData* cfd, PinnableSlice* value,
|
||||
const BlobFetcher* blob_fetcher, 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`. Unlike the direct-write helper above, this path only depends on
|
||||
// a BlobFetcher and therefore works for read-only/secondary DBs. Sets
|
||||
// `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
|
||||
@@ -3190,6 +3492,10 @@ 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
|
||||
@@ -3205,6 +3511,16 @@ class DBImpl : public DB {
|
||||
// * whenever a column family is dropped.
|
||||
InstrumentedCondVar bg_cv_;
|
||||
|
||||
// Set only while ResumeImpl performs a file-scoped WAL recovery. Protected
|
||||
// by mutex_; SwitchMemtable uses it to avoid touching the failed writer.
|
||||
bool recovering_from_wal_write_error_ = false;
|
||||
uint64_t recover_wal_through_number_ = 0;
|
||||
|
||||
// Once a file-scoped WAL error is reported, all writers through this
|
||||
// inclusive cutoff are quarantined until recovery detaches them. A
|
||||
// concurrent SyncWAL() reads this without taking the DB mutex.
|
||||
std::atomic<uint64_t> wal_recovery_cutoff_{0};
|
||||
|
||||
ColumnFamilyHandleImpl* persist_stats_cf_handle_ = nullptr;
|
||||
|
||||
bool persistent_stats_cfd_exists_ = true;
|
||||
@@ -3399,7 +3715,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 this list are all Ref()-erenced
|
||||
// Column families in these collections 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
|
||||
@@ -3414,9 +3730,23 @@ class DBImpl : public DB {
|
||||
// invariant(column family present in flush_queue_ <==>
|
||||
// ColumnFamilyData::pending_flush_ == true)
|
||||
std::deque<FlushRequest> flush_queue_;
|
||||
// invariant(column family present in compaction_queue_ <==>
|
||||
// ColumnFamilyData::pending_compaction_ == true)
|
||||
// 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.
|
||||
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_;
|
||||
@@ -3447,9 +3777,19 @@ 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;
|
||||
|
||||
// LOW avoids consuming a flush worker while joining the target write thread.
|
||||
static constexpr Env::Priority kWBMFlushPriority = Env::Priority::LOW;
|
||||
|
||||
// Outstanding cross-DB WBM flush jobs, drained during shutdown.
|
||||
int bg_wbm_flush_scheduled_ = 0;
|
||||
|
||||
// stores the number of flushes are currently running
|
||||
int num_running_flushes_ = 0;
|
||||
|
||||
@@ -3656,9 +3996,47 @@ class GetWithTimestampReadCallback : public ReadCallback {
|
||||
public:
|
||||
explicit GetWithTimestampReadCallback(SequenceNumber seq)
|
||||
: ReadCallback(seq) {}
|
||||
// A null result is used by MultiGet, whose per-key results live in
|
||||
// KeyContext/GetContext.
|
||||
void EnableNewerVersionTracking(SequenceNumber read_snapshot_seq,
|
||||
SequenceNumber upper_bound_seq,
|
||||
bool* single_key_result) {
|
||||
metadata_read_bounds_.emplace(
|
||||
MetadataReadBounds{read_snapshot_seq, upper_bound_seq});
|
||||
newer_version_present_ = single_key_result;
|
||||
}
|
||||
const MetadataReadBounds* GetMetadataReadBounds() const override {
|
||||
return metadata_read_bounds_.has_value() ? &*metadata_read_bounds_
|
||||
: nullptr;
|
||||
}
|
||||
bool NeedToTrackNewerVersions(
|
||||
const bool* per_key_result = nullptr) const override {
|
||||
const bool* result =
|
||||
per_key_result != nullptr ? per_key_result : newer_version_present_;
|
||||
return metadata_read_bounds_.has_value() && result != nullptr && !*result;
|
||||
}
|
||||
bool IsVisibleFullCheck(SequenceNumber seq) override {
|
||||
return seq <= max_visible_seq_;
|
||||
}
|
||||
bool IsNewerVisibleForMetadataRead(SequenceNumber seq) override {
|
||||
const MetadataReadBounds* bounds = GetMetadataReadBounds();
|
||||
return bounds != nullptr && bounds->read_snapshot_seq < seq &&
|
||||
seq <= bounds->newer_version_upper_bound_seq;
|
||||
}
|
||||
void MaybeRecordNewerVersion(SequenceNumber seq, ValueType type,
|
||||
bool* per_key_result = nullptr) override {
|
||||
bool* result =
|
||||
per_key_result != nullptr ? per_key_result : newer_version_present_;
|
||||
if (result != nullptr && !*result &&
|
||||
(IsValueType(type) || type == kTypeRangeDeletion) &&
|
||||
IsNewerVisibleForMetadataRead(seq)) {
|
||||
*result = true;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
std::optional<MetadataReadBounds> metadata_read_bounds_;
|
||||
bool* newer_version_present_ = nullptr;
|
||||
};
|
||||
|
||||
Options SanitizeOptions(const std::string& db, const Options& src,
|
||||
@@ -3770,7 +4148,7 @@ inline Status DBImpl::FailIfTsMismatchCf(ColumnFamilyHandle* column_family,
|
||||
inline Status DBImpl::FailIfTableFilterWithRangeConversion(
|
||||
const ReadOptions& read_options,
|
||||
const MutableCFOptions& mutable_cf_options) const {
|
||||
if (read_options.table_filter &&
|
||||
if (HasTableFilter(read_options) &&
|
||||
mutable_cf_options.min_tombstones_for_range_conversion > 0) {
|
||||
return Status::InvalidArgument(
|
||||
"ReadOptions::table_filter is not supported when "
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -144,6 +144,18 @@ Status DBImpl::TEST_SwitchMemtable(ColumnFamilyData* cfd) {
|
||||
return s;
|
||||
}
|
||||
|
||||
size_t DBImpl::TEST_GetWBMFlushableMemUsage() {
|
||||
InstrumentedMutexLock l(&mutex_);
|
||||
assert(wbm_flush_initiator_ != nullptr);
|
||||
RefreshFlushableMemAccounting();
|
||||
return wbm_flush_initiator_->GetFlushableMemUsage();
|
||||
}
|
||||
|
||||
bool DBImpl::TEST_IsWBMFlushInitiatorFlushable() const {
|
||||
assert(wbm_flush_initiator_ != nullptr);
|
||||
return wbm_flush_initiator_->IsFlushable();
|
||||
}
|
||||
|
||||
Status DBImpl::TEST_FlushMemTable(bool wait, bool allow_write_stall,
|
||||
ColumnFamilyHandle* cfh) {
|
||||
FlushOptions fo;
|
||||
@@ -182,9 +194,31 @@ Status DBImpl::TEST_FlushMemTableWithListenerWait(bool allow_write_stall,
|
||||
|
||||
Status DBImpl::TEST_AtomicFlushMemTables(
|
||||
const autovector<ColumnFamilyData*>& provided_candidate_cfds,
|
||||
const FlushOptions& flush_opts) {
|
||||
return AtomicFlushMemTables(flush_opts, FlushReason::kTest,
|
||||
provided_candidate_cfds);
|
||||
const FlushOptions& flush_opts, bool non_blocking_write_thread) {
|
||||
const auto join_mode = non_blocking_write_thread
|
||||
? WriteThreadJoinMode::kNonBlocking
|
||||
: WriteThreadJoinMode::kBlocking;
|
||||
return AtomicFlushMemTablesImpl(
|
||||
flush_opts, FlushReason::kTest, provided_candidate_cfds,
|
||||
false /* entered_write_thread */, join_mode, nullptr /* made_progress */);
|
||||
}
|
||||
|
||||
void DBImpl::TEST_BeginWriteStall() {
|
||||
InstrumentedMutexLock l(&mutex_);
|
||||
write_thread_.BeginWriteStall();
|
||||
if (wbm_flush_initiator_ != nullptr &&
|
||||
write_buffer_manager_->ShouldTrackFlushInitiator()) {
|
||||
wbm_flush_initiator_->SetFlushable(false);
|
||||
}
|
||||
}
|
||||
|
||||
void DBImpl::TEST_EndWriteStall() {
|
||||
InstrumentedMutexLock l(&mutex_);
|
||||
write_thread_.EndWriteStall();
|
||||
if (wbm_flush_initiator_ != nullptr &&
|
||||
write_buffer_manager_->ShouldTrackFlushInitiator()) {
|
||||
wbm_flush_initiator_->SetFlushable(true);
|
||||
}
|
||||
}
|
||||
|
||||
Status DBImpl::TEST_WaitForBackgroundWork() {
|
||||
@@ -225,6 +259,12 @@ Status DBImpl::TEST_GetBGError() {
|
||||
return error_handler_.GetBGError();
|
||||
}
|
||||
|
||||
void DBImpl::TEST_SetBGError(const IOStatus& error,
|
||||
BackgroundErrorReason reason) {
|
||||
InstrumentedMutexLock l(&mutex_);
|
||||
error_handler_.SetBGError(error, reason);
|
||||
}
|
||||
|
||||
bool DBImpl::TEST_IsRecoveryInProgress() {
|
||||
InstrumentedMutexLock l(&mutex_);
|
||||
return error_handler_.IsRecoveryInProgress();
|
||||
|
||||
@@ -140,7 +140,7 @@ Status DBImpl::PromoteL0(ColumnFamilyHandle* column_family, int target_level) {
|
||||
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->oldest_blob_file_number, f->oldest_ancestor_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,
|
||||
|
||||
+22
-10
@@ -55,6 +55,8 @@ 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;
|
||||
}
|
||||
@@ -487,31 +489,33 @@ void DBImpl::DeleteObsoleteFileImpl(int job_id, const std::string& fname,
|
||||
&file_deletion_status);
|
||||
if (file_deletion_status.ok()) {
|
||||
ROCKS_LOG_DEBUG(immutable_db_options_.info_log,
|
||||
"[JOB %d] Delete %s type=%d #%" PRIu64 " -- %s\n", job_id,
|
||||
fname.c_str(), type, number,
|
||||
"[JOB %d] [db_session_id=%s] Delete %s type=%d #%" PRIu64
|
||||
" -- %s\n",
|
||||
job_id, db_session_id_.c_str(), fname.c_str(), type, number,
|
||||
file_deletion_status.ToString().c_str());
|
||||
} else if (env_->FileExists(fname).IsNotFound()) {
|
||||
ROCKS_LOG_INFO(
|
||||
immutable_db_options_.info_log,
|
||||
"[JOB %d] Tried to delete a non-existing file %s type=%d #%" PRIu64
|
||||
" -- %s\n",
|
||||
job_id, fname.c_str(), type, number,
|
||||
"[JOB %d] [db_session_id=%s] Tried to delete a non-existing file %s"
|
||||
" type=%d #%" PRIu64 " -- %s\n",
|
||||
job_id, db_session_id_.c_str(), fname.c_str(), type, number,
|
||||
file_deletion_status.ToString().c_str());
|
||||
} else {
|
||||
ROCKS_LOG_ERROR(immutable_db_options_.info_log,
|
||||
"[JOB %d] Failed to delete %s type=%d #%" PRIu64 " -- %s\n",
|
||||
job_id, fname.c_str(), type, number,
|
||||
"[JOB %d] [db_session_id=%s] Failed to delete %s type=%d"
|
||||
" #%" PRIu64 " -- %s\n",
|
||||
job_id, db_session_id_.c_str(), fname.c_str(), type, number,
|
||||
file_deletion_status.ToString().c_str());
|
||||
}
|
||||
if (type == kTableFile) {
|
||||
EventHelpers::LogAndNotifyTableFileDeletion(
|
||||
&event_logger_, job_id, number, fname, file_deletion_status, GetName(),
|
||||
immutable_db_options_.listeners);
|
||||
db_session_id_, immutable_db_options_.listeners);
|
||||
}
|
||||
if (type == kBlobFile) {
|
||||
EventHelpers::LogAndNotifyBlobFileDeletion(
|
||||
&event_logger_, immutable_db_options_.listeners, job_id, number, fname,
|
||||
file_deletion_status, GetName());
|
||||
file_deletion_status, GetName(), db_session_id_);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1190,6 +1194,7 @@ Status DBImpl::MaybeUpdateNextFileNumber(RecoveryContext* recovery_ctx) {
|
||||
const uint64_t prev_next_file_number = versions_->current_next_file_number();
|
||||
uint64_t largest_file_number = prev_next_file_number;
|
||||
bool on_disk_file_advanced_counter = false;
|
||||
bool manifest_relevant_file_advanced_counter = false;
|
||||
Status s;
|
||||
for (const auto& path : CollectAllDBPaths()) {
|
||||
std::vector<std::string> files;
|
||||
@@ -1211,6 +1216,9 @@ Status DBImpl::MaybeUpdateNextFileNumber(RecoveryContext* recovery_ctx) {
|
||||
// NewFileNumber() would collide with it.
|
||||
if (number >= prev_next_file_number) {
|
||||
on_disk_file_advanced_counter = true;
|
||||
if (type != kOptionsFile && type != kTempFile) {
|
||||
manifest_relevant_file_advanced_counter = true;
|
||||
}
|
||||
}
|
||||
largest_file_number = std::max(largest_file_number, number);
|
||||
if ((type == kTableFile || type == kBlobFile)) {
|
||||
@@ -1232,7 +1240,8 @@ Status DBImpl::MaybeUpdateNextFileNumber(RecoveryContext* recovery_ctx) {
|
||||
mutable_db_options_.optimize_manifest_for_recovery &&
|
||||
!immutable_db_options_.best_efforts_recovery;
|
||||
|
||||
if (!optimize_manifest_for_recovery || on_disk_file_advanced_counter) {
|
||||
if (!optimize_manifest_for_recovery ||
|
||||
manifest_relevant_file_advanced_counter) {
|
||||
if (largest_file_number >= prev_next_file_number) {
|
||||
versions_->next_file_number_.store(largest_file_number + 1);
|
||||
}
|
||||
@@ -1245,6 +1254,9 @@ Status DBImpl::MaybeUpdateNextFileNumber(RecoveryContext* recovery_ctx) {
|
||||
assert(default_cfd);
|
||||
recovery_ctx->UpdateVersionEdits(default_cfd, edit);
|
||||
} else {
|
||||
if (on_disk_file_advanced_counter) {
|
||||
versions_->next_file_number_.store(largest_file_number + 1);
|
||||
}
|
||||
TEST_SYNC_POINT("DBImpl::Recovery:SkippedNoopEdit:NextFileNumber");
|
||||
}
|
||||
return s;
|
||||
|
||||
@@ -131,21 +131,21 @@ Status DBImplFollower::TryCatchUpWithLeader() {
|
||||
for (auto cfd : cfds_changed) {
|
||||
if (cfd->mem()->GetEarliestSequenceNumber() <
|
||||
versions_->LastSequence()) {
|
||||
// Construct a new memtable with earliest sequence number set to the
|
||||
// last sequence number in the VersionSet. This matters when
|
||||
// DBImpl::MultiCFSnapshot tries to get consistent references
|
||||
// to super versions in a lock free manner, it checks the earliest
|
||||
// sequence number to detect if there was a change in version in
|
||||
// the meantime.
|
||||
MemTable* new_mem = cfd->ConstructNewMemtable(
|
||||
cfd->GetLatestMutableCFOptions(), versions_->LastSequence());
|
||||
cfd->mem()->SetNextLogNumber(cfd->GetLogNumber());
|
||||
cfd->mem()->ConstructFragmentedRangeTombstones();
|
||||
cfd->imm()->Add(cfd->mem(), &job_context.memtables_to_free);
|
||||
new_mem->Ref();
|
||||
cfd->SetMemtable(new_mem);
|
||||
// Seal the active memtable so that its replacement gets its earliest
|
||||
// sequence number set to the last sequence number in the VersionSet.
|
||||
// This matters when DBImpl::MultiCFSnapshot tries to get consistent
|
||||
// references to super versions in a lock free manner, it checks the
|
||||
// earliest sequence number to detect if there was a change in
|
||||
// version in the meantime.
|
||||
SealActiveMemtable(cfd, cfd->GetLogNumber(),
|
||||
versions_->LastSequence(), &job_context);
|
||||
}
|
||||
|
||||
// `cfd->GetLogNumber()` is a safe watermark here, unlike in
|
||||
// DBImplSecondary::TryCatchUpWithPrimary(): this catch-up path never
|
||||
// replays WALs, so the memtables it collects hold nothing that only a
|
||||
// not-yet-installed Version could make readable.
|
||||
//
|
||||
// This will check if the old memtable is still referenced
|
||||
cfd->imm()->RemoveOldMemTables(cfd->GetLogNumber(),
|
||||
&job_context.memtables_to_free);
|
||||
@@ -153,6 +153,7 @@ Status DBImplFollower::TryCatchUpWithLeader() {
|
||||
cfd->InstallSuperVersion(&sv_context, &mutex_);
|
||||
sv_context.NewSuperVersion();
|
||||
}
|
||||
PublishSecondaryReadView();
|
||||
}
|
||||
|
||||
for (auto& file : files_to_delete) {
|
||||
@@ -164,6 +165,7 @@ Status DBImplFollower::TryCatchUpWithLeader() {
|
||||
}
|
||||
}
|
||||
}
|
||||
CleanupRetiredSecondaryReadViews();
|
||||
job_context.Clean();
|
||||
|
||||
// Cleanup unused, obsolete files.
|
||||
@@ -296,7 +298,8 @@ Status DB::OpenAsFollower(
|
||||
dbname, &impl->immutable_db_options_, impl->mutable_db_options_,
|
||||
impl->file_options_, impl->table_cache_.get(),
|
||||
impl->write_buffer_manager_, &impl->write_controller_, impl->io_tracer_,
|
||||
impl->db_id_, impl->db_session_id_));
|
||||
impl->db_id_, impl->db_session_id_,
|
||||
/*defer_sst_file_opening=*/false));
|
||||
impl->column_family_memtables_.reset(
|
||||
new ColumnFamilyMemTablesImpl(impl->versions_->GetColumnFamilySet()));
|
||||
impl->wal_in_db_path_ = impl->immutable_db_options_.IsWalDirSameAsDBPath();
|
||||
@@ -322,9 +325,11 @@ Status DB::OpenAsFollower(
|
||||
sv_context.NewSuperVersion();
|
||||
cfd->InstallSuperVersion(&sv_context, &impl->mutex_);
|
||||
}
|
||||
impl->PublishSecondaryReadView();
|
||||
impl->MarkAsyncFileOpenNotNeeded();
|
||||
}
|
||||
impl->mutex_.Unlock();
|
||||
impl->CleanupRetiredSecondaryReadViews();
|
||||
sv_context.Clean();
|
||||
if (s.ok()) {
|
||||
dbptr->reset(impl);
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
// 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 <string>
|
||||
#include <vector>
|
||||
|
||||
#include "rocksdb/db.h"
|
||||
#include "table/multiget_context.h"
|
||||
#include "util/autovector.h"
|
||||
|
||||
namespace ROCKSDB_NAMESPACE {
|
||||
|
||||
inline std::string* GetOutputTimestamp(OutputMetadata* output_metadata) {
|
||||
return output_metadata != nullptr && output_metadata->timestamp.has_value()
|
||||
? &*output_metadata->timestamp
|
||||
: nullptr;
|
||||
}
|
||||
|
||||
inline std::vector<std::string>* GetOutputTimestamps(
|
||||
MultiGetOutputMetadata* output_metadata) {
|
||||
return output_metadata != nullptr && output_metadata->timestamps.has_value()
|
||||
? &*output_metadata->timestamps
|
||||
: nullptr;
|
||||
}
|
||||
|
||||
inline bool* GetOutputNewerVersionPresent(OutputMetadata* output_metadata) {
|
||||
return output_metadata != nullptr &&
|
||||
output_metadata->newer_version_present.has_value()
|
||||
? &*output_metadata->newer_version_present
|
||||
: nullptr;
|
||||
}
|
||||
|
||||
inline std::vector<uint8_t>* GetOutputNewerVersionPresent(
|
||||
MultiGetOutputMetadata* output_metadata) {
|
||||
return output_metadata != nullptr &&
|
||||
output_metadata->newer_version_present.has_value()
|
||||
? &*output_metadata->newer_version_present
|
||||
: nullptr;
|
||||
}
|
||||
|
||||
inline ColumnFamilyHandle** MakeMutableCfHandles(
|
||||
ColumnFamilyHandle* const* column_families, size_t num_keys,
|
||||
autovector<ColumnFamilyHandle*, MultiGetContext::MAX_BATCH_SIZE>*
|
||||
stack_column_families,
|
||||
std::vector<ColumnFamilyHandle*>* heap_column_families) {
|
||||
ColumnFamilyHandle** mutable_column_families;
|
||||
if (num_keys <= MultiGetContext::MAX_BATCH_SIZE) {
|
||||
stack_column_families->resize(num_keys);
|
||||
mutable_column_families =
|
||||
num_keys == 0 ? nullptr : &(*stack_column_families)[0];
|
||||
} else {
|
||||
heap_column_families->resize(num_keys);
|
||||
mutable_column_families = heap_column_families->data();
|
||||
}
|
||||
for (size_t i = 0; i < num_keys; ++i) {
|
||||
mutable_column_families[i] = column_families[i];
|
||||
}
|
||||
return mutable_column_families;
|
||||
}
|
||||
|
||||
} // namespace ROCKSDB_NAMESPACE
|
||||
+80
-15
@@ -243,6 +243,11 @@ 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. ");
|
||||
@@ -678,7 +683,7 @@ Status DBImpl::Recover(
|
||||
f->marked_for_compaction,
|
||||
f->temperature, // this can be different from
|
||||
// `last_level_temperature`
|
||||
f->oldest_blob_file_number, f->oldest_ancester_time,
|
||||
f->oldest_blob_file_number, f->oldest_ancestor_time,
|
||||
f->file_creation_time, f->epoch_number,
|
||||
f->file_checksum, f->file_checksum_func_name,
|
||||
f->unique_id, f->compensated_range_deletion_size,
|
||||
@@ -1029,7 +1034,7 @@ Status DBImpl::InitPersistStatsColumnFamily() {
|
||||
return s;
|
||||
}
|
||||
|
||||
Status DBImpl::LogAndApplyForRecovery(const RecoveryContext& recovery_ctx) {
|
||||
Status DBImpl::LogAndApplyForRecovery(RecoveryContext& recovery_ctx) {
|
||||
mutex_.AssertHeld();
|
||||
// descriptor_log_ is normally null after Recover, but when
|
||||
// reuse_manifest_on_open is set VersionSet::Recover may have already
|
||||
@@ -1039,9 +1044,21 @@ Status DBImpl::LogAndApplyForRecovery(const RecoveryContext& recovery_ctx) {
|
||||
const ReadOptions read_options(Env::IOActivity::kDBOpen);
|
||||
const WriteOptions write_options(Env::IOActivity::kDBOpen);
|
||||
|
||||
if (versions_->force_new_manifest_on_open_ &&
|
||||
!recovery_ctx.HasVersionEdits()) {
|
||||
VersionEdit edit;
|
||||
ColumnFamilyData* default_cfd =
|
||||
versions_->GetColumnFamilySet()->GetDefault();
|
||||
assert(default_cfd);
|
||||
recovery_ctx.UpdateVersionEdits(default_cfd, edit);
|
||||
}
|
||||
|
||||
Status s = versions_->LogAndApply(recovery_ctx.cfds_, read_options,
|
||||
write_options, recovery_ctx.edit_lists_,
|
||||
&mutex_, directories_.GetDbDir());
|
||||
if (s.ok()) {
|
||||
versions_->force_new_manifest_on_open_ = false;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
@@ -2126,7 +2143,7 @@ Status DBImpl::WriteLevel0TableForRecovery(int job_id, ColumnFamilyData* cfd,
|
||||
immutable_db_options_.clock->GetCurrentTime(&_current_time)
|
||||
.PermitUncheckedError(); // ignore error
|
||||
const uint64_t current_time = static_cast<uint64_t>(_current_time);
|
||||
meta.oldest_ancester_time = current_time;
|
||||
meta.oldest_ancestor_time = current_time;
|
||||
meta.epoch_number = cfd->NewEpochNumber();
|
||||
{
|
||||
auto write_hint = cfd->current()->storage_info()->CalculateSSTWriteHint(
|
||||
@@ -2171,7 +2188,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);
|
||||
kMaxSequenceNumber, dbname_ /* db_name */);
|
||||
Version* version = cfd->current();
|
||||
version->Ref();
|
||||
TableProperties temp_table_proerties;
|
||||
@@ -2260,7 +2277,7 @@ Status DBImpl::WriteLevel0TableForRecovery(int job_id, ColumnFamilyData* cfd,
|
||||
meta.fd.GetFileSize(), meta.smallest, meta.largest,
|
||||
meta.fd.smallest_seqno, meta.fd.largest_seqno,
|
||||
meta.marked_for_compaction, meta.temperature,
|
||||
meta.oldest_blob_file_number, meta.oldest_ancester_time,
|
||||
meta.oldest_blob_file_number, meta.oldest_ancestor_time,
|
||||
meta.file_creation_time, meta.epoch_number,
|
||||
meta.file_checksum, meta.file_checksum_func_name,
|
||||
meta.unique_id, meta.compensated_range_deletion_size,
|
||||
@@ -2694,6 +2711,12 @@ Status DBImpl::Open(const DBOptions& db_options, const std::string& dbname,
|
||||
if (s.ok()) {
|
||||
s = impl->CreateArchivalDirectory();
|
||||
}
|
||||
if (s.ok() &&
|
||||
impl->immutable_db_options_.use_session_tmp_dir_for_remote_compaction) {
|
||||
// Create the session-scoped temporary directory before a CompactionService
|
||||
// can create any per-job directory under it.
|
||||
s = impl->env_->CreateDirIfMissing(SessionTmpDir(dbname));
|
||||
}
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
@@ -2768,8 +2791,9 @@ Status DBImpl::Open(const DBOptions& db_options, const std::string& dbname,
|
||||
s = WritableFileWriter::PrepareIOOptions(write_options, opts);
|
||||
}
|
||||
if (s.ok()) {
|
||||
s = log_writer->file()->Sync(opts,
|
||||
impl->immutable_db_options_.use_fsync);
|
||||
s = impl->immutable_db_options_.use_fsync
|
||||
? log_writer->file()->Fsync(opts)
|
||||
: log_writer->file()->Sync(opts);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2872,11 +2896,16 @@ 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();
|
||||
@@ -2903,6 +2932,13 @@ Status DBImpl::Open(const DBOptions& db_options, const std::string& dbname,
|
||||
impl->immutable_db_options_.db_paths[0].path);
|
||||
}
|
||||
|
||||
if (s.ok() &&
|
||||
impl->immutable_db_options_.use_session_tmp_dir_for_remote_compaction) {
|
||||
// Finish deleting data from the previous DB session before this open can
|
||||
// schedule a new compaction in the directory.
|
||||
impl->CleanupSessionTmpDir();
|
||||
}
|
||||
|
||||
if (s.ok()) {
|
||||
// When the DB is stopped, it's possible that there are some .trash files
|
||||
// that were not deleted yet, when we open the DB we will find these .trash
|
||||
@@ -2944,8 +2980,9 @@ Status DBImpl::Open(const DBOptions& db_options, const std::string& dbname,
|
||||
IOOptions opts;
|
||||
s = WritableFileWriter::PrepareIOOptions(write_options, opts);
|
||||
if (s.ok()) {
|
||||
s = log_writer->file()->Sync(opts,
|
||||
impl->immutable_db_options_.use_fsync);
|
||||
s = impl->immutable_db_options_.use_fsync
|
||||
? log_writer->file()->Fsync(opts)
|
||||
: log_writer->file()->Sync(opts);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2966,7 +3003,20 @@ 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()) {
|
||||
// Register only after open succeeds and without holding the DB mutex.
|
||||
impl->MaybeRegisterFlushInitiator();
|
||||
*dbptr = std::move(impl);
|
||||
} else {
|
||||
for (auto* h : *handles) {
|
||||
@@ -3024,8 +3074,18 @@ void DBImpl::ScheduleAsyncFileOpening() {
|
||||
bg_async_file_open_state_ = AsyncFileOpenState::kScheduled;
|
||||
|
||||
// since this is a one time job, best to schedule it with high priority
|
||||
auto unschedule_callback = [](void* arg) {
|
||||
auto* unscheduled_ctx = static_cast<AsyncFileOpenContext*>(arg);
|
||||
DBImpl* db = unscheduled_ctx->db;
|
||||
db->mutex_.AssertHeld();
|
||||
delete unscheduled_ctx;
|
||||
db->bg_async_file_open_state_ = AsyncFileOpenState::kComplete;
|
||||
db->bg_cv_.SignalAll();
|
||||
TEST_SYNC_POINT("DBImpl::UnscheduleAsyncFileOpenCallback");
|
||||
TEST_SYNC_POINT("DBImpl::BGWorkAsyncFileOpen:Done");
|
||||
};
|
||||
env_->Schedule(&DBImpl::BGWorkAsyncFileOpen, ctx, Env::Priority::HIGH,
|
||||
nullptr);
|
||||
&bg_async_file_open_state_, unschedule_callback);
|
||||
}
|
||||
|
||||
void DBImpl::MarkAsyncFileOpenNotNeeded() {
|
||||
@@ -3055,8 +3115,9 @@ void DBImpl::BGWorkAsyncFileOpen(void* arg) {
|
||||
auto* version = ctx->versions[i];
|
||||
ColumnFamilyData* cfd = version->cfd();
|
||||
|
||||
// Skip column families that were dropped after scheduling
|
||||
if (cfd->IsDropped()) {
|
||||
// Retained secondary handles remain readable after the primary drops the
|
||||
// column family, so their captured Versions still need pinned readers.
|
||||
if (cfd->IsDropped() && !db->read_only_) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -3086,11 +3147,15 @@ void DBImpl::BGWorkAsyncFileOpen(void* arg) {
|
||||
if (!s.ok()) {
|
||||
ROCKS_LOG_ERROR(
|
||||
db->immutable_db_options_.info_log,
|
||||
"BGWorkAsyncFileOpen: LoadTableHandlers failed for CF %s: "
|
||||
"%s",
|
||||
"BGWorkAsyncFileOpen: file validation/opening failed for CF %s: %s",
|
||||
cfd->GetName().c_str(), s.ToString().c_str());
|
||||
InstrumentedMutexLock l(&db->mutex_);
|
||||
db->error_handler_.SetBGError(s, BackgroundErrorReason::kAsyncFileOpen);
|
||||
if (db->read_only_) {
|
||||
db->error_handler_.SetBGErrorNoAutoRecovery(
|
||||
s, BackgroundErrorReason::kAsyncFileOpen);
|
||||
} else {
|
||||
db->error_handler_.SetBGError(s, BackgroundErrorReason::kAsyncFileOpen);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
+114
-43
@@ -11,6 +11,7 @@
|
||||
#include "db/blob/blob_fetcher.h"
|
||||
#include "db/db_impl/compacted_db_impl.h"
|
||||
#include "db/db_impl/db_impl.h"
|
||||
#include "db/db_impl/db_impl_metadata.h"
|
||||
#include "db/manifest_ops.h"
|
||||
#include "db/merge_context.h"
|
||||
#include "logging/logging.h"
|
||||
@@ -30,6 +31,30 @@ DBImplReadOnly::DBImplReadOnly(const DBOptions& db_options,
|
||||
|
||||
DBImplReadOnly::~DBImplReadOnly() = default;
|
||||
|
||||
void DBImplReadOnly::MultiGetWithMetadata(
|
||||
const ReadOptions& options, const size_t num_keys,
|
||||
ColumnFamilyHandle* const* column_families, const Slice* keys,
|
||||
PinnableSlice* values, Status* statuses,
|
||||
MultiGetOutputMetadata* output_metadata, const bool sorted_input) {
|
||||
std::vector<std::string>* timestamps = GetOutputTimestamps(output_metadata);
|
||||
if (timestamps != nullptr) {
|
||||
timestamps->resize(num_keys);
|
||||
}
|
||||
std::vector<uint8_t>* newer_version_present =
|
||||
GetOutputNewerVersionPresent(output_metadata);
|
||||
if (newer_version_present != nullptr) {
|
||||
newer_version_present->assign(num_keys, false);
|
||||
}
|
||||
autovector<ColumnFamilyHandle*, MultiGetContext::MAX_BATCH_SIZE>
|
||||
stack_column_families;
|
||||
std::vector<ColumnFamilyHandle*> heap_column_families;
|
||||
ColumnFamilyHandle** mutable_column_families = MakeMutableCfHandles(
|
||||
column_families, num_keys, &stack_column_families, &heap_column_families);
|
||||
DBImpl::MultiGet(options, num_keys, mutable_column_families, keys, values,
|
||||
timestamps != nullptr ? timestamps->data() : nullptr,
|
||||
statuses, sorted_input);
|
||||
}
|
||||
|
||||
Iterator* DBImplReadOnly::NewIterator(const ReadOptions& _read_options,
|
||||
ColumnFamilyHandle* column_family) {
|
||||
if (_read_options.io_activity != Env::IOActivity::kUnknown &&
|
||||
@@ -82,65 +107,111 @@ Status DBImplReadOnly::NewIterators(
|
||||
const ReadOptions& read_options,
|
||||
const std::vector<ColumnFamilyHandle*>& column_families,
|
||||
std::vector<Iterator*>* iterators) {
|
||||
if (read_options.timestamp) {
|
||||
for (auto* cf : column_families) {
|
||||
assert(cf);
|
||||
const Status s = FailIfTsMismatchCf(cf, *(read_options.timestamp));
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (auto* cf : column_families) {
|
||||
assert(cf);
|
||||
const Status s = FailIfCfHasTs(cf);
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
}
|
||||
return NewIterators(
|
||||
std::vector<ReadOptions>(column_families.size(), read_options),
|
||||
column_families, iterators);
|
||||
}
|
||||
|
||||
ReadCallback* read_callback = nullptr; // No read callback provided.
|
||||
Status DBImplReadOnly::NewIterators(
|
||||
const std::vector<ReadOptions>& read_options,
|
||||
const std::vector<ColumnFamilyHandle*>& column_families,
|
||||
std::vector<Iterator*>* iterators) {
|
||||
if (read_options.size() != column_families.size()) {
|
||||
return Status::InvalidArgument(
|
||||
"read_options and column_families must have the same size");
|
||||
}
|
||||
if (iterators == nullptr) {
|
||||
return Status::InvalidArgument("iterators not allowed to be nullptr");
|
||||
}
|
||||
|
||||
if (column_families.empty()) {
|
||||
iterators->clear();
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
const Snapshot* const snapshot = read_options.front().snapshot;
|
||||
const bool tailing = read_options.front().tailing;
|
||||
std::vector<ReadOptions> normalized_read_options;
|
||||
normalized_read_options.reserve(read_options.size());
|
||||
for (size_t i = 0; i < read_options.size(); ++i) {
|
||||
const ReadOptions& options = read_options[i];
|
||||
if (options.io_activity != Env::IOActivity::kUnknown &&
|
||||
options.io_activity != Env::IOActivity::kDBIterator) {
|
||||
return Status::InvalidArgument(
|
||||
"Can only call NewIterators with `ReadOptions::io_activity` is "
|
||||
"`Env::IOActivity::kUnknown` or `Env::IOActivity::kDBIterator`");
|
||||
}
|
||||
if (options.read_tier == kPersistedTier) {
|
||||
return Status::NotSupported(
|
||||
"ReadTier::kPersistedData is not yet supported in iterators.");
|
||||
}
|
||||
if (options.snapshot != snapshot) {
|
||||
return Status::InvalidArgument(
|
||||
"All ReadOptions must use the same snapshot");
|
||||
}
|
||||
if (options.tailing != tailing) {
|
||||
return Status::InvalidArgument(
|
||||
"All ReadOptions must use the same tailing setting");
|
||||
}
|
||||
|
||||
auto* cf = column_families[i];
|
||||
assert(cf);
|
||||
Status s;
|
||||
if (options.timestamp) {
|
||||
s = FailIfTsMismatchCf(cf, *(options.timestamp));
|
||||
} else {
|
||||
s = FailIfCfHasTs(cf);
|
||||
}
|
||||
if (!s.ok()) {
|
||||
return s;
|
||||
}
|
||||
|
||||
normalized_read_options.emplace_back(options);
|
||||
if (normalized_read_options.back().io_activity ==
|
||||
Env::IOActivity::kUnknown) {
|
||||
normalized_read_options.back().io_activity = Env::IOActivity::kDBIterator;
|
||||
}
|
||||
}
|
||||
|
||||
iterators->clear();
|
||||
iterators->reserve(column_families.size());
|
||||
SequenceNumber latest_snapshot = versions_->LastSequence();
|
||||
|
||||
SequenceNumber read_seq =
|
||||
read_options.snapshot != nullptr
|
||||
? static_cast<const SnapshotImpl*>(read_options.snapshot)->number_
|
||||
: latest_snapshot;
|
||||
|
||||
snapshot != nullptr ? static_cast<const SnapshotImpl*>(snapshot)->number_
|
||||
: versions_->LastSequence();
|
||||
autovector<std::tuple<ColumnFamilyHandleImpl*, SuperVersion*>> cfh_to_sv;
|
||||
for (auto* cf : column_families) {
|
||||
auto* cfh = static_cast_with_check<ColumnFamilyHandleImpl>(cf);
|
||||
cfh_to_sv.emplace_back(cfh, cfh->cfd()->GetSuperVersion()->Ref());
|
||||
}
|
||||
|
||||
const bool check_read_ts =
|
||||
read_options.timestamp && read_options.timestamp->size() > 0;
|
||||
for (auto cfh : column_families) {
|
||||
auto* cfd = static_cast_with_check<ColumnFamilyHandleImpl>(cfh)->cfd();
|
||||
auto* sv = cfd->GetSuperVersion()->Ref();
|
||||
cfh_to_sv.emplace_back(static_cast_with_check<ColumnFamilyHandleImpl>(cfh),
|
||||
sv);
|
||||
if (check_read_ts) {
|
||||
const auto unref_super_versions = [&]() {
|
||||
for (const auto& entry : cfh_to_sv) {
|
||||
std::get<1>(entry)->Unref();
|
||||
}
|
||||
};
|
||||
for (size_t i = 0; i < cfh_to_sv.size(); ++i) {
|
||||
const ReadOptions& options = normalized_read_options[i];
|
||||
if (options.timestamp && !options.timestamp->empty()) {
|
||||
auto* cfd = std::get<0>(cfh_to_sv[i])->cfd();
|
||||
auto* sv = std::get<1>(cfh_to_sv[i]);
|
||||
const Status s =
|
||||
FailIfReadCollapsedHistory(cfd, sv, *(read_options.timestamp));
|
||||
FailIfReadCollapsedHistory(cfd, sv, *(options.timestamp));
|
||||
if (!s.ok()) {
|
||||
for (auto prev_entry : cfh_to_sv) {
|
||||
std::get<1>(prev_entry)->Unref();
|
||||
}
|
||||
unref_super_versions();
|
||||
return s;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert(cfh_to_sv.size() == column_families.size());
|
||||
for (auto [cfh, sv] : cfh_to_sv) {
|
||||
auto* db_iter = NewArenaWrappedDbIterator(
|
||||
env_, read_options, cfh, sv, read_seq, read_callback, this,
|
||||
/*expose_blob_index=*/false, /*allow_refresh=*/false,
|
||||
/*allow_mark_memtable_for_flush=*/false);
|
||||
iterators->push_back(db_iter);
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < cfh_to_sv.size(); ++i) {
|
||||
auto* cfh = std::get<0>(cfh_to_sv[i]);
|
||||
auto* sv = std::get<1>(cfh_to_sv[i]);
|
||||
iterators->push_back(NewArenaWrappedDbIterator(
|
||||
env_, normalized_read_options[i], cfh, sv, read_seq,
|
||||
nullptr /* read_callback */, this, /* expose_blob_index */ false,
|
||||
/* allow_refresh */ false, /* allow_mark_memtable_for_flush */ false));
|
||||
}
|
||||
return Status::OK();
|
||||
}
|
||||
|
||||
|
||||
@@ -28,7 +28,13 @@ class DBImplReadOnly : public DBImpl {
|
||||
const Slice& key,
|
||||
GetImplOptions& get_impl_options);
|
||||
|
||||
// TODO: Implement ReadOnly MultiGet?
|
||||
using DBImpl::MultiGetWithMetadata;
|
||||
void MultiGetWithMetadata(const ReadOptions& options, const size_t num_keys,
|
||||
ColumnFamilyHandle* const* column_families,
|
||||
const Slice* keys, PinnableSlice* values,
|
||||
Status* statuses,
|
||||
MultiGetOutputMetadata* output_metadata,
|
||||
const bool sorted_input = false) override;
|
||||
|
||||
using DBImpl::NewIterator;
|
||||
Iterator* NewIterator(const ReadOptions& _read_options,
|
||||
@@ -37,6 +43,9 @@ class DBImplReadOnly : public DBImpl {
|
||||
Status NewIterators(const ReadOptions& options,
|
||||
const std::vector<ColumnFamilyHandle*>& column_families,
|
||||
std::vector<Iterator*>* iterators) override;
|
||||
Status NewIterators(const std::vector<ReadOptions>& read_options,
|
||||
const std::vector<ColumnFamilyHandle*>& column_families,
|
||||
std::vector<Iterator*>* iterators) override;
|
||||
|
||||
using DBImpl::Put;
|
||||
Status Put(const WriteOptions& /*options*/,
|
||||
|
||||
@@ -20,6 +20,10 @@ DEFINE_SYNC_AND_ASYNC(Status, DBImplReadOnly::GetImpl)
|
||||
get_impl_options.merge_operands != nullptr);
|
||||
assert(get_impl_options.column_family);
|
||||
|
||||
// This instance cannot observe writes after one of its snapshots, so the
|
||||
// false result initialized by GetWithMetadata is definitive.
|
||||
get_impl_options.newer_version_present = nullptr;
|
||||
|
||||
Status s;
|
||||
|
||||
if (read_options.timestamp) {
|
||||
@@ -49,7 +53,13 @@ DEFINE_SYNC_AND_ASYNC(Status, DBImplReadOnly::GetImpl)
|
||||
|
||||
const Comparator* ucmp = get_impl_options.column_family->GetComparator();
|
||||
assert(ucmp);
|
||||
SequenceNumber snapshot = versions_->LastSequence();
|
||||
// For a batched lazy read (MultiGetEntityLazy), use the SuperVersion and
|
||||
// consistent sequence number the batch already fixed (see
|
||||
// GetImplOptions::lazy_columns_shared_sv); otherwise this read-only
|
||||
// instance's stable current SuperVersion and last sequence.
|
||||
SequenceNumber snapshot = get_impl_options.lazy_columns_shared_sv != nullptr
|
||||
? get_impl_options.lazy_columns_snapshot_seq
|
||||
: versions_->LastSequence();
|
||||
GetWithTimestampReadCallback read_cb(snapshot);
|
||||
auto cfh = static_cast_with_check<ColumnFamilyHandleImpl>(
|
||||
get_impl_options.column_family);
|
||||
@@ -77,7 +87,10 @@ DEFINE_SYNC_AND_ASYNC(Status, DBImplReadOnly::GetImpl)
|
||||
|
||||
// In read-only mode Get(), no super version operation is needed (i.e.
|
||||
// GetAndRefSuperVersion and ReturnAndCleanupSuperVersion)
|
||||
SuperVersion* super_version = cfd->GetSuperVersion();
|
||||
SuperVersion* super_version =
|
||||
get_impl_options.lazy_columns_shared_sv != nullptr
|
||||
? get_impl_options.lazy_columns_shared_sv
|
||||
: cfd->GetSuperVersion();
|
||||
if (read_options.timestamp && read_options.timestamp->size() > 0) {
|
||||
s = FailIfReadCollapsedHistory(cfd, super_version,
|
||||
*(read_options.timestamp));
|
||||
@@ -128,7 +141,8 @@ DEFINE_SYNC_AND_ASYNC(Status, DBImplReadOnly::GetImpl)
|
||||
/*value_found*/ nullptr,
|
||||
/*key_exists*/ nullptr, /*seq*/ nullptr, &read_cb,
|
||||
/*is_blob*/ nullptr,
|
||||
/*do_merge=*/get_impl_options.get_value);
|
||||
/*do_merge=*/get_impl_options.get_value,
|
||||
get_impl_options.lazy_columns_same_file_reader);
|
||||
RecordTick(stats_, MEMTABLE_MISS);
|
||||
}
|
||||
{
|
||||
@@ -156,6 +170,21 @@ DEFINE_SYNC_AND_ASYNC(Status, DBImplReadOnly::GetImpl)
|
||||
PERF_COUNTER_ADD(get_read_bytes, size);
|
||||
}
|
||||
}
|
||||
if (get_impl_options.lazy_columns_version != nullptr && s.ok()) {
|
||||
// Lazy result (GetEntityLazy / MultiGetEntityLazy): hand back the Version
|
||||
// the entity's blob references must be resolved against (both the
|
||||
// single-key and batched paths).
|
||||
*get_impl_options.lazy_columns_version = super_version->current;
|
||||
}
|
||||
if (get_impl_options.lazy_columns_pin != nullptr && s.ok()) {
|
||||
// Single-key GetEntityLazy: 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. The batched path passes no pin (it
|
||||
// uses lazy_columns_shared_sv); the batch holds one shared pin per column
|
||||
// family instead.
|
||||
TransferSuperVersionPin(super_version, get_impl_options.lazy_columns_pin);
|
||||
}
|
||||
CO_RETURN s;
|
||||
}
|
||||
|
||||
|
||||
+891
-138
File diff suppressed because it is too large.
Load diff
Loaded 100 of 493 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user