Repository: dgraph-io/badger
Branch: main
Commit: 796cb85f662c
Files: 136
Total size: 1.1 MB
Directory structure:
gitextract_mc7da0i7/
├── .github/
│ ├── CODEOWNERS
│ ├── ISSUE_TEMPLATE/
│ │ ├── bug_report.md
│ │ ├── config.yml
│ │ └── feature_request.md
│ ├── PULL_REQUEST_TEMPLATE.md
│ ├── renovate.json
│ └── workflows/
│ ├── cd-badger.yml
│ ├── ci-badger-bank-tests-nightly.yml
│ ├── ci-badger-bank-tests.yml
│ ├── ci-badger-tests.yml
│ ├── ci-dgraph-tests.yml
│ └── trunk.yml
├── .gitignore
├── .trunk/
│ ├── .gitignore
│ ├── configs/
│ │ ├── .checkov.yaml
│ │ ├── .markdownlint.json
│ │ ├── .prettierrc
│ │ ├── .shellcheckrc
│ │ ├── .yamllint.yaml
│ │ └── svgo.config.mjs
│ └── trunk.yaml
├── .vscode/
│ ├── extensions.json
│ └── settings.json
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── Makefile
├── README.md
├── SECURITY.md
├── VERSIONING.md
├── backup.go
├── backup_test.go
├── batch.go
├── batch_test.go
├── changes.sh
├── compaction.go
├── contrib/
│ └── RELEASE.md
├── db.go
├── db2_test.go
├── db_test.go
├── dir_aix.go
├── dir_other.go
├── dir_plan9.go
├── dir_unix.go
├── dir_windows.go
├── discard.go
├── discard_test.go
├── doc.go
├── docs/
│ ├── design.md
│ ├── encryption-at-rest.md
│ ├── index.md
│ ├── quickstart.md
│ └── troubleshooting.md
├── errors.go
├── fb/
│ ├── BlockOffset.go
│ ├── TableIndex.go
│ ├── flatbuffer.fbs
│ ├── gen.sh
│ └── install_flatbuffers.sh
├── go.mod
├── go.sum
├── histogram.go
├── histogram_test.go
├── integration/
│ └── testgc/
│ ├── .gitignore
│ └── main.go
├── iterator.go
├── iterator_test.go
├── key_registry.go
├── key_registry_test.go
├── level_handler.go
├── levels.go
├── levels_test.go
├── logger.go
├── logger_test.go
├── managed_db.go
├── managed_db_test.go
├── manifest.go
├── manifest_test.go
├── memtable.go
├── merge.go
├── merge_test.go
├── metrics_test.go
├── options/
│ └── options.go
├── options.go
├── options_test.go
├── pb/
│ ├── badgerpb4.pb.go
│ ├── badgerpb4.proto
│ ├── gen.sh
│ └── protos_test.go
├── publisher.go
├── publisher_test.go
├── skl/
│ ├── README.md
│ ├── arena.go
│ ├── skl.go
│ └── skl_test.go
├── stream.go
├── stream_test.go
├── stream_writer.go
├── stream_writer_test.go
├── structs.go
├── structs_test.go
├── table/
│ ├── README.md
│ ├── builder.go
│ ├── builder_test.go
│ ├── iterator.go
│ ├── merge_iterator.go
│ ├── merge_iterator_test.go
│ ├── table.go
│ └── table_test.go
├── test.sh
├── test_extensions.go
├── trie/
│ ├── trie.go
│ └── trie_test.go
├── txn.go
├── txn_test.go
├── util.go
├── value.go
├── value_test.go
├── watermark_edge_test.go
└── y/
├── bloom.go
├── bloom_test.go
├── checksum.go
├── checksum_test.go
├── encrypt.go
├── encrypt_test.go
├── error.go
├── error_test.go
├── file_dsync.go
├── file_nodsync.go
├── iterator.go
├── metrics.go
├── watermark.go
├── y.go
├── y_test.go
└── zstd.go
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/CODEOWNERS
================================================
# CODEOWNERS info: https://help.github.com/en/articles/about-code-owners
# Owners are automatically requested for review for PRs that changes code
# that they own.
* @dgraph-io/maintainers
================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.md
================================================
---
name: Bug report
about: Create a report to help us improve
title: ""
labels: bug
assignees: ""
---
## Describe the bug
A clear and concise description of what the bug is.
## To Reproduce
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
## Expected behavior
A clear and concise description of what you expected to happen.
## Screenshots
If applicable, add screenshots to help explain your problem.
## Environment
- OS: [e.g. macOS, Windows, Ubuntu]
- Language [e.g. AssemblyScript, Go]
- Version [e.g. v0.xx]
## Additional context
Add any other context about the problem here.
================================================
FILE: .github/ISSUE_TEMPLATE/config.yml
================================================
blank_issues_enabled: false
contact_links:
- name: Badger Community Support
url: https://github.com/orgs/dgraph-io/discussions
about: Please ask and answer questions here
================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.md
================================================
---
name: Feature request
about: Suggest an idea for this project
title: ""
labels: ""
assignees: ""
---
## Is your feature request related to a problem? Please describe
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
## Describe the solution you'd like
A clear and concise description of what you want to happen.
## Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.
## Additional context
Add any other context or screenshots about the feature request here.
================================================
FILE: .github/PULL_REQUEST_TEMPLATE.md
================================================
**Description**
Please explain the changes you made here.
**Checklist**
- [ ] Code compiles correctly and linting passes locally
- [ ] Tests added for new functionality, or regression tests for bug fixes added as applicable
**Instructions**
- The PR title should follow the [Conventional Commits](https://www.conventionalcommits.org/)
syntax, leading with `fix:`, `feat:`, `chore:`, `ci:`, etc.
- The description should briefly explain what the PR is about. In the case of a bugfix, describe or
link to the bug.
- In the checklist section, check the boxes in that are applicable, using `[x]` syntax.
- If not applicable, remove the entire line. Only leave the box unchecked if you intend to come
back and check the box later.
- Delete the `Instructions` line and everything below it, to indicate you have read and are
following these instructions. 🙂
Thank you for your contribution to Badger!
================================================
FILE: .github/renovate.json
================================================
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": ["local>dgraph-io/renovate-config"],
"rangeStrategy": "widen",
"packageRules": [
{ "matchManagers": ["gomod"], "matchPackageNames": ["go"], "enabled": false },
{ "matchManagers": ["gomod"], "matchDepNames": ["go"], "enabled": false }
],
"ignoreDeps": ["go"]
}
================================================
FILE: .github/workflows/cd-badger.yml
================================================
name: cd-badger
on:
workflow_dispatch:
inputs:
releasetag:
description: releasetag
required: true
type: string
permissions:
contents: read
jobs:
badger-build-amd64:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
with:
ref: "${{ github.event.inputs.releasetag }}"
- name: Set up Go
uses: actions/setup-go@v6
with:
go-version-file: go.mod
- name: Set Badger Release Version
run: |
#!/bin/bash
GIT_TAG_NAME='${{ github.event.inputs.releasetag }}'
if [[ "$GIT_TAG_NAME" == "v"* ]];
then
echo "this is a release tag"
else
echo "this is NOT a release tag"
exit 1
fi
BADGER_RELEASE_VERSION='${{ github.event.inputs.releasetag }}'
echo "making a new release for "$BADGER_RELEASE_VERSION
echo "BADGER_RELEASE_VERSION=$BADGER_RELEASE_VERSION" >> $GITHUB_ENV
- name: Fetch dependencies
run: sudo apt-get update && sudo apt-get -y install build-essential
- name: Build badger linux/amd64
run: make badger
- name: Generate SHA for Linux Build
run:
cd badger && sha256sum badger-linux-amd64 | cut -c-64 > badger-checksum-linux-amd64.sha256
- name: Tar Archive for Linux Build
run: cd badger && tar -zcvf badger-linux-amd64.tar.gz badger-linux-amd64
- name: Upload Badger Binary Build Artifacts
uses: actions/upload-artifact@v4
with:
name: badger-linux-amd64-${{ github.run_id }}-${{ github.job }}
path: |
badger/badger-checksum-linux-amd64.sha256
badger/badger-linux-amd64.tar.gz
badger-build-arm64:
runs-on: ubuntu-24.04-arm
steps:
- uses: actions/checkout@v5
with:
ref: "${{ github.event.inputs.releasetag }}"
- name: Set up Go
uses: actions/setup-go@v6
with:
go-version-file: go.mod
- name: Set Badger Release Version
run: |
#!/bin/bash
GIT_TAG_NAME='${{ github.event.inputs.releasetag }}'
if [[ "$GIT_TAG_NAME" == "v"* ]];
then
echo "this is a release tag"
else
echo "this is NOT a release tag"
exit 1
fi
BADGER_RELEASE_VERSION='${{ github.event.inputs.releasetag }}'
echo "making a new release for "$BADGER_RELEASE_VERSION
echo "BADGER_RELEASE_VERSION=$BADGER_RELEASE_VERSION" >> $GITHUB_ENV
- name: Fetch dependencies
run: sudo apt-get -y install build-essential
- name: Build badger linux/arm64
run: make badger
- name: Generate SHA for Linux Build
run:
cd badger && sha256sum badger-linux-arm64 | cut -c-64 > badger-checksum-linux-arm64.sha256
- name: Tar Archive for Linux Build
run: cd badger && tar -zcvf badger-linux-arm64.tar.gz badger-linux-arm64
- name: List Artifacts
run: ls -al badger/
- name: Upload Badger Binary Build Artifacts
uses: actions/upload-artifact@v4
with:
name: badger-linux-arm64-${{ github.run_id }}-${{ github.job }}
path: |
badger/badger-checksum-linux-arm64.sha256
badger/badger-linux-arm64.tar.gz
================================================
FILE: .github/workflows/ci-badger-bank-tests-nightly.yml
================================================
name: ci-badger-bank-tests-nightly
on:
push:
paths-ignore:
- "**.md"
- docs/**
- images/**
branches:
- main
- release/v*
schedule:
- cron: 1 3 * * *
permissions:
contents: read
jobs:
badger-bank:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- name: Setup Go
uses: actions/setup-go@v6
with:
go-version-file: go.mod
- name: Install Dependencies
run: make dependency
- name: Install jemalloc
run: make jemalloc
- name: Install Badger
run: cd badger && go install --race --tags=jemalloc .
- name: Run Badger Bank Test
run: |
#!/bin/bash -x
set -o pipefail
# get 16 random bytes from /dev/urandom
hexdump -vn16 -e'4/4 "%08X" 1 "\n"' /dev/urandom > badgerkey16bytes
badger bank test --dir=. --encryption-key "badgerkey16bytes" -d=4h 2>&1 | tee badgerbanktest.log | grep -v 'Moved $5'
if [ $? -ne 0 ]; then
if grep -qi 'data race' badgerbanktest.log; then
echo "Detected data race via grep..."
cat badgerbanktest.log | grep -v 'Moved $5'
else
echo "No data race detected via grep. Assuming txn violation..."
tail -1000 badgerbanktest.log
badger bank disect --dir=. --decryption-key "badgerkey16bytes"
fi
exit 1
fi
echo 'Bank test finished with no issues.'
================================================
FILE: .github/workflows/ci-badger-bank-tests.yml
================================================
name: ci-badger-bank-tests
on:
workflow_dispatch: # allows manual trigger from GitHub
pull_request:
paths-ignore:
- "**.md"
- docs/**
- images/**
branches:
- main
- release/v*
permissions:
contents: read
jobs:
badger-bank:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- name: Setup Go
uses: actions/setup-go@v6
with:
go-version-file: go.mod
- name: Install Dependencies
run: make dependency
- name: Install jemalloc
run: make jemalloc
- name: Install Badger
run: cd badger && go install --race --tags=jemalloc .
- name: Run Badger Bank Test
run: |
#!/bin/bash
mkdir bank && cd bank
badger bank test -v --dir=. -d=20m
================================================
FILE: .github/workflows/ci-badger-tests.yml
================================================
name: ci-badger-tests
on:
workflow_dispatch: # allows manual trigger from GitHub
pull_request:
paths-ignore:
- "**.md"
- docs/**
- images/**
- contrib/**
branches:
- main
- release/v*
permissions:
contents: read
jobs:
cross-compile:
runs-on: ubuntu-latest
strategy:
matrix:
include:
- goos: linux
goarch: amd64
- goos: linux
goarch: arm64
- goos: darwin
goarch: amd64
- goos: darwin
goarch: arm64
- goos: windows
goarch: amd64
- goos: aix
goarch: ppc64
- goos: plan9
goarch: amd64
steps:
- uses: actions/checkout@v5
- name: Setup Go
uses: actions/setup-go@v6
with:
go-version-file: go.mod
- name: Cross-compile for ${{ matrix.goos }}/${{ matrix.goarch }}
env:
GOOS: ${{ matrix.goos }}
GOARCH: ${{ matrix.goarch }}
run: go build ./...
badger-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- name: Setup Go
uses: actions/setup-go@v6
with:
go-version-file: go.mod
- name: Install Dependencies
run: make dependency
- name: Run Badger Tests
run: make test
================================================
FILE: .github/workflows/ci-dgraph-tests.yml
================================================
name: ci-dgraph-tests
on:
push:
paths-ignore:
- "**.md"
- docs/**
- images/**
branches:
- main
permissions:
contents: read
jobs:
dgraph-tests:
runs-on: ubuntu-latest
steps:
- name: Checkout Dgraph repo
uses: actions/checkout@v5
with:
repository: dgraph-io/dgraph
ref: main
- name: Set up Go
uses: actions/setup-go@v6
with:
go-version-file: go.mod
- name: Install gotestsum
run: go install gotest.tools/gotestsum@latest
- name: Fetch latest Badger version
run: |
go get github.com/dgraph-io/badger/v4@main
- name: Set up Node
uses: actions/setup-node@v5
with:
node-version: 16 || 22
- name: Install protobuf-compiler
run: sudo apt update && sudo apt install -y protobuf-compiler
- name: Check protobuf
run: |
cd ./protos
go mod tidy
make regenerate
git diff --exit-code -- .
- name: Make Linux Build and Docker Image
run: make docker-image
- name: Build Test Binary
run: |
#!/bin/bash
# build the test binary
cd t; go build .
- name: Clean Up Environment
run: |
#!/bin/bash
# clean cache
go clean -testcache
# clean up docker containers before test execution
cd t; ./t -r
- name: Run Unit Tests
run: |
#!/bin/bash
# go env settings
export GOPATH=~/go
# move the binary
cp dgraph/dgraph ~/go/bin/dgraph
# run the tests
cd t; ./t --pkg=edgraph,posting,worker,query
# clean up docker containers after test execution
./t -r
# sleep
sleep 5
================================================
FILE: .github/workflows/trunk.yml
================================================
name: Trunk Code Quality
on:
pull_request:
branches: main
permissions:
contents: read
actions: write
checks: write
jobs:
trunk-code-quality:
name: Trunk Code Quality
uses: dgraph-io/.github/.github/workflows/trunk.yml@main
================================================
FILE: .gitignore
================================================
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
badger/badger-*
# Test binary, build with `go test -c`
*.test
badger-test*/
# Output of the go coverage tool
*.out
#darwin
.DS_Store
================================================
FILE: .trunk/.gitignore
================================================
*out
*logs
*actions
*notifications
*tools
plugins
user_trunk.yaml
user.yaml
tmp
================================================
FILE: .trunk/configs/.checkov.yaml
================================================
skip-check:
- CKV_GHA_7
================================================
FILE: .trunk/configs/.markdownlint.json
================================================
{
"line-length": { "line_length": 150, "tables": false },
"no-inline-html": false,
"no-bare-urls": false,
"no-space-in-emphasis": false,
"no-emphasis-as-heading": false,
"first-line-heading": false
}
================================================
FILE: .trunk/configs/.prettierrc
================================================
{
"semi": false,
"proseWrap": "always",
"printWidth": 100
}
================================================
FILE: .trunk/configs/.shellcheckrc
================================================
enable=all
source-path=SCRIPTDIR
disable=SC2154
# If you're having issues with shellcheck following source, disable the errors via:
# disable=SC1090
# disable=SC1091
================================================
FILE: .trunk/configs/.yamllint.yaml
================================================
rules:
quoted-strings:
required: only-when-needed
extra-allowed: ["{|}"]
key-duplicates: {}
octal-values:
forbid-implicit-octal: true
================================================
FILE: .trunk/configs/svgo.config.mjs
================================================
export default {
plugins: [
{
name: "preset-default",
params: {
overrides: {
removeViewBox: false, // https://github.com/svg/svgo/issues/1128
sortAttrs: true,
removeOffCanvasPaths: true,
},
},
},
],
}
================================================
FILE: .trunk/trunk.yaml
================================================
# This file controls the behavior of Trunk: https://docs.trunk.io/cli
# To learn more about the format of this file, see https://docs.trunk.io/reference/trunk-yaml
version: 0.1
cli:
version: 1.25.0
plugins:
sources:
- id: trunk
ref: v1.7.4
uri: https://github.com/trunk-io/plugins
runtimes:
enabled:
- go@1.25.5
lint:
ignore:
- linters: [ALL]
paths:
- pb/*.pb.go
enabled:
- golangci-lint2@2.4.0
- trivy@0.64.1
- renovate@41.76.0
- actionlint@1.7.7
- checkov@3.2.461
- git-diff-check
- gofmt@1.20.4
- golangci-lint@1.64.8
- markdownlint@0.45.0
- osv-scanner@2.0.3
- oxipng@9.1.5
- prettier@3.6.2
- shellcheck@0.10.0
- shfmt@3.6.0
- svgo@4.0.0
- taplo@0.9.3
- trufflehog@3.90.5
- yamllint@1.37.1
actions:
enabled:
- trunk-announce
- trunk-check-pre-push
- trunk-fmt-pre-commit
- trunk-upgrade-available
================================================
FILE: .vscode/extensions.json
================================================
{
"recommendations": ["trunk.io"]
}
================================================
FILE: .vscode/settings.json
================================================
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "trunk.io",
"editor.trimAutoWhitespace": true,
"trunk.autoInit": false
}
================================================
FILE: CHANGELOG.md
================================================
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/).
## [4.9.1] - 2026-02-04
**Fixed**
- fix(aix): add aix directory synchronization support (#2115)
- fix: correct the comment on value size in skl.node (#2250)
**Tests**
- test: add checksum tests for package y (#2246)
**Chores**
- chore(ci): update arm runner label (#2248)
**Full Changelog**: https://github.com/dgraph-io/badger/compare/v4.9.0...v4.9.1
## [4.9.0] - 2025-12-15
**Fixed**
- fix(y): y.SafeCopy shall always return empty slice rather than nil (#2245)
> **WARNING** SafeCopy now returns an empty slice rather than nil. For those using our `y` utility
> package, this could be a breaking change. This has implications for empty slices stored in
> badger, specifically, upon retrieval the value stored with the key will be equal to what was set
> (an empty []byte). See #2067 for more details.
- fix: test.sh error (#2225)
- fix: typo of abandoned (#2222)
**Docs**
- add doc for encryption at rest (#2240)
- move docs pages in the repo (#2232)
**Chores**
- chore(ci): restrict Dgraph test to core packages only (#2242)
- chore: update README.md with correct links and badges (#2239)
- chore: change renovate to maintain backwards compatible go version (#2236)
- chore: configure renovate to leave go version as declared (#2235)
- chore(deps): Update actions (major) (#2229)
- chore(deps): Update actions/checkout action to v5 (#2221)
- chore(deps): Update go minor and patch (#2218)
- chore: update the trunk conf file (#2217)
- chore(deps): Update dependency node to v22 (#2219)
- chore(deps): Update go minor and patch (#2212)
**CI**
- move to GitHub Actions runners
**Full Changelog**: https://github.com/dgraph-io/badger/compare/v4.8.0...v4.8.1
## [4.8.0] - 2025-07-15
**Features**
- feat(stream): Update stream framework with new alternate keyToList function (#2211)
**Fixed**
- fix: crash loop on missing manifest tables (#2198)
**Chores**
- chore(deps): Update module golang.org/x/sys to v0.34.0 (#2210)
- chore(deps): Update go minor and patch (#2208)
- chore(deps): Update go minor and patch (#2204)
- chore(deps): Update go minor and patch (#2202)
- chore(deps): Update go minor and patch (#2200)
- chore(deps): Update module golang.org/x/sys to v0.33.0 (#2195)
- chore(deps): Update go minor and patch (#2189)
- Compile with jemalloc v5.3.0 (#2191)
**CI**
- Update trunk.yml
- move Trunk to action
**Docs**
- docs: add new badge (#2194)
**Full Changelog**: https://github.com/dgraph-io/badger/compare/v4.7.0...v4.8.0
## [4.7.0] - 2025-04-08
**Chores**
- chore(deps): remove dependency on github.com/pkg/errors (#2184)
- chore(deps): Update go minor and patch (#2187)
- chore(deps): Update go minor and patch (#2181)
- chore(deps): Update module golang.org/x/sys to v0.31.0 (#2179)
**Fixed**
- fix broken badge (#2186)
**Docs**
- Update README.md
- doc: add Blink Labs projects to the using Badger list (#2183)
- doc: add FlowG to "Projects Using Badger" section of the README (#2180)
**Full Changelog**: https://github.com/dgraph-io/badger/compare/v4.6.0...v4.7.0
## [4.6.0] - 2025-02-26
**Chores**
- chore(deps): Migrate from OpenCensus to OpenTelemetry (#2169)
- chore(deps): Update go minor and patch (#2177)
- chore(deps): Update module github.com/spf13/cobra to v1.9.0 (#2174)
- chore: add editor config
- update .gitignore (#2176)
**Fixed**
- fix: remove accidentally uploaded binary `badger-darwin-arm64` (#2175)
**Full Changelog**: https://github.com/dgraph-io/badger/compare/v4.5.2...v4.6.0
## [4.5.2] - 2025-02-14
**Chores**
- chore(deps): Update go minor and patch (#2168)
- chore(deps): bump minimum Go support to 1.22 (#2171)
- chore: migrate docs to centralized docs repo (#2166)
- chore: align repo conventions (#2158)
- chore(deps): bump the patch group with 2 updates (#2156)
- chore(deps): bump github.com/google/flatbuffers from 24.12.23+incompatible to 25.1.21+incompatible
(#2153)
- chore(deps): bump golangci/golangci-lint-action from 6.1.1 to 6.2.0 in the actions group (#2154)
- Update renovate.json
- Update trunk.yaml
- enable Trivy
**Fixed**
- update docs link in error message (#2170)
- Revert "Update badgerpb4.pb.go" (#2172)
**Docs**
- Update README.md
- Added my project that uses Badger database (#2157)
- Create SECURITY.md
**Full Changelog**: https://github.com/dgraph-io/badger/compare/v4.5.1...v4.5.2
## [4.5.1] - 2025-01-21
- chore(deps): bump google.golang.org/protobuf from 1.36.2 to 1.36.3 in the patch group (#2150)
- bump github.com/dgraph-io/ristretto/v2 from 2.0.1 to 2.1.0 in the minor group (#2151)
- feat(info): print total size of listed keys (#2149)
- chore(deps): bump google.golang.org/protobuf from 1.36.1 to 1.36.2 in the patch group (#2146)
- chore(deps): bump the minor group with 2 updates (#2147)
- fix(info): print Total BloomFilter Size with totalBloomFilter instead of totalIndex (#2145)
- chore(deps): bump the minor group with 2 updates (#2141)
- chore(deps): bump google.golang.org/protobuf from 1.36.0 to 1.36.1 in the patch group (#2140)
- chore(deps): bump google.golang.org/protobuf from 1.35.2 to 1.36.0 in the minor group (#2139)
- chore(deps): bump github.com/dgraph-io/ristretto/v2 from 2.0.0 to 2.0.1 in the patch group (#2136)
- chore(deps): bump golang.org/x/net from 0.31.0 to 0.32.0 in the minor group (#2137)
- chore(deps): bump the minor group with 2 updates (#2135)
- docs: Add pagination explanation to docs (#2134)
- Fix build for GOARCH=wasm with GOOS=js or GOOS=wasip1 (#2048)
**Full Changelog**: https://github.com/dgraph-io/badger/compare/v4.5.0...v4.5.1
## [4.5.0] - 2024-11-29
- fix the cd pipeline by @mangalaman93 in https://github.com/dgraph-io/badger/pull/2127
- chore(deps): bump the minor group with 2 updates by @dependabot in
https://github.com/dgraph-io/badger/pull/2128
- chore(deps): bump github.com/stretchr/testify from 1.9.0 to 1.10.0 in the minor group by
@dependabot in https://github.com/dgraph-io/badger/pull/2130
- upgrade protobuf library by @shivaji-kharse in https://github.com/dgraph-io/badger/pull/2131
**Full Changelog**: https://github.com/dgraph-io/badger/compare/v4.4.0...v4.5.0
## [4.4.0] - 2024-10-26
- retract v4.3.0 due to #2121 and #2113, upgrade to Go v1.23, use ristretto v2 in
https://github.com/dgraph-io/badger/pull/2122
- Allow stream custom maxsize per batch in https://github.com/dgraph-io/badger/pull/2063
- chore(deps): bump github.com/klauspost/compress from 1.17.10 to 1.17.11 in the patch group in
https://github.com/dgraph-io/badger/pull/2120
- fix: sentinel errors should not have stack traces in https://github.com/dgraph-io/badger/pull/2042
- chore(deps): bump the minor group with 2 updates in https://github.com/dgraph-io/badger/pull/2119
**Full Changelog**: https://github.com/dgraph-io/badger/compare/v4.3.1...v4.4.0
## [4.3.1] - 2024-10-06
- chore: update docs links by @ryanfoxtyler in https://github.com/dgraph-io/badger/pull/2097
- chore(deps): bump golang.org/x/sys from 0.24.0 to 0.25.0 in the minor group by @dependabot in
https://github.com/dgraph-io/badger/pull/2100
- chore(deps): bump golang.org/x/net from 0.28.0 to 0.29.0 in the minor group by @dependabot in
https://github.com/dgraph-io/badger/pull/2106
- fix: fix reverse iterator broken by seek by @harshil-goel in
https://github.com/dgraph-io/badger/pull/2109
- chore(deps): bump github.com/klauspost/compress from 1.17.9 to 1.17.10 in the patch group by
@dependabot in https://github.com/dgraph-io/badger/pull/2114
- chore(deps): bump github.com/dgraph-io/ristretto from 0.1.2-0.20240116140435-c67e07994f91 to 1.0.0
by @dependabot in https://github.com/dgraph-io/badger/pull/2112
**Full Changelog**: https://github.com/dgraph-io/badger/compare/v4.3.0...v4.3.1
## [4.3.0] - 2024-08-29
> **Warning** The tag v4.3.0 has been retracted due to an issue go.sum. Use v4.3.1 (see #2121 and
> #2113)
**Fixes**
- chore(changelog): add a missed entry in CHANGELOG for v4.2.0 by @mangalaman93 in
https://github.com/dgraph-io/badger/pull/1988
- update README with project KVS using badger by @tauraamui in
https://github.com/dgraph-io/badger/pull/1989
- fix edge case for watermark when index is zero by @mangalaman93 in
https://github.com/dgraph-io/badger/pull/1999
- upgrade spf13/cobra to version v1.7.0 by @mangalaman93 in
https://github.com/dgraph-io/badger/pull/2001
- chore: update readme by @joshua-goldstein in https://github.com/dgraph-io/badger/pull/2011
- perf: upgrade compress package test and benchmark. by @siddhant2001 in
https://github.com/dgraph-io/badger/pull/2009
- fix(Transactions): Fix resource consumption on empty write transaction by @Zach-Johnson in
https://github.com/dgraph-io/badger/pull/2018
- chore(deps): bump golang.org/x/net from 0.7.0 to 0.17.0 by @dependabot in
https://github.com/dgraph-io/badger/pull/2017
- perf(compactor): optimize allocations: use buffer for priorities by @deff7 in
https://github.com/dgraph-io/badger/pull/2006
- fix(Transaction): discard empty transactions on CommitWith by @Wondertan in
https://github.com/dgraph-io/badger/pull/2031
- fix(levelHandler): use lock for levelHandler sort tables instead of rlock by @xgzlucario in
https://github.com/dgraph-io/badger/pull/2034
- Docs: update README with project LLS using badger by @Boc-chi-no in
https://github.com/dgraph-io/badger/pull/2032
- chore: MaxTableSize has been renamed to BaseTableSize by @mitar in
https://github.com/dgraph-io/badger/pull/2038
- Update CODEOWNERS by @ryanfoxtyler in https://github.com/dgraph-io/badger/pull/2043
- Chore(): add Stale Action by @ryanfoxtyler in https://github.com/dgraph-io/badger/pull/2070
- Update ristretto and refactor for use of generics by @paralin in
https://github.com/dgraph-io/badger/pull/2047
- chore: Remove obsolete comment by @mitar in https://github.com/dgraph-io/badger/pull/2039
- chore(Docs): Update jQuery 3.2.1 to 3.7.1 by @kokizzu in
https://github.com/dgraph-io/badger/pull/2023
- chore(deps): bump the go_modules group with 3 updates by @dependabot in
https://github.com/dgraph-io/badger/pull/2074
- docs(): update docs path by @ryanfoxtyler in https://github.com/dgraph-io/badger/pull/2076
- perf: fix operation in seek by @harshil-goel in https://github.com/dgraph-io/badger/pull/2077
- Add lakeFS to README.md by @N-o-Z in https://github.com/dgraph-io/badger/pull/2078
- chore(): add Dependabot by @ryanfoxtyler in https://github.com/dgraph-io/badger/pull/2080
- chore(deps): bump golangci/golangci-lint-action from 4 to 6 by @dependabot in
https://github.com/dgraph-io/badger/pull/2083
- chore(deps): bump actions/upload-artifact from 3 to 4 by @dependabot in
https://github.com/dgraph-io/badger/pull/2081
- chore(deps): bump github/codeql-action from 2 to 3 by @dependabot in
https://github.com/dgraph-io/badger/pull/2082
- chore(deps): bump the minor group with 7 updates by @dependabot in
https://github.com/dgraph-io/badger/pull/2089
- Action Manager by @madhu72 in https://github.com/dgraph-io/badger/pull/2050
- chore(deps): bump golang.org/x/sys from 0.23.0 to 0.24.0 in the minor group by @dependabot in
https://github.com/dgraph-io/badger/pull/2091
- chore(deps): bump github.com/golang/protobuf from 1.5.3 to 1.5.4 in the patch group by @dependabot
in https://github.com/dgraph-io/badger/pull/2090
- chore: fix some comments by @dufucun in https://github.com/dgraph-io/badger/pull/2092
- chore(deps): bump github.com/google/flatbuffers from 1.12.1 to 24.3.25+incompatible by @dependabot
in https://github.com/dgraph-io/badger/pull/2084
**CI**
- ci: change cron frequency to fix ghost jobs by @joshua-goldstein in
https://github.com/dgraph-io/badger/pull/2010
- fix(CI): Update to pull_request trigger by @ryanfoxtyler in
https://github.com/dgraph-io/badger/pull/2056
- ci/cd optimization by @ryanfoxtyler in https://github.com/dgraph-io/badger/pull/2051
- fix(cd): fixed cd pipeline by @harshil-goel in https://github.com/dgraph-io/badger/pull/2093
- fix(cd): change name by @harshil-goel in https://github.com/dgraph-io/badger/pull/2094
- fix(cd): added more debug things to cd by @harshil-goel in
https://github.com/dgraph-io/badger/pull/2095
- fix(cd): removing some debug items by @harshil-goel in
https://github.com/dgraph-io/badger/pull/2096
**Full Changelog**: https://github.com/dgraph-io/badger/compare/v4.2.0...v4.3.0
## [4.2.0] - 2023-08-03
**Breaking**
- feat(metrics): fix and update metrics in badger (#1948)
- fix(metrics): remove badger version in the metrics name (#1982)
**Fixed**
- fix(db): avoid panic in parallel reads after closing DB (#1987)
- fix(logging): fix direct access to logger (#1980)
- fix(sec): bump google.golang.org/grpc from 1.20.1 to 1.53.0 (#1977)
- fix(sec): update gopkg.in/yaml.v2 package (#1969)
- fix(test): fix flakiness of TestPersistLFDiscardStats (#1963)
- fix(stream): setup oracle correctly in stream writer (#1968) (#1904)
- fix(stream): improve incremental stream writer (#1901)
- fix(test): improve the params in BenchmarkDbGrowth (#1967)
- fix(sync): sync active memtable and value log on Db.Sync (#1847) (#1953)
- fix(test): handle draining of closed channel, speed up test. (#1957)
- fix(test): fix table checksum test. Test on uncompressed. (#1952)
- fix(level): change split key range right key to use ts=0 (#1932)
- fix(test): the new test case PagebufferReader5 introduced an error. (#1936)
- fix(test): add missing unlock in TestPersistLFDiscardStats (#1924)
- fix(PageBufferReader): should conform to io.Reader interface (#1935)
- fix(publisher): publish updates after persistence in WAL (#1917)
**CI**
- chore(ci): split off coverage workflow (#1944)
- chore(ci): adding trivy scanning workflow (#1925)
## [4.1.0] - 2023-03-30
This release adds support for incremental stream writer. We also do some cleanup in the docs and
resolve some CI issues for community PR's. We resolve high and medium CVE's and fix
[#1833](https://github.com/dgraph-io/badger/issues/1833).
**Features**
- feat(stream): add support for incremental stream writer (#1722) (#1874)
**Fixes**
- chore: upgrade xxhash from v1.1.0 to v2.1.2 (#1910) (fixes
[#1833](https://github.com/dgraph-io/badger/issues/1833))
**Security**
- chore(deps): bump golang.org/x/net from 0.0.0-20201021035429-f5854403a974 to 0.7.0 (#1885)
**CVEs**
- [CVE-2021-31525](https://github.com/dgraph-io/badger/security/dependabot/7)
- [CVE-2022-41723](https://github.com/dgraph-io/badger/security/dependabot/4)
- [CVE-2022-27664](https://github.com/dgraph-io/badger/security/dependabot/5)
- [CVE-2021-33194](https://github.com/dgraph-io/badger/security/dependabot/9)
- [CVE-2022-41723](https://github.com/dgraph-io/badger/security/dependabot/13)
- [CVE-2021-33194](https://github.com/dgraph-io/badger/security/dependabot/16)
- [CVE-2021-38561](https://github.com/dgraph-io/badger/security/dependabot/8)
**Chores**
- fix(docs): update README (#1915)
- cleanup sstable file after tests (#1912)
- chore(ci): add dgraph regression tests (#1908)
- docs: fix the default value in docs (#1909)
- chore: update URL for unsupported manifest version error (#1905)
- docs(README): add raft-badger to projects using badger (#1902)
- sync the docs with README with projects using badger (#1903)
- fix: update code comments for WithNumCompactors (#1900)
- docs: add loggie to projects using badger (#1882)
- chore(memtable): refactor code for memtable flush (#1866)
- resolve coveralls issue for community PR's (#1892, #1894, #1896)
## [4.0.1] - 2023-02-28
We issue a follow up release in order to resolve a bug in subscriber. We also generate updated
protobufs for Badger v4.
**Fixed**
- fix(pb): fix generated protos #1888
- fix(publisher): initialize the atomic variable #1889
**Chores**
- chore(cd): tag based deployments #1887
- chore(ci): fail fast when testing #1890
## [4.0.0] - 2023-02-27
> **Warning** The tag v4.0.0 has been retracted due to a bug in publisher. Use v4.0.1 (see #1889)
This release fixes a bug in the maxHeaderSize parameter that could lead to panics. We introduce an
external magic number to keep track of external dependencies. We bump up the minimum required Go
version to 1.19. No changes were made to the format of data on disk. This is a major release because
we are making a switch to SemVer in order to make it easier for the community to understand when
breaking API and data format changes are made.
**Fixed**
- fix: update maxHeaderSize #1877
- feat(externalMagic): Introduce external magic number (#1745) #1852
- fix(bench): bring in benchmark fixes from main #1863
**Chores**
- upgrade go to 1.19 #1868
- enable linters (gosimple, govet, lll, unused, staticcheck, errcheck, ineffassign, gofmt) #1871
#1870 #1876
- remove dependency on io/ioutil #1879
- various doc and comment fixes #1857
- moving from CalVer to SemVer
## [3.2103.5] - 2022-12-15
We release Badger CLI tool binaries for amd64 and now arm64. This release does not involve any core
code changes to Badger. We add a CD job for building Badger for arm64.
## [3.2103.4] - 2022-11-04
**Fixed**
- fix(manifest): fix manifest corruption due to race condition in concurrent compactions (#1756)
**Chores**
- We bring the release branch to parity with main by updating the CI/CD jobs, Readme, Codeowners, PR
and issue templates, etc.
## [3.2103.3] - 2022-10-14
**Remarks**
- This is a minor patch release that fixes arm64 related issues. The issues in the `z` package in
Ristretto were resolved in Ristretto v0.1.1.
**Fixed**
- fix(arm64): bump ristretto v0.1.0 --> v0.1.1 (#1806)
## [3.2103.2] - 2021-10-07
**Fixed**
- fix(compact): close vlog after the compaction at L0 has completed (#1752)
- fix(builder): put the upper limit on reallocation (#1748)
- deps: Bump github.com/google/flatbuffers to v1.12.1 (#1746)
- fix(levels): Avoid a deadlock when acquiring read locks in levels (#1744)
- fix(pubsub): avoid deadlock in publisher and subscriber (#1749) (#1751)
## [3.2103.1] - 2021-07-08
**Fixed**
- fix(compaction): copy over the file ID when building tables #1713
- fix: Fix conflict detection for managed DB (#1716)
- fix(pendingWrites): don't skip the pending entries with version=0 (#1721)
**Features**
- feat(zstd): replace datadog's zstd with Klauspost's zstd (#1709)
## [3.2103.0] - 2021-06-02
**Breaking**
- Subscribe: Add option to subscribe with holes in prefixes. (#1658)
**Fixed**
- fix(compaction): Remove compaction backoff mechanism (#1686)
- Add a name to mutexes to make them unexported (#1678)
- fix(merge-operator): don't read the deleted keys (#1675)
- fix(discard): close the discard stats file on db close (#1672)
- fix(iterator): fix iterator when data does not exist in read only mode (#1670)
- fix(badger): Do not reuse variable across badger commands (#1624)
- fix(dropPrefix): check properly if the key is present in a table (#1623)
**Performance**
- Opt(Stream): Optimize how we deduce key ranges for iteration (#1687)
- Increase value threshold from 1 KB to 1 MB (#1664)
- opt(DropPrefix): check if there exist some data to drop before dropping prefixes (#1621)
**Features**
- feat(options): allow special handling and checking when creating options from superflag (#1688)
- overwrite default Options from SuperFlag string (#1663)
- Support SinceTs in iterators (#1653)
- feat(info): Add a flag to parse and print DISCARD file (#1662)
- feat(vlog): making vlog threshold dynamic 6ce3b7c (#1635)
- feat(options): add NumGoroutines option for default Stream.numGo (#1656)
- feat(Trie): Working prefix match with holes (#1654)
- feat: add functionality to ban a prefix (#1638)
- feat(compaction): Support Lmax to Lmax compaction (#1615)
**New APIs**
- Badger.DB
- BanNamespace
- BannedNamespaces
- Ranges
- Badger.Options
- FromSuperFlag
- WithNumGoRoutines
- WithNamespaceOffset
- WithVLogPercentile
- Badger.Trie
- AddMatch
- DeleteMatch
- Badger.Table
- StaleDataSize
- Badger.Table.Builder
- AddStaleKey
- Badger.InitDiscardStats
**Removed APIs**
- Badger.DB
- KeySplits
- Badger.Options
- SkipVlog
### Changed APIs
- Badger.DB
- Subscribe
- Badger.Options
- WithValueThreshold
## [3.2011.1] - 2021-01-22
**Fixed**
- Fix(compaction): Set base level correctly after stream (#1651)
- Fix: update ristretto and use filepath (#1652)
- Fix(badger): Do not reuse variable across badger commands (#1650)
- Fix(build): fix 32-bit build (#1646)
- Fix(table): always sync SST to disk (#1645)
## [3.2011.0] - 2021-01-15
This release is not backward compatible with Badger v2.x.x
**Breaking**:
- opt(compactions): Improve compaction performance (#1574)
- Change how Badger handles WAL (#1555)
- feat(index): Use flatbuffers instead of protobuf (#1546)
**Fixed**:
- Fix(GC): Set bits correctly for moved keys (#1619)
- Fix(tableBuilding): reduce scope of valuePointer (#1617)
- Fix(compaction): fix table size estimation on compaction (#1613)
- Fix(OOM): Reuse pb.KVs in Stream (#1609)
- Fix race condition in L0StallMs variable (#1605)
- Fix(stream): Stop produceKVs on error (#1604)
- Fix(skiplist): Remove z.Buffer from skiplist (#1600)
- Fix(readonly): fix the file opening mode (#1592)
- Fix: Disable CompactL0OnClose by default (#1586)
- Fix(compaction): Don't drop data when split overlaps with top tables (#1587)
- Fix(subcompaction): Close builder before throttle.Done (#1582)
- Fix(table): Add onDisk size (#1569)
- Fix(Stream): Only send done markers if told to do so
- Fix(value log GC): Fix a bug which caused value log files to not be GCed.
- Fix segmentation fault when cache sizes are small. (#1552)
- Fix(builder): Too many small tables when compression is enabled (#1549)
- Fix integer overflow error when building for 386 (#1541)
- Fix(writeBatch): Avoid deadlock in commit callback (#1529)
- Fix(db): Handle nil logger (#1534)
- Fix(maxVersion): Use choosekey instead of KeyToList (#1532)
- Fix(Backup/Restore): Keep all versions (#1462)
- Fix(build): Fix nocgo builds. (#1493)
- Fix(cleanup): Avoid truncating in value.Open on error (#1465)
- Fix(compaction): Don't use cache for table compaction (#1467)
- Fix(compaction): Use separate compactors for L0, L1 (#1466)
- Fix(options): Do not implicitly enable cache (#1458)
- Fix(cleanup): Do not close cache before compaction (#1464)
- Fix(replay): Update head for LSM entires also (#1456)
- fix(levels): Cleanup builder resources on building an empty table (#1414)
**Performance**
- perf(GC): Remove move keys (#1539)
- Keep the cheaper parts of the index within table struct. (#1608)
- Opt(stream): Use z.Buffer to stream data (#1606)
- opt(builder): Use z.Allocator for building tables (#1576)
- opt(memory): Use z.Calloc for allocating KVList (#1563)
- opt: Small memory usage optimizations (#1562)
- KeySplits checks tables and memtables when number of splits is small. (#1544)
- perf: Reduce memory usage by better struct packing (#1528)
- perf(tableIterator): Don't do next on NewIterator (#1512)
- Improvements: Manual Memory allocation via Calloc (#1459)
- Various bug fixes: Break up list and run DropAll func (#1439)
- Add a limit to the size of the batches sent over a stream. (#1412)
- Commit does not panic after Finish, instead returns an error (#1396)
- levels: Compaction incorrectly drops some delete markers (#1422)
- Remove vlog file if bootstrap, syncDir or mmap fails (#1434)
**Features**:
- Use opencensus for tracing (#1566)
- Export functions from Key Registry (#1561)
- Allow sizes of block and index caches to be updated. (#1551)
- Add metric for number of tables being compacted (#1554)
- feat(info): Show index and bloom filter size (#1543)
- feat(db): Add db.MaxVersion API (#1526)
- Expose DB options in Badger. (#1521)
- Feature: Add a Calloc based Buffer (#1471)
- Add command to stream contents of DB into another DB. (#1463)
- Expose NumAlloc metrics via expvar (#1470)
- Support fully disabling the bloom filter (#1319)
- Add --enc-key flag in badger info tool (#1441)
**New APIs**
- Badger.DB
- CacheMaxCost (#1551)
- Levels (#1574)
- LevelsToString (#1574)
- Opts (#1521)
- Badger.Options
- WithBaseLevelSize (#1574)
- WithBaseTableSize (#1574)
- WithMemTableSize (#1574)
- Badger.KeyRegistry
- DataKey (#1561)
- LatestDataKey (#1561)
**Removed APIs**
- Badger.Options
- WithKeepL0InMemory (#1555)
- WithLevelOneSize (#1574)
- WithLoadBloomsOnOpen (#1555)
- WithLogRotatesToFlush (#1574)
- WithMaxTableSize (#1574)
- WithTableLoadingMode (#1555)
- WithTruncate (#1555)
- WithValueLogLoadingMode (#1555)
## [2.2007.4] - 2021-08-25
**Fixed**
- Fix build on Plan 9 (#1451) (#1508) (#1738)
**Features**
- feat(zstd): backport replacement of DataDog's zstd with Klauspost's zstd (#1736)
## [2.2007.3] - 2021-07-21
**Fixed**
- fix(maxVersion): Use choosekey instead of KeyToList (#1532) #1533
- fix(flatten): Add --num_versions flag (#1518) #1520
- fix(build): Fix integer overflow on 32-bit architectures #1558
- fix(pb): avoid protobuf warning due to common filename (#1519)
**Features**
- Add command to stream contents of DB into another DB. (#1486)
**New APIs**
- DB.StreamDB
- DB.MaxVersion
## [2.2007.2] - 2020-08-31
**Fixed**
- Compaction: Use separate compactors for L0, L1 (#1466)
- Rework Block and Index cache (#1473)
- Add IsClosed method (#1478)
- Cleanup: Avoid truncating in vlog.Open on error (#1465)
- Cleanup: Do not close cache before compactions (#1464)
**New APIs**
- Badger.DB
- BlockCacheMetrics (#1473)
- IndexCacheMetrics (#1473)
- Badger.Option
- WithBlockCacheSize (#1473)
- WithIndexCacheSize (#1473)
**Removed APIs** [Breaking Changes]
- Badger.DB
- DataCacheMetrics (#1473)
- BfCacheMetrics (#1473)
- Badger.Option
- WithMaxCacheSize (#1473)
- WithMaxBfCacheSize (#1473)
- WithKeepBlockIndicesInCache (#1473)
- WithKeepBlocksInCache (#1473)
## [2.2007.1] - 2020-08-19
**Fixed**
- Remove vlog file if bootstrap, syncDir or mmap fails (#1434)
- levels: Compaction incorrectly drops some delete markers (#1422)
- Replay: Update head for LSM entires also (#1456)
## [2.2007.0] - 2020-08-10
**Fixed**
- Add a limit to the size of the batches sent over a stream. (#1412)
- Fix Sequence generates duplicate values (#1281)
- Fix race condition in DoesNotHave (#1287)
- Fail fast if cgo is disabled and compression is ZSTD (#1284)
- Proto: make badger/v2 compatible with v1 (#1293)
- Proto: Rename dgraph.badger.v2.pb to badgerpb2 (#1314)
- Handle duplicates in ManagedWriteBatch (#1315)
- Ensure `bitValuePointer` flag is cleared for LSM entry values written to LSM (#1313)
- DropPrefix: Return error on blocked writes (#1329)
- Confirm `badgerMove` entry required before rewrite (#1302)
- Drop move keys when its key prefix is dropped (#1331)
- Iterator: Always add key to txn.reads (#1328)
- Restore: Account for value size as well (#1358)
- Compaction: Expired keys and delete markers are never purged (#1354)
- GC: Consider size of value while rewriting (#1357)
- Force KeepL0InMemory to be true when InMemory is true (#1375)
- Rework DB.DropPrefix (#1381)
- Update head while replaying value log (#1372)
- Avoid panic on multiple closer.Signal calls (#1401)
- Return error if the vlog writes exceeds more than 4GB (#1400)
**Performance**
- Clean up transaction oracle as we go (#1275)
- Use cache for storing block offsets (#1336)
**Features**
- Support disabling conflict detection (#1344)
- Add leveled logging (#1249)
- Support entry version in Write batch (#1310)
- Add Write method to batch write (#1321)
- Support multiple iterators in read-write transactions (#1286)
**New APIs**
- Badger.DB
- NewManagedWriteBatch (#1310)
- DropPrefix (#1381)
- Badger.Option
- WithDetectConflicts (#1344)
- WithKeepBlockIndicesInCache (#1336)
- WithKeepBlocksInCache (#1336)
- Badger.WriteBatch
- DeleteAt (#1310)
- SetEntryAt (#1310)
- Write (#1321)
### Changes to Default Options
- DefaultOptions: Set KeepL0InMemory to false (#1345)
- Increase default valueThreshold from 32B to 1KB (#1346)
### Deprecated
- Badger.Option
- WithEventLogging (#1203)
### Reverts
This sections lists the changes which were reverted because of non-reproducible crashes.
- Compress/Encrypt Blocks in the background (#1227)
## [2.0.3] - 2020-03-24
**Fixed**
- Add support for watching nil prefix in subscribe API (#1246)
**Performance**
- Compress/Encrypt Blocks in the background (#1227)
- Disable cache by default (#1257)
**Features**
- Add BypassDirLock option (#1243)
- Add separate cache for bloomfilters (#1260)
**New APIs**
- badger.DB
- BfCacheMetrics (#1260)
- DataCacheMetrics (#1260)
- badger.Options
- WithBypassLockGuard (#1243)
- WithLoadBloomsOnOpen (#1260)
- WithMaxBfCacheSize (#1260)
## [2.0.2] - 2020-03-02
**Fixed**
- Cast sz to uint32 to fix compilation on 32 bit. (#1175)
- Fix checkOverlap in compaction. (#1166)
- Avoid sync in inmemory mode. (#1190)
- Support disabling the cache completely. (#1185)
- Add support for caching bloomfilters. (#1204)
- Fix int overflow for 32bit. (#1216)
- Remove the 'this entry should've caught' log from value.go. (#1170)
- Rework concurrency semantics of valueLog.maxFid. (#1187)
**Performance**
- Use fastRand instead of locked-rand in skiplist. (#1173)
- Improve write stalling on level 0 and 1. (#1186)
- Disable compression and set ZSTD Compression Level to 1. (#1191)
## [2.0.1] - 2020-01-02
**New APIs**
- badger.Options
- WithInMemory (f5b6321)
- WithZSTDCompressionLevel (3eb4e72)
- Badger.TableInfo
- EstimatedSz (f46f8ea)
**Features**
- Introduce in-memory mode in badger. (#1113)
**Fixed**
- Limit manifest's change set size. (#1119)
- Cast idx to uint32 to fix compilation on i386. (#1118)
- Fix request increment ref bug. (#1121)
- Fix windows dataloss issue. (#1134)
- Fix VerifyValueChecksum checks. (#1138)
- Fix encryption in stream writer. (#1146)
- Fix segmentation fault in vlog.Read. (header.Decode) (#1150)
- Fix merge iterator duplicates issue. (#1157)
**Performance**
- Set level 15 as default compression level in Zstd. (#1111)
- Optimize createTable in stream_writer.go. (#1132)
## [2.0.0] - 2019-11-12
**New APIs**
- badger.DB
- NewWriteBatchAt (7f43769)
- CacheMetrics (b9056f1)
- badger.Options
- WithMaxCacheSize (b9056f1)
- WithEventLogging (75c6a44)
- WithBlockSize (1439463)
- WithBloomFalsePositive (1439463)
- WithKeepL0InMemory (ee70ff2)
- WithVerifyValueChecksum (ee70ff2)
- WithCompression (5f3b061)
- WithEncryptionKey (a425b0e)
- WithEncryptionKeyRotationDuration (a425b0e)
- WithChecksumVerificationMode (7b4083d)
**Features**
- Data cache to speed up lookups and iterations. (#1066)
- Data compression. (#1013)
- Data encryption-at-rest. (#1042)
**Fixed**
- Fix deadlock when flushing discard stats. (#976)
- Set move key's expiresAt for keys with TTL. (#1006)
- Fix unsafe usage in Decode. (#1097)
- Fix race condition on db.orc.nextTxnTs. (#1101)
- Fix level 0 GC dataloss bug. (#1090)
- Fix deadlock in discard stats. (#1070)
- Support checksum verification for values read from vlog. (#1052)
- Store entire L0 in memory. (#963)
- Fix table.Smallest/Biggest and iterator Prefix bug. (#997)
- Use standard proto functions for Marshal/Unmarshal and Size. (#994)
- Fix boundaries on GC batch size. (#987)
- VlogSize to store correct directory name to expvar.Map. (#956)
- Fix transaction too big issue in restore. (#957)
- Fix race condition in updateDiscardStats. (#973)
- Cast results of len to uint32 to fix compilation in i386 arch. (#961)
- Making the stream writer APIs goroutine-safe. (#959)
- Fix prefix bug in key iterator and allow all versions. (#950)
- Drop discard stats if we can't unmarshal it. (#936)
- Fix race condition in flushDiscardStats function. (#921)
- Ensure rewrite in vlog is within transactional limits. (#911)
- Fix discard stats moved by GC bug. (#929)
- Fix busy-wait loop in Watermark. (#920)
**Performance**
- Introduce fast merge iterator. (#1080)
- Binary search based table picker. (#983)
- Flush vlog buffer if it grows beyond threshold. (#1067)
- Introduce StreamDone in Stream Writer. (#1061)
- Performance Improvements to block iterator. (#977)
- Prevent unnecessary safecopy in iterator parseKV. (#971)
- Use pointers instead of binary encoding. (#965)
- Reuse block iterator inside table iterator. (#972)
- [breaking/format] Remove vlen from entry header. (#945)
- Replace FarmHash with AESHash for Oracle conflicts. (#952)
- [breaking/format] Optimize Bloom filters. (#940)
- [breaking/format] Use varint for header encoding (without header length). (#935)
- Change file picking strategy in compaction. (#894)
- [breaking/format] Block level changes. (#880)
- [breaking/format] Add key-offset index to the end of SST table. (#881)
## [1.6.0] - 2019-07-01
This is a release including almost 200 commits, so expect many changes - some of them not backward
compatible.
Regarding backward compatibility in Badger versions, you might be interested on reading
[VERSIONING.md](VERSIONING.md).
_Note_: The hashes in parentheses correspond to the commits that impacted the given feature.
**New APIs**
- badger.DB
- DropPrefix (291295e)
- Flatten (7e41bba)
- KeySplits (4751ef1)
- MaxBatchCount (b65e2a3)
- MaxBatchSize (b65e2a3)
- PrintKeyValueHistogram (fd59907)
- Subscribe (26128a7)
- Sync (851e462)
- badger.DefaultOptions() and badger.LSMOnlyOptions() (91ce687)
- badger.Options.WithX methods
- badger.Entry (e9447c9)
- NewEntry
- WithMeta
- WithDiscard
- WithTTL
- badger.Item
- KeySize (fd59907)
- ValueSize (5242a99)
- badger.IteratorOptions
- PickTable (7d46029, 49a49e3)
- Prefix (7d46029)
- badger.Logger (fbb2778)
- badger.Options
- CompactL0OnClose (7e41bba)
- Logger (3f66663)
- LogRotatesToFlush (2237832)
- badger.Stream (14cbd89, 3258067)
- badger.StreamWriter (7116e16)
- badger.TableInfo.KeyCount (fd59907)
- badger.TableManifest (2017987)
- badger.Tx.NewKeyIterator (49a49e3)
- badger.WriteBatch (6daccf9, 7e78e80)
**Modified APIs**
**Breaking**
- badger.DefaultOptions and badger.LSMOnlyOptions are now functions rather than variables (91ce687)
- badger.Item.Value now receives a function that returns an error (439fd46)
- badger.Txn.Commit doesn't receive any params now (6daccf9)
- badger.DB.Tables now receives a boolean (76b5341)
**Features**
- badger.LSMOptions changed values (799c33f)
- badger.DB.NewIterator now allows multiple iterators per RO txn (41d9656)
- badger.Options.TableLoadingMode's new default is options.MemoryMap (6b97bac)
**Removed APIs**
- badger.ManagedDB (d22c0e8)
- badger.Options.DoNotCompact (7e41bba)
- badger.Txn.SetWithX (e9447c9)
**Tools**
- badger bank disect (13db058)
- badger bank test (13db058) --mmap (03870e3)
- badger fill (7e41bba)
- badger flatten (7e41bba)
- badger info --histogram (fd59907) --history --lookup --show-keys --show-meta --with-prefix
(09e9b63) --show-internal (fb2eed9)
- badger benchmark read (239041e)
- badger benchmark write (6d3b67d)
## [1.5.5] - 2019-06-20
- Introduce support for Go Modules
## [1.5.3] - 2018-07-11
Bug Fixes:
- Fix a panic caused due to item.vptr not copying over vs.Value, when looking for a move key.
## [1.5.2] - 2018-06-19
Bug Fixes:
- Fix the way move key gets generated.
- If a transaction has unclosed, or multiple iterators running simultaneously, throw a panic. Every
iterator must be properly closed. At any point in time, only one iterator per transaction can be
running. This is to avoid bugs in a transaction data structure which is thread unsafe.
- _Warning: This change might cause panics in user code. Fix is to properly close your iterators,
and only have one running at a time per transaction._
## [1.5.1] - 2018-06-04
Bug Fixes:
- Fix for infinite yieldItemValue recursion. #503
- Fix recursive addition of `badgerMove` prefix.
https://github.com/dgraph-io/badger/commit/2e3a32f0ccac3066fb4206b28deb39c210c5266f
- Use file size based window size for sampling, instead of fixing it to 10MB. #501
Cleanup:
- Clarify comments and documentation.
- Move badger tool one directory level up.
## [1.5.0] - 2018-05-08
- Introduce `NumVersionsToKeep` option. This option is used to discard many versions of the same
key, which saves space.
- Add a new `SetWithDiscard` method, which would indicate that all the older versions of the key are
now invalid. Those versions would be discarded during compactions.
- Value log GC moves are now bound to another keyspace to ensure latest versions of data are always
at the top in LSM tree.
- Introduce `ValueLogMaxEntries` to restrict the number of key-value pairs per value log file. This
helps bound the time it takes to garbage collect one file.
## [1.4.0] - 2018-05-04
- Make mmap-ing of value log optional.
- Run GC multiple times, based on recorded discard statistics.
- Add MergeOperator.
- Force compact L0 on clsoe (#439).
- Add truncate option to warn about data loss (#452).
- Discard key versions during compaction (#464).
- Introduce new `LSMOnlyOptions`, to make Badger act like a typical LSM based DB.
Bug fix:
- (Temporary) Check max version across all tables in Get (removed in next release).
- Update commit and read ts while loading from backup.
- Ensure all transaction entries are part of the same value log file.
- On commit, run unlock callbacks before doing writes (#413).
- Wait for goroutines to finish before closing iterators (#421).
## [1.3.0] - 2017-12-12
- Add `DB.NextSequence()` method to generate monotonically increasing integer sequences.
- Add `DB.Size()` method to return the size of LSM and value log files.
- Tweaked mmap code to make Windows 32-bit builds work.
- Tweaked build tags on some files to make iOS builds work.
- Fix `DB.PurgeOlderVersions()` to not violate some constraints.
## [1.2.0] - 2017-11-30
- Expose a `Txn.SetEntry()` method to allow setting the key-value pair and all the metadata at the
same time.
## [1.1.1] - 2017-11-28
- Fix bug where txn.Get was returing key deleted in same transaction.
- Fix race condition while decrementing reference in oracle.
- Update doneCommit in the callback for CommitAsync.
- Iterator see writes of current txn.
## [1.1.0] - 2017-11-13
- Create Badger directory if it does not exist when `badger.Open` is called.
- Added `Item.ValueCopy()` to avoid deadlocks in long-running iterations
- Fixed 64-bit alignment issues to make Badger run on Arm v7
## [1.0.1] - 2017-11-06
- Fix an uint16 overflow when resizing key slice
[4.9.0]: https://github.com/dgraph-io/badger/compare/v4.8.0...v4.9.0
[4.8.0]: https://github.com/dgraph-io/badger/compare/v4.7.0...v4.8.0
[4.7.0]: https://github.com/dgraph-io/badger/compare/v4.6.0...v4.7.0
[4.6.0]: https://github.com/dgraph-io/badger/compare/v4.5.2...v4.6.0
[4.5.2]: https://github.com/dgraph-io/badger/compare/v4.5.1...v4.5.2
[4.5.1]: https://github.com/dgraph-io/badger/compare/v4.5.0...v4.5.1
[4.5.0]: https://github.com/dgraph-io/badger/compare/v4.4.0...v4.5.0
[4.4.0]: https://github.com/dgraph-io/badger/compare/v4.3.1...v4.4.0
[4.3.1]: https://github.com/dgraph-io/badger/compare/v4.3.0...v4.3.1
[4.3.0]: https://github.com/dgraph-io/badger/compare/v4.2.0...v4.3.0
[4.2.0]: https://github.com/dgraph-io/badger/compare/v4.1.0...v4.2.0
[4.1.0]: https://github.com/dgraph-io/badger/compare/v4.0.1...v4.1.0
[4.0.1]: https://github.com/dgraph-io/badger/compare/v4.0.0...v4.0.1
[4.0.0]: https://github.com/dgraph-io/badger/compare/v3.2103.5...v4.0.0
[3.2103.5]: https://github.com/dgraph-io/badger/compare/v3.2103.4...v3.2103.5
[3.2103.4]: https://github.com/dgraph-io/badger/compare/v3.2103.3...v3.2103.4
[3.2103.3]: https://github.com/dgraph-io/badger/compare/v3.2103.2...v3.2103.3
[3.2103.2]: https://github.com/dgraph-io/badger/compare/v3.2103.1...v3.2103.2
[3.2103.1]: https://github.com/dgraph-io/badger/compare/v3.2103.0...v3.2103.1
[3.2103.0]: https://github.com/dgraph-io/badger/compare/v3.2011.1...v3.2103.0
[3.2011.1]: https://github.com/dgraph-io/badger/compare/v3.2011.0...v3.2011.1
[3.2011.0]: https://github.com/dgraph-io/badger/compare/v2.2007.4...v3.2011.0
[2.2007.4]: https://github.com/dgraph-io/badger/compare/v2.2007.3...v2.2007.4
[2.2007.3]: https://github.com/dgraph-io/badger/compare/v2.2007.2...v2.2007.3
[2.2007.2]: https://github.com/dgraph-io/badger/compare/v2.2007.1...v2.2007.2
[2.2007.1]: https://github.com/dgraph-io/badger/compare/v2.2007.0...v2.2007.1
[2.2007.0]: https://github.com/dgraph-io/badger/compare/v2.0.3...v2.2007.0
[2.0.3]: https://github.com/dgraph-io/badger/compare/v2.0.2...v2.0.3
[2.0.2]: https://github.com/dgraph-io/badger/compare/v2.0.1...v2.0.2
[2.0.1]: https://github.com/dgraph-io/badger/compare/v2.0.0...v2.0.1
[2.0.0]: https://github.com/dgraph-io/badger/compare/v1.6.0...v2.0.0
[1.6.0]: https://github.com/dgraph-io/badger/compare/v1.5.5...v1.6.0
[1.5.5]: https://github.com/dgraph-io/badger/compare/v1.5.3...v1.5.5
[1.5.3]: https://github.com/dgraph-io/badger/compare/v1.5.2...v1.5.3
[1.5.2]: https://github.com/dgraph-io/badger/compare/v1.5.1...v1.5.2
[1.5.1]: https://github.com/dgraph-io/badger/compare/v1.5.0...v1.5.1
[1.5.0]: https://github.com/dgraph-io/badger/compare/v1.4.0...v1.5.0
[1.4.0]: https://github.com/dgraph-io/badger/compare/v1.3.0...v1.4.0
[1.3.0]: https://github.com/dgraph-io/badger/compare/v1.2.0...v1.3.0
[1.2.0]: https://github.com/dgraph-io/badger/compare/v1.1.1...v1.2.0
[1.1.1]: https://github.com/dgraph-io/badger/compare/v1.1.0...v1.1.1
[1.1.0]: https://github.com/dgraph-io/badger/compare/v1.0.1...v1.1.0
[1.0.1]: https://github.com/dgraph-io/badger/compare/v1.0.0...v1.0.1
================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our community a
harassment-free experience for everyone, regardless of age, body size, visible or invisible
disability, ethnicity, sex characteristics, gender identity and expression, level of experience,
education, socio-economic status, nationality, personal appearance, race, religion, or sexual
identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and
healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our community include:
- Demonstrating empathy and kindness toward other people
- Being respectful of differing opinions, viewpoints, and experiences
- Giving and gracefully accepting constructive feedback
- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the
experience
- Focusing on what is best not just for us as individuals, but for the overall community
Examples of unacceptable behavior include:
- The use of sexualized language or imagery, and sexual attention or advances of any kind
- Trolling, insulting or derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or email address, without their
explicit permission
- Other conduct which could reasonably be considered inappropriate in a professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior
and will take appropriate and fair corrective action in response to any behavior that they deem
inappropriate, threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject comments, commits,
code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and
will communicate reasons for moderation decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when an individual is
officially representing the community in public spaces. Examples of representing our community
include using an official e-mail address, posting via an official social media account, or acting as
an appointed representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community
leaders responsible for enforcement at dgraph-admin@istaridigital.com. All complaints will be
reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the reporter of any
incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining the consequences for
any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or
unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing clarity around the
nature of the violation and an explanation of why the behavior was inappropriate. A public apology
may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of actions.
**Consequence**: A warning with consequences for continued behavior. No interaction with the people
involved, including unsolicited interaction with those enforcing the Code of Conduct, for a
specified period of time. This includes avoiding interactions in community spaces as well as
external channels like social media. Violating these terms may lead to a temporary or permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including sustained inappropriate
behavior.
**Consequence**: A temporary ban from any sort of interaction or public communication with the
community for a specified period of time. No public or private interaction with the people involved,
including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this
period. Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community standards, including
sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement
of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by
[Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
================================================
FILE: CONTRIBUTING.md
================================================
# Contribution Guide
- [Before you get started](#before-you-get-started)
- [Code of Conduct](#code-of-conduct)
- [Your First Contribution](#your-first-contribution)
- [Find a good first topic](#find-a-good-first-topic)
- [Setting up your development environment](#setting-up-your-development-environment)
- [Fork the project](#fork-the-project)
- [Clone the project](#clone-the-project)
- [New branch for a new code](#new-branch-for-a-new-code)
- [Test](#test)
- [Commit and push](#commit-and-push)
- [Create a Pull Request](#create-a-pull-request)
- [Sign the CLA](#sign-the-cla)
- [Get a code review](#get-a-code-review)
## Before you get started
### Code of Conduct
Please make sure to read and observe our [Code of Conduct](./CODE_OF_CONDUCT.md).
## Your First Contribution
### Find a good first topic
You can start by finding an existing issue with the
[good first issue](https://github.com/dgraph-io/badger/labels/good%20first%20issue) or
[help wanted](https://github.com/dgraph-io/badger/labels/help%20wanted) labels. These issues are
well suited for new contributors.
## Setting up your development environment
- [Install Go 1.25.0 or above](https://golang.org/doc/install).
- Install
[trunk](https://docs.trunk.io/code-quality/overview/getting-started/install#install-the-launcher).
Our CI uses trunk to lint and check code, having it installed locally will save you time.
### Fork the project
- Visit https://github.com/dgraph-io/badger
- Click the `Fork` button (top right) to create a fork of the repository
### Clone the project
```sh
git clone https://github.com/$GITHUB_USER/badger
cd badger
git remote add upstream git@github.com:dgraph-io/badger.git
# Never push to the upstream master
git remote set-url --push upstream no_push
```
### New branch for a new code
Get your local master up to date:
```sh
git fetch upstream
git checkout master
git rebase upstream/master
```
Create a new branch from the master:
```sh
git checkout -b my_new_feature
```
And now you can finally add your changes to project.
### Test
Build and run all tests:
```sh
./test.sh
```
### Commit and push
Commit your changes:
```sh
git commit
```
When the changes are ready to review:
```sh
git push origin my_new_feature
```
### Create a Pull Request
Just open `https://github.com/$GITHUB_USER/badger/pull/new/my_new_feature` and fill the PR
description.
### Sign the CLA
Click the **Sign in with Github to agree** button to sign the CLA.
[An example](https://cla-assistant.io/dgraph-io/badger?pullRequest=1377).
### Get a code review
If your pull request (PR) is opened, it will be assigned to one or more reviewers. Those reviewers
will do a code review.
To address review comments, you should commit the changes to the same branch of the PR on your fork.
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
================================================
FILE: Makefile
================================================
#
# SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
# SPDX-License-Identifier: Apache-2.0
#
USER_ID = $(shell id -u)
HAS_JEMALLOC = $(shell test -f /usr/local/lib/libjemalloc.a && echo "jemalloc")
JEMALLOC_URL = "https://github.com/jemalloc/jemalloc/releases/download/5.3.0/jemalloc-5.3.0.tar.bz2"
.PHONY: all badger test jemalloc dependency
badger: jemalloc
@echo "Compiling Badger binary..."
@$(MAKE) -C badger badger
@echo "Badger binary located in badger directory."
test: jemalloc
@echo "Running Badger tests..."
@./test.sh
jemalloc:
@if [ -z "$(HAS_JEMALLOC)" ] ; then \
mkdir -p /tmp/jemalloc-temp && cd /tmp/jemalloc-temp ; \
echo "Downloading jemalloc..." ; \
curl -s -L ${JEMALLOC_URL} -o jemalloc.tar.bz2 ; \
tar xjf ./jemalloc.tar.bz2 ; \
cd jemalloc-5.3.0 ; \
./configure --with-jemalloc-prefix='je_' --with-malloc-conf='background_thread:true,metadata_thp:auto'; \
make ; \
if [ "$(USER_ID)" -eq "0" ]; then \
make install ; \
else \
echo "==== Need sudo access to install jemalloc" ; \
sudo make install ; \
fi \
fi
dependency:
@echo "Installing dependencies..."
@sudo apt-get update
@sudo apt-get -y install \
ca-certificates \
curl \
gnupg \
lsb-release \
build-essential \
protobuf-compiler \
================================================
FILE: README.md
================================================
# BadgerDB
[](https://pkg.go.dev/github.com/dgraph-io/badger/v4)
[](https://goreportcard.com/report/github.com/dgraph-io/badger/v4)
[](https://sourcegraph.com/github.com/dgraph-io/badger?badge)
[](https://github.com/dgraph-io/badger/actions/workflows/ci-badger-tests.yml)
[](https://github.com/dgraph-io/badger/actions/workflows/ci-badger-bank-tests.yml)
[](https://github.com/dgraph-io/badger/actions/workflows/ci-badger-bank-tests-nightly.yml)

BadgerDB is an embeddable, persistent and fast key-value (KV) database written in pure Go. It is the
underlying database for [Dgraph](https://github.com/dgraph-io/dgraph), a fast, distributed graph
database. It's meant to be a performant alternative to non-Go-based key-value stores like RocksDB.
## Project Status
Badger is stable and is being used to serve data sets worth hundreds of terabytes. Badger supports
concurrent ACID transactions with serializable snapshot isolation (SSI) guarantees. A Jepsen-style
bank test runs nightly for 8h, with `--race` flag and ensures the maintenance of transactional
guarantees. Badger has also been tested to work with filesystem level anomalies, to ensure
persistence and consistency. Badger is being used by a number of projects which includes Dgraph,
Jaeger Tracing, UsenetExpress, and many more.
The list of projects using Badger can be found [here](#projects-using-badger).
Please consult the [Changelog] for more detailed information on releases.
Note: Badger is built with go 1.23 and we refrain from bumping this version to minimize downstream
effects of those using Badger in applications built with older versions of Go.
[Changelog]: https://github.com/dgraph-io/badger/blob/main/CHANGELOG.md
## Table of Contents
- [BadgerDB](#badgerdb)
- [Project Status](#project-status)
- [Table of Contents](#table-of-contents)
- [Getting Started](#getting-started)
- [Installing](#installing)
- [Installing Badger Command Line Tool](#installing-badger-command-line-tool)
- [Choosing a version](#choosing-a-version)
- [Badger Documentation](#badger-documentation)
- [Resources](#resources)
- [Blog Posts](#blog-posts)
- [Design](#design)
- [Comparisons](#comparisons)
- [Benchmarks](#benchmarks)
- [Projects Using Badger](#projects-using-badger)
- [Contributing](#contributing)
- [Contact](#contact)
## Getting Started
### Installing
To start using Badger, install Go 1.23 or above. Badger v3 and above needs go modules. From your
project, run the following command
```sh
go get github.com/dgraph-io/badger/v4
```
This will retrieve the library.
#### Installing Badger Command Line Tool
Badger provides a CLI tool which can perform certain operations like offline backup/restore. To
install the Badger CLI, retrieve the repository and checkout the desired version. Then run
```sh
cd badger
go install .
```
This will install the badger command line utility into your $GOBIN path.
## Badger Documentation
Badger Documentation is available at [https://badger.dgraph.io](https://badger.dgraph.io)
## Resources
### Blog Posts
1. [Introducing Badger: A fast key-value store written natively in Go](https://hypermode.com/blog/badger/)
2. [Make Badger crash resilient with ALICE](https://hypermode.com/blog/alice/)
3. [Badger vs LMDB vs BoltDB: Benchmarking key-value databases in Go](https://hypermode.com/blog/badger-lmdb-boltdb/)
4. [Concurrent ACID Transactions in Badger](https://hypermode.com/blog/badger-txn/)
## Design
Badger was written with these design goals in mind:
- Write a key-value database in pure Go.
- Use latest research to build the fastest KV database for data sets spanning terabytes.
- Optimize for SSDs.
Badger’s design is based on a paper titled _[WiscKey: Separating Keys from Values in SSD-conscious
Storage][wisckey]_.
[wisckey]: https://www.usenix.org/system/files/conference/fast16/fast16-papers-lu.pdf
### Comparisons
| Feature | Badger | RocksDB | BoltDB |
| ----------------------------- | ------------------------------------------ | ----------------------------- | --------- |
| Design | LSM tree with value log | LSM tree only | B+ tree |
| High Read throughput | Yes | No | Yes |
| High Write throughput | Yes | Yes | No |
| Designed for SSDs | Yes (with latest research 1) | Not specifically 2 | No |
| Embeddable | Yes | Yes | Yes |
| Sorted KV access | Yes | Yes | Yes |
| Pure Go (no Cgo) | Yes | No | Yes |
| Transactions | Yes, ACID, concurrent with SSI3 | Yes (but non-ACID) | Yes, ACID |
| Snapshots | Yes | Yes | Yes |
| TTL support | Yes | Yes | No |
| 3D access (key-value-version) | Yes4 | No | No |
1 The [WISCKEY paper][wisckey] (on which Badger is based) saw big wins with separating
values from keys, significantly reducing the write amplification compared to a typical LSM tree.
2 RocksDB is an SSD optimized version of LevelDB, which was designed specifically for
rotating disks. As such RocksDB's design isn't aimed at SSDs.
3 SSI: Serializable Snapshot Isolation. For more details, see the blog post
[Concurrent ACID Transactions in Badger](https://hypermode.com/blog/badger-txn/)
4 Badger provides direct access to value versions via its Iterator API. Users can also
specify how many versions to keep per key via Options.
### Benchmarks
We have run comprehensive benchmarks against RocksDB, Bolt and LMDB. The benchmarking code, and the
detailed logs for the benchmarks can be found in the [badger-bench] repo. More explanation,
including graphs can be found the blog posts (linked above).
[badger-bench]: https://github.com/dgraph-io/badger-bench
## Projects Using Badger
Below is a list of known projects that use Badger:
- [Dgraph](https://github.com/dgraph-io/dgraph) - Distributed graph database.
- [Jaeger](https://github.com/jaegertracing/jaeger) - Distributed tracing platform.
- [go-ipfs](https://github.com/ipfs/go-ipfs) - Go client for the InterPlanetary File System (IPFS),
a new hypermedia distribution protocol.
- [Riot](https://github.com/go-ego/riot) - An open-source, distributed search engine.
- [emitter](https://github.com/emitter-io/emitter) - Scalable, low latency, distributed pub/sub
broker with message storage, uses MQTT, gossip and badger.
- [OctoSQL](https://github.com/cube2222/octosql) - Query tool that allows you to join, analyse and
transform data from multiple databases using SQL.
- [Dkron](https://dkron.io/) - Distributed, fault tolerant job scheduling system.
- [smallstep/certificates](https://github.com/smallstep/certificates) - Step-ca is an online
certificate authority for secure, automated certificate management.
- [Sandglass](https://github.com/celrenheit/sandglass) - distributed, horizontally scalable,
persistent, time sorted message queue.
- [TalariaDB](https://github.com/grab/talaria) - Grab's Distributed, low latency time-series
database.
- [Sloop](https://github.com/salesforce/sloop) - Salesforce's Kubernetes History Visualization
Project.
- [Usenet Express](https://usenetexpress.com/) - Serving over 300TB of data with Badger.
- [gorush](https://github.com/appleboy/gorush) - A push notification server written in Go.
- [0-stor](https://github.com/zero-os/0-stor) - Single device object store.
- [Dispatch Protocol](https://github.com/dispatchlabs/disgo) - Blockchain protocol for distributed
application data analytics.
- [GarageMQ](https://github.com/valinurovam/garagemq) - AMQP server written in Go.
- [RedixDB](https://alash3al.github.io/redix/) - A real-time persistent key-value store with the
same redis protocol.
- [BBVA](https://github.com/BBVA/raft-badger) - Raft backend implementation using BadgerDB for
Hashicorp raft.
- [Fantom](https://github.com/Fantom-foundation/go-lachesis) - aBFT Consensus platform for
distributed applications.
- [decred](https://github.com/decred/dcrdata) - An open, progressive, and self-funding
cryptocurrency with a system of community-based governance integrated into its blockchain.
- [OpenNetSys](https://github.com/opennetsys/c3-go) - Create useful dApps in any software language.
- [HoneyTrap](https://github.com/honeytrap/honeytrap) - An extensible and opensource system for
running, monitoring and managing honeypots.
- [Insolar](https://github.com/insolar/insolar) - Enterprise-ready blockchain platform.
- [IoTeX](https://github.com/iotexproject/iotex-core) - The next generation of the decentralized
network for IoT powered by scalability- and privacy-centric blockchains.
- [go-sessions](https://github.com/kataras/go-sessions) - The sessions manager for Go net/http and
fasthttp.
- [Babble](https://github.com/mosaicnetworks/babble) - BFT Consensus platform for distributed
applications.
- [Tormenta](https://github.com/jpincas/tormenta) - Embedded object-persistence layer / simple JSON
database for Go projects.
- [BadgerHold](https://github.com/timshannon/badgerhold) - An embeddable NoSQL store for querying Go
types built on Badger
- [Goblero](https://github.com/didil/goblero) - Pure Go embedded persistent job queue backed by
BadgerDB
- [Surfline](https://www.surfline.com) - Serving global wave and weather forecast data with Badger.
- [Cete](https://github.com/mosuka/cete) - Simple and highly available distributed key-value store
built on Badger. Makes it easy bringing up a cluster of Badger with Raft consensus algorithm by
hashicorp/raft.
- [Volument](https://volument.com/) - A new take on website analytics backed by Badger.
- [KVdb](https://kvdb.io/) - Hosted key-value store and serverless platform built on top of Badger.
- [Terminotes](https://gitlab.com/asad-awadia/terminotes) - Self hosted notes storage and search
server - storage powered by BadgerDB
- [Pyroscope](https://github.com/pyroscope-io/pyroscope) - Open source continuous profiling platform
built with BadgerDB
- [Veri](https://github.com/bgokden/veri) - A distributed feature store optimized for Search and
Recommendation tasks.
- [bIter](https://github.com/MikkelHJuul/bIter) - A library and Iterator interface for working with
the `badger.Iterator`, simplifying from-to, and prefix mechanics.
- [ld](https://github.com/MikkelHJuul/ld) - (Lean Database) A very simple gRPC-only key-value
database, exposing BadgerDB with key-range scanning semantics.
- [Souin](https://github.com/darkweak/Souin) - A RFC compliant HTTP cache with lot of other features
based on Badger for the storage. Compatible with all existing reverse-proxies.
- [Xuperchain](https://github.com/xuperchain/xupercore) - A highly flexible blockchain architecture
with great transaction performance.
- [m2](https://github.com/qichengzx/m2) - A simple http key/value store based on the raft protocol.
- [chaindb](https://github.com/ChainSafe/chaindb) - A blockchain storage layer used by
[Gossamer](https://chainsafe.github.io/gossamer/), a Go client for the
[Polkadot Network](https://polkadot.network/).
- [vxdb](https://github.com/vitalvas/vxdb) - Simple schema-less Key-Value NoSQL database with
simplest API interface.
- [Opacity](https://github.com/opacity/storage-node) - Backend implementation for the Opacity
storage project
- [Vephar](https://github.com/vaccovecrana/vephar) - A minimal key/value store using hashicorp-raft
for cluster coordination and Badger for data storage.
- [gowarcserver](https://github.com/nlnwa/gowarcserver) - Open-source server for warc files. Can be
used in conjunction with pywb
- [flow-go](https://github.com/onflow/flow-go) - A fast, secure, and developer-friendly blockchain
built to support the next generation of games, apps and the digital assets that power them.
- [Wrgl](https://www.wrgl.co) - A data version control system that works like Git but specialized to
store and diff CSV.
- [Loggie](https://github.com/loggie-io/loggie) - A lightweight, cloud-native data transfer agent
and aggregator.
- [raft-badger](https://github.com/rfyiamcool/raft-badger) - raft-badger implements LogStore and
StableStore Interface of hashcorp/raft. it is used to store raft log and metadata of
hashcorp/raft.
- [DVID](https://github.com/janelia-flyem/dvid) - A dataservice for branched versioning of a variety
of data types. Originally created for large-scale brain reconstructions in Connectomics.
- [KVS](https://github.com/tauraamui/kvs) - A library for making it easy to persist, load and query
full structs into BadgerDB, using an ownership hierarchy model.
- [LLS](https://github.com/Boc-chi-no/LLS) - LLS is an efficient URL Shortener that can be used to
shorten links and track link usage. Support for BadgerDB and MongoDB. Improved performance by more
than 30% when using BadgerDB
- [lakeFS](https://github.com/treeverse/lakeFS) - lakeFS is an open-source data version control that
transforms your object storage to Git-like repositories. lakeFS uses BadgerDB for its underlying
local metadata KV store implementation
- [Goptivum](https://github.com/smegg99/Goptivum) - Goptivum is a better frontend and API for the
Vulcan Optivum schedule program
- [ActionManager](https://mftlabs.io/actionmanager) - A dynamic entity manager based on rjsf schema
and badger db
- [MightyMap](https://github.com/thisisdevelopment/mightymap) - Mightymap: Conveys both robustness
and high capability, fitting for a powerful concurrent map.
- [FlowG](https://github.com/link-society/flowg) - A low-code log processing facility
- [Bluefin](https://github.com/blinklabs-io/bluefin) - Bluefin is a TUNA Proof of Work miner for the
Fortuna smart contract on the Cardano blockchain
- [cDNSd](https://github.com/blinklabs-io/cdnsd) - A Cardano blockchain backed DNS server daemon
- [Dingo](https://github.com/blinklabs-io/dingo) - A Cardano blockchain data node
If you are using Badger in a project please send a pull request to add it to the list.
### Platform Compatibility
Badger uses OS-specific implementations for directory locking and `fsync` operations. On
**POSIX-compliant systems** (Linux, macOS, BSD), these work as expected.
For **non-POSIX platforms**, be aware of potential limitations:
| Platform | File | Notes |
| -------- | ---------------- | -------------------------------------------------------------------- |
| AIX | `dir_aix.go` | Directory `fsync` not supported; durability on crash may be affected |
| Windows | `dir_windows.go` | Uses different locking mechanism |
| Plan9 | `dir_plan9.go` | No file locking support |
| WASM/JS | `dir_other.go` | No file locking support |
If you encounter issues on these platforms, review the corresponding `dir_*.go` source file for
implementation details.
## Contributing
If you're interested in contributing to Badger see [CONTRIBUTING](./CONTRIBUTING.md).
## Contact
- Please use [Github issues](https://github.com/dgraph-io/badger/issues) for filing bugs.
- Please use [Discussions](https://github.com/orgs/dgraph-io/discussions) for questions,
discussions, and feature requests.
================================================
FILE: SECURITY.md
================================================
# Reporting Security Concerns
We take the security of Badger very seriously. If you believe you have found a security
vulnerability in Badger, we encourage you to let us know right away.
We will investigate all legitimate reports and do our best to quickly fix the problem. Please report
any issues or vulnerabilities via GitHub Security Advisories instead of posting a public issue in
GitHub. You can also send security communications to dgraph-admin@istaridigital.com.
Please include the version identifier and details on how the vulnerability can be exploited.
================================================
FILE: VERSIONING.md
================================================
# Serialization Versioning: Semantic Versioning for databases
Semantic Versioning, commonly known as SemVer, is a great idea that has been very widely adopted as
a way to decide how to name software versions. The whole concept is very well summarized on
semver.org with the following lines:
> Given a version number MAJOR.MINOR.PATCH, increment the:
>
> 1. MAJOR version when you make incompatible API changes,
> 2. MINOR version when you add functionality in a backwards-compatible manner, and
> 3. PATCH version when you make backwards-compatible bug fixes.
>
> Additional labels for pre-release and build metadata are available as extensions to the
> MAJOR.MINOR.PATCH format.
Unfortunately, API changes are not the most important changes for libraries that serialize data for
later consumption. For these libraries, such as BadgerDB, changes to the API are much easier to
handle than change to the data format used to store data on disk.
## Serialization Version specification
Serialization Versioning, like Semantic Versioning, uses 3 numbers and also calls them
MAJOR.MINOR.PATCH, but the semantics of the numbers are slightly modified:
Given a version number MAJOR.MINOR.PATCH, increment the:
- MAJOR version when you make changes that require a transformation of the dataset before it can be
used again.
- MINOR version when old datasets are still readable but the API might have changed in
backwards-compatible or incompatible ways.
- PATCH version when you make backwards-compatible bug fixes.
Additional labels for pre-release and build metadata are available as extensions to the
MAJOR.MINOR.PATCH format.
Following this naming strategy, migration from v1.x to v2.x requires a migration strategy for your
existing dataset, and as such has to be carefully planned. Migrations in between different minor
versions (e.g. v1.5.x and v1.6.x) might break your build, as the API _might_ have changed, but once
your code compiles there's no need for any data migration. Lastly, changes in between two different
patch versions should never break your build or dataset.
For more background on our decision to adopt Serialization Versioning, read the blog post [Semantic
Versioning, Go Modules, and Databases][blog] and the original proposal on [this comment on Dgraph's
Discuss forum][discuss].
[blog]: https://open.dgraph.io/post/serialization-versioning/
[discuss]: https://discuss.dgraph.io/t/go-modules-on-badger-and-dgraph/4662/7
================================================
FILE: backup.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"bufio"
"bytes"
"context"
"encoding/binary"
"fmt"
"io"
"google.golang.org/protobuf/proto"
"github.com/dgraph-io/badger/v4/pb"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2/z"
)
// flushThreshold determines when a buffer will be flushed. When performing a
// backup/restore, the entries will be batched up until the total size of batch
// is more than flushThreshold or entry size (without the value size) is more
// than the maxBatchSize.
const flushThreshold = 100 << 20
// Backup dumps a protobuf-encoded list of all entries in the database into the
// given writer, that are newer than or equal to the specified version. It
// returns a timestamp (version) indicating the version of last entry that is
// dumped, which after incrementing by 1 can be passed into later invocation to
// generate incremental backup of entries that have been added/modified since
// the last invocation of DB.Backup().
// DB.Backup is a wrapper function over Stream.Backup to generate full and
// incremental backups of the DB. For more control over how many goroutines are
// used to generate the backup, or if you wish to backup only a certain range
// of keys, use Stream.Backup directly.
func (db *DB) Backup(w io.Writer, since uint64) (uint64, error) {
stream := db.NewStream()
stream.LogPrefix = "DB.Backup"
stream.SinceTs = since
return stream.Backup(w, since)
}
// Backup dumps a protobuf-encoded list of all entries in the database into the
// given writer, that are newer than or equal to the specified version. It returns a
// timestamp(version) indicating the version of last entry that was dumped, which
// after incrementing by 1 can be passed into a later invocation to generate an
// incremental dump of entries that have been added/modified since the last
// invocation of Stream.Backup().
//
// This can be used to backup the data in a database at a given point in time.
func (stream *Stream) Backup(w io.Writer, since uint64) (uint64, error) {
stream.KeyToList = func(key []byte, itr *Iterator) (*pb.KVList, error) {
list := &pb.KVList{}
a := itr.Alloc
for ; itr.Valid(); itr.Next() {
item := itr.Item()
if !bytes.Equal(item.Key(), key) {
return list, nil
}
if item.Version() < since {
return nil, fmt.Errorf("Backup: Item Version: %d less than sinceTs: %d",
item.Version(), since)
}
var valCopy []byte
if !item.IsDeletedOrExpired() {
// No need to copy value, if item is deleted or expired.
err := item.Value(func(val []byte) error {
valCopy = a.Copy(val)
return nil
})
if err != nil {
stream.db.opt.Errorf("Key [%x, %d]. Error while fetching value [%v]\n",
item.Key(), item.Version(), err)
return nil, err
}
}
// clear txn bits
meta := item.meta &^ (bitTxn | bitFinTxn)
kv := y.NewKV(a)
*kv = pb.KV{
Key: a.Copy(item.Key()),
Value: valCopy,
UserMeta: a.Copy([]byte{item.UserMeta()}),
Version: item.Version(),
ExpiresAt: item.ExpiresAt(),
Meta: a.Copy([]byte{meta}),
}
list.Kv = append(list.Kv, kv)
switch {
case item.DiscardEarlierVersions():
// If we need to discard earlier versions of this item, add a delete
// marker just below the current version.
list.Kv = append(list.Kv, &pb.KV{
Key: item.KeyCopy(nil),
Version: item.Version() - 1,
Meta: []byte{bitDelete},
})
return list, nil
case item.IsDeletedOrExpired():
return list, nil
}
}
return list, nil
}
var maxVersion uint64
stream.Send = func(buf *z.Buffer) error {
list, err := BufferToKVList(buf)
if err != nil {
return err
}
out := list.Kv[:0]
for _, kv := range list.Kv {
if maxVersion < kv.Version {
maxVersion = kv.Version
}
if !kv.StreamDone {
// Don't pick stream done changes.
out = append(out, kv)
}
}
list.Kv = out
return writeTo(list, w)
}
if err := stream.Orchestrate(context.Background()); err != nil {
return 0, err
}
return maxVersion, nil
}
func writeTo(list *pb.KVList, w io.Writer) error {
if err := binary.Write(w, binary.LittleEndian, uint64(proto.Size(list))); err != nil {
return err
}
buf, err := proto.Marshal(list)
if err != nil {
return err
}
_, err = w.Write(buf)
return err
}
// KVLoader is used to write KVList objects in to badger. It can be used to restore a backup.
type KVLoader struct {
db *DB
throttle *y.Throttle
entries []*Entry
entriesSize int64
totalSize int64
}
// NewKVLoader returns a new instance of KVLoader.
func (db *DB) NewKVLoader(maxPendingWrites int) *KVLoader {
return &KVLoader{
db: db,
throttle: y.NewThrottle(maxPendingWrites),
entries: make([]*Entry, 0, db.opt.maxBatchCount),
}
}
// Set writes the key-value pair to the database.
func (l *KVLoader) Set(kv *pb.KV) error {
var userMeta, meta byte
if len(kv.UserMeta) > 0 {
userMeta = kv.UserMeta[0]
}
if len(kv.Meta) > 0 {
meta = kv.Meta[0]
}
e := &Entry{
Key: y.KeyWithTs(kv.Key, kv.Version),
Value: kv.Value,
UserMeta: userMeta,
ExpiresAt: kv.ExpiresAt,
meta: meta,
}
estimatedSize := e.estimateSizeAndSetThreshold(l.db.valueThreshold())
// Flush entries if inserting the next entry would overflow the transactional limits.
if int64(len(l.entries))+1 >= l.db.opt.maxBatchCount ||
l.entriesSize+estimatedSize >= l.db.opt.maxBatchSize ||
l.totalSize >= flushThreshold {
if err := l.send(); err != nil {
return err
}
}
l.entries = append(l.entries, e)
l.entriesSize += estimatedSize
l.totalSize += estimatedSize + int64(len(e.Value))
return nil
}
func (l *KVLoader) send() error {
if err := l.throttle.Do(); err != nil {
return err
}
if err := l.db.batchSetAsync(l.entries, func(err error) {
l.throttle.Done(err)
}); err != nil {
return err
}
l.entries = make([]*Entry, 0, l.db.opt.maxBatchCount)
l.entriesSize = 0
l.totalSize = 0
return nil
}
// Finish is meant to be called after all the key-value pairs have been loaded.
func (l *KVLoader) Finish() error {
if len(l.entries) > 0 {
if err := l.send(); err != nil {
return err
}
}
return l.throttle.Finish()
}
// Load reads a protobuf-encoded list of all entries from a reader and writes
// them to the database. This can be used to restore the database from a backup
// made by calling DB.Backup(). If more complex logic is needed to restore a badger
// backup, the KVLoader interface should be used instead.
//
// DB.Load() should be called on a database that is not running any other
// concurrent transactions while it is running.
func (db *DB) Load(r io.Reader, maxPendingWrites int) error {
br := bufio.NewReaderSize(r, 16<<10)
unmarshalBuf := make([]byte, 1<<10)
ldr := db.NewKVLoader(maxPendingWrites)
for {
var sz uint64
err := binary.Read(br, binary.LittleEndian, &sz)
if err == io.EOF {
break
} else if err != nil {
return err
}
if cap(unmarshalBuf) < int(sz) {
unmarshalBuf = make([]byte, sz)
}
if _, err = io.ReadFull(br, unmarshalBuf[:sz]); err != nil {
return err
}
list := &pb.KVList{}
if err := proto.Unmarshal(unmarshalBuf[:sz], list); err != nil {
return err
}
for _, kv := range list.Kv {
if err := ldr.Set(kv); err != nil {
return err
}
// Update nextTxnTs, memtable stores this
// timestamp in badger head when flushed.
if kv.Version >= db.orc.nextTxnTs {
db.orc.nextTxnTs = kv.Version + 1
}
}
}
if err := ldr.Finish(); err != nil {
return err
}
db.orc.txnMark.Done(db.orc.nextTxnTs - 1)
return nil
}
================================================
FILE: backup_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"bytes"
"fmt"
"math/rand"
"os"
"path/filepath"
"reflect"
"strconv"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/dgraph-io/badger/v4/pb"
)
func TestBackupRestore1(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
db, err := Open(getTestOptions(dir))
require.NoError(t, err)
// Write some stuff
entries := []struct {
key []byte
val []byte
userMeta byte
version uint64
}{
{key: []byte("answer1"), val: []byte("42"), version: 1},
{key: []byte("answer2"), val: []byte("43"), userMeta: 1, version: 2},
}
err = db.Update(func(txn *Txn) error {
e := entries[0]
err := txn.SetEntry(NewEntry(e.key, e.val).WithMeta(e.userMeta))
if err != nil {
return err
}
return nil
})
require.NoError(t, err)
err = db.Update(func(txn *Txn) error {
e := entries[1]
err := txn.SetEntry(NewEntry(e.key, e.val).WithMeta(e.userMeta))
if err != nil {
return err
}
return nil
})
require.NoError(t, err)
// Use different directory.
dir, err = os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
bak, err := os.CreateTemp(dir, "badgerbak")
require.NoError(t, err)
_, err = db.Backup(bak, 0)
require.NoError(t, err)
require.NoError(t, bak.Close())
require.NoError(t, db.Close())
db, err = Open(getTestOptions(dir))
require.NoError(t, err)
defer db.Close()
bak, err = os.Open(bak.Name())
require.NoError(t, err)
defer bak.Close()
require.NoError(t, db.Load(bak, 16))
err = db.View(func(txn *Txn) error {
opts := DefaultIteratorOptions
opts.AllVersions = true
it := txn.NewIterator(opts)
defer it.Close()
var count int
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
val, err := item.ValueCopy(nil)
if err != nil {
return err
}
t.Logf("Got entry: %v\n", item.Version())
require.Equal(t, entries[count].key, item.Key())
require.Equal(t, entries[count].val, val)
require.Equal(t, entries[count].version, item.Version())
require.Equal(t, entries[count].userMeta, item.UserMeta())
count++
}
require.Equal(t, count, 2)
return nil
})
require.NoError(t, err)
require.Equal(t, 3, int(db.orc.nextTs()))
}
func TestBackupRestore2(t *testing.T) {
tmpdir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(tmpdir)
s1Path := filepath.Join(tmpdir, "test1")
s2Path := filepath.Join(tmpdir, "test2")
s3Path := filepath.Join(tmpdir, "test3")
db1, err := Open(getTestOptions(s1Path))
require.NoError(t, err)
defer db1.Close()
key1 := []byte("key1")
key2 := []byte("key2")
rawValue := []byte("NotLongValue")
N := byte(251)
err = db1.Update(func(tx *Txn) error {
if err := tx.SetEntry(NewEntry(key1, rawValue)); err != nil {
return err
}
return tx.SetEntry(NewEntry(key2, rawValue))
})
require.NoError(t, err)
for i := byte(1); i < N; i++ {
err = db1.Update(func(tx *Txn) error {
if err := tx.SetEntry(NewEntry(append(key1, i), rawValue)); err != nil {
return err
}
return tx.SetEntry(NewEntry(append(key2, i), rawValue))
})
require.NoError(t, err)
}
var backup bytes.Buffer
_, err = db1.Backup(&backup, 0)
require.NoError(t, err)
fmt.Println("backup1 length:", backup.Len())
db2, err := Open(getTestOptions(s2Path))
require.NoError(t, err)
defer db2.Close()
err = db2.Load(&backup, 16)
require.NoError(t, err)
// Check nextTs is correctly set.
require.Equal(t, db1.orc.nextTs(), db2.orc.nextTs())
for i := byte(1); i < N; i++ {
err = db2.View(func(tx *Txn) error {
k := append(key1, i)
item, err := tx.Get(k)
if err != nil {
if err == ErrKeyNotFound {
return fmt.Errorf("Key %q has been not found, but was set\n", k)
}
return err
}
v, err := item.ValueCopy(nil)
if err != nil {
return err
}
if !reflect.DeepEqual(v, rawValue) {
return fmt.Errorf("Values not match, got %v, expected %v", v, rawValue)
}
return nil
})
require.NoError(t, err)
}
for i := byte(1); i < N; i++ {
err = db2.Update(func(tx *Txn) error {
if err := tx.SetEntry(NewEntry(append(key1, i), rawValue)); err != nil {
return err
}
return tx.SetEntry(NewEntry(append(key2, i), rawValue))
})
require.NoError(t, err)
}
backup.Reset()
_, err = db2.Backup(&backup, 0)
require.NoError(t, err)
fmt.Println("backup2 length:", backup.Len())
db3, err := Open(getTestOptions(s3Path))
require.NoError(t, err)
defer db3.Close()
err = db3.Load(&backup, 16)
require.NoError(t, err)
// Check nextTs is correctly set.
require.Equal(t, db2.orc.nextTs(), db3.orc.nextTs())
for i := byte(1); i < N; i++ {
err = db3.View(func(tx *Txn) error {
k := append(key1, i)
item, err := tx.Get(k)
if err != nil {
if err == ErrKeyNotFound {
return fmt.Errorf("Key %q has been not found, but was set\n", k)
}
return err
}
v, err := item.ValueCopy(nil)
if err != nil {
return err
}
if !reflect.DeepEqual(v, rawValue) {
return fmt.Errorf("Values not match, got %v, expected %v", v, rawValue)
}
return nil
})
require.NoError(t, err)
}
}
var randSrc = rand.NewSource(time.Now().UnixNano())
func createEntries(n int) []*pb.KV {
entries := make([]*pb.KV, n)
for i := 0; i < n; i++ {
entries[i] = &pb.KV{
Key: []byte(fmt.Sprint("key", i)),
Value: []byte{1},
UserMeta: []byte{0},
Meta: []byte{0},
}
}
return entries
}
func populateEntries(db *DB, entries []*pb.KV) error {
return db.Update(func(txn *Txn) error {
var err error
for i, e := range entries {
if err = txn.SetEntry(NewEntry(e.Key, e.Value)); err != nil {
return err
}
entries[i].Version = 1
}
return nil
})
}
func TestBackup(t *testing.T) {
test := func(t *testing.T, db *DB) {
var bb bytes.Buffer
N := 1000
entries := createEntries(N)
require.NoError(t, populateEntries(db, entries))
_, err := db.Backup(&bb, 0)
require.NoError(t, err)
err = db.View(func(txn *Txn) error {
opts := DefaultIteratorOptions
it := txn.NewIterator(opts)
defer it.Close()
var count int
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
idx, err := strconv.Atoi(string(item.Key())[3:])
if err != nil {
return err
}
if idx > N || !bytes.Equal(entries[idx].Key, item.Key()) {
return fmt.Errorf("%s: %s", string(item.Key()), ErrKeyNotFound)
}
count++
}
if N != count {
return fmt.Errorf("wrong number of items: %d expected, %d actual", N, count)
}
return nil
})
require.NoError(t, err)
}
t.Run("disk mode", func(t *testing.T) {
tmpdir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(tmpdir)
opt := DefaultOptions(filepath.Join(tmpdir, "backup0"))
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
test(t, db)
})
})
t.Run("InMemory mode", func(t *testing.T) {
opt := DefaultOptions("")
opt.InMemory = true
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
test(t, db)
})
})
}
func TestBackupRestore3(t *testing.T) {
var bb bytes.Buffer
tmpdir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(tmpdir)
N := 1000
entries := createEntries(N)
var db1NextTs uint64
// backup
{
db1, err := Open(DefaultOptions(filepath.Join(tmpdir, "backup1")))
require.NoError(t, err)
defer db1.Close()
require.NoError(t, populateEntries(db1, entries))
_, err = db1.Backup(&bb, 0)
require.NoError(t, err)
db1NextTs = db1.orc.nextTs()
require.NoError(t, db1.Close())
}
require.True(t, len(entries) == N)
require.True(t, bb.Len() > 0)
// restore
db2, err := Open(DefaultOptions(filepath.Join(tmpdir, "restore1")))
require.NoError(t, err)
defer db2.Close()
require.NotEqual(t, db1NextTs, db2.orc.nextTs())
require.NoError(t, db2.Load(&bb, 16))
require.Equal(t, db1NextTs, db2.orc.nextTs())
// verify
err = db2.View(func(txn *Txn) error {
opts := DefaultIteratorOptions
it := txn.NewIterator(opts)
defer it.Close()
var count int
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
idx, err := strconv.Atoi(string(item.Key())[3:])
if err != nil {
return err
}
if idx > N || !bytes.Equal(entries[idx].Key, item.Key()) {
return fmt.Errorf("%s: %s", string(item.Key()), ErrKeyNotFound)
}
count++
}
if N != count {
return fmt.Errorf("wrong number of items: %d expected, %d actual", N, count)
}
return nil
})
require.NoError(t, err)
}
func TestBackupLoadIncremental(t *testing.T) {
tmpdir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(tmpdir)
N := 100
entries := createEntries(N)
updates := make(map[int]byte)
var bb bytes.Buffer
var db1NextTs uint64
// backup
{
db1, err := Open(DefaultOptions(filepath.Join(tmpdir, "backup2")))
require.NoError(t, err)
defer db1.Close()
require.NoError(t, populateEntries(db1, entries))
since, err := db1.Backup(&bb, 0)
require.NoError(t, err)
ints := rand.New(randSrc).Perm(N)
// pick 10 items to mark as deleted.
err = db1.Update(func(txn *Txn) error {
for _, i := range ints[:10] {
if err := txn.Delete(entries[i].Key); err != nil {
return err
}
updates[i] = bitDelete
}
return nil
})
require.NoError(t, err)
since, err = db1.Backup(&bb, since)
require.NoError(t, err)
// pick 5 items to mark as expired.
err = db1.Update(func(txn *Txn) error {
for _, i := range (ints)[10:15] {
entry := NewEntry(entries[i].Key, entries[i].Value).WithTTL(-time.Hour)
if err := txn.SetEntry(entry); err != nil {
return err
}
updates[i] = bitDelete // expired
}
return nil
})
require.NoError(t, err)
since, err = db1.Backup(&bb, since)
require.NoError(t, err)
// pick 5 items to mark as discard.
err = db1.Update(func(txn *Txn) error {
for _, i := range ints[15:20] {
entry := NewEntry(entries[i].Key, entries[i].Value).WithDiscard()
if err := txn.SetEntry(entry); err != nil {
return err
}
updates[i] = bitDiscardEarlierVersions
}
return nil
})
require.NoError(t, err)
_, err = db1.Backup(&bb, since)
require.NoError(t, err)
db1NextTs = db1.orc.nextTs()
require.NoError(t, db1.Close())
}
require.True(t, len(entries) == N)
require.True(t, bb.Len() > 0)
// restore
db2, err := Open(getTestOptions(filepath.Join(tmpdir, "restore2")))
require.NoError(t, err)
defer db2.Close()
require.NotEqual(t, db1NextTs, db2.orc.nextTs())
require.NoError(t, db2.Load(&bb, 16))
require.Equal(t, db1NextTs, db2.orc.nextTs())
// verify
actual := make(map[int]byte)
err = db2.View(func(txn *Txn) error {
opts := DefaultIteratorOptions
opts.AllVersions = true
it := txn.NewIterator(opts)
defer it.Close()
var count int
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
idx, err := strconv.Atoi(string(item.Key())[3:])
if err != nil {
return err
}
if item.IsDeletedOrExpired() {
_, ok := updates[idx]
if !ok {
return fmt.Errorf("%s: not expected to be updated but it is",
string(item.Key()))
}
actual[idx] = item.meta
count++
continue
}
}
if len(updates) != count {
return fmt.Errorf("mismatched updated items: %d expected, %d actual",
len(updates), count)
}
return nil
})
require.NoError(t, err, "%v %v", updates, actual)
}
func TestBackupBitClear(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := getTestOptions(dir)
opt.ValueThreshold = 10 // This is important
db, err := Open(opt)
require.NoError(t, err)
key := []byte("foo")
val := []byte(fmt.Sprintf("%0100d", 1))
require.Greater(t, int64(len(val)), db.valueThreshold())
err = db.Update(func(txn *Txn) error {
e := NewEntry(key, val)
// Value > valueTheshold so bitValuePointer will be set.
return txn.SetEntry(e)
})
require.NoError(t, err)
// Use different directory.
dir, err = os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
bak, err := os.CreateTemp(dir, "badgerbak")
require.NoError(t, err)
_, err = db.Backup(bak, 0)
require.NoError(t, err)
require.NoError(t, bak.Close())
oldValue := db.orc.nextTs()
require.NoError(t, db.Close())
opt = getTestOptions(dir)
opt.ValueThreshold = 200 // This is important.
db, err = Open(opt)
require.NoError(t, err)
defer db.Close()
bak, err = os.Open(bak.Name())
require.NoError(t, err)
defer bak.Close()
require.NoError(t, db.Load(bak, 16))
// Ensure nextTs is still the same.
require.Equal(t, oldValue, db.orc.nextTs())
require.NoError(t, db.View(func(txn *Txn) error {
e, err := txn.Get(key)
require.NoError(t, err)
v, err := e.ValueCopy(nil)
require.NoError(t, err)
require.Equal(t, val, v)
return nil
}))
}
================================================
FILE: batch.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"errors"
"fmt"
"sync"
"sync/atomic"
"google.golang.org/protobuf/proto"
"github.com/dgraph-io/badger/v4/pb"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2/z"
)
// WriteBatch holds the necessary info to perform batched writes.
type WriteBatch struct {
sync.Mutex
txn *Txn
db *DB
throttle *y.Throttle
err atomic.Value
isManaged bool
commitTs uint64
finished bool
}
// NewWriteBatch creates a new WriteBatch. This provides a way to conveniently do a lot of writes,
// batching them up as tightly as possible in a single transaction and using callbacks to avoid
// waiting for them to commit, thus achieving good performance. This API hides away the logic of
// creating and committing transactions. Due to the nature of SSI guaratees provided by Badger,
// blind writes can never encounter transaction conflicts (ErrConflict).
func (db *DB) NewWriteBatch() *WriteBatch {
if db.opt.managedTxns {
panic("cannot use NewWriteBatch in managed mode. Use NewWriteBatchAt instead")
}
return db.newWriteBatch(false)
}
func (db *DB) newWriteBatch(isManaged bool) *WriteBatch {
return &WriteBatch{
db: db,
isManaged: isManaged,
txn: db.newTransaction(true, isManaged),
throttle: y.NewThrottle(16),
}
}
// SetMaxPendingTxns sets a limit on maximum number of pending transactions while writing batches.
// This function should be called before using WriteBatch. Default value of MaxPendingTxns is
// 16 to minimise memory usage.
func (wb *WriteBatch) SetMaxPendingTxns(max int) {
wb.throttle = y.NewThrottle(max)
}
// Cancel function must be called if there's a chance that Flush might not get
// called. If neither Flush or Cancel is called, the transaction oracle would
// never get a chance to clear out the row commit timestamp map, thus causing an
// unbounded memory consumption. Typically, you can call Cancel as a defer
// statement right after NewWriteBatch is called.
//
// Note that any committed writes would still go through despite calling Cancel.
func (wb *WriteBatch) Cancel() {
wb.Lock()
defer wb.Unlock()
wb.finished = true
if err := wb.throttle.Finish(); err != nil {
wb.db.opt.Errorf("WatchBatch.Cancel error while finishing: %v", err)
}
wb.txn.Discard()
}
func (wb *WriteBatch) callback(err error) {
// sync.WaitGroup is thread-safe, so it doesn't need to be run inside wb.Lock.
defer wb.throttle.Done(err)
if err == nil {
return
}
if err := wb.Error(); err != nil {
return
}
wb.err.Store(err)
}
func (wb *WriteBatch) writeKV(kv *pb.KV) error {
e := Entry{Key: kv.Key, Value: kv.Value}
if len(kv.UserMeta) > 0 {
e.UserMeta = kv.UserMeta[0]
}
y.AssertTrue(kv.Version != 0)
e.version = kv.Version
return wb.handleEntry(&e)
}
func (wb *WriteBatch) Write(buf *z.Buffer) error {
wb.Lock()
defer wb.Unlock()
err := buf.SliceIterate(func(s []byte) error {
kv := &pb.KV{}
if err := proto.Unmarshal(s, kv); err != nil {
return err
}
return wb.writeKV(kv)
})
return err
}
func (wb *WriteBatch) WriteList(kvList *pb.KVList) error {
wb.Lock()
defer wb.Unlock()
for _, kv := range kvList.Kv {
if err := wb.writeKV(kv); err != nil {
return err
}
}
return nil
}
// SetEntryAt is the equivalent of Txn.SetEntry but it also allows setting version for the entry.
// SetEntryAt can be used only in managed mode.
func (wb *WriteBatch) SetEntryAt(e *Entry, ts uint64) error {
if !wb.db.opt.managedTxns {
return errors.New("SetEntryAt can only be used in managed mode. Use SetEntry instead")
}
e.version = ts
return wb.SetEntry(e)
}
// Should be called with lock acquired.
func (wb *WriteBatch) handleEntry(e *Entry) error {
if err := wb.txn.SetEntry(e); err != ErrTxnTooBig {
return err
}
// Txn has reached it's zenith. Commit now.
if cerr := wb.commit(); cerr != nil {
return cerr
}
// This time the error must not be ErrTxnTooBig, otherwise, we make the
// error permanent.
if err := wb.txn.SetEntry(e); err != nil {
wb.err.Store(err)
return err
}
return nil
}
// SetEntry is the equivalent of Txn.SetEntry.
func (wb *WriteBatch) SetEntry(e *Entry) error {
wb.Lock()
defer wb.Unlock()
return wb.handleEntry(e)
}
// Set is equivalent of Txn.Set().
func (wb *WriteBatch) Set(k, v []byte) error {
e := &Entry{Key: k, Value: v}
return wb.SetEntry(e)
}
// DeleteAt is equivalent of Txn.Delete but accepts a delete timestamp.
func (wb *WriteBatch) DeleteAt(k []byte, ts uint64) error {
e := Entry{Key: k, meta: bitDelete, version: ts}
return wb.SetEntry(&e)
}
// Delete is equivalent of Txn.Delete.
func (wb *WriteBatch) Delete(k []byte) error {
wb.Lock()
defer wb.Unlock()
if err := wb.txn.Delete(k); err != ErrTxnTooBig {
return err
}
if err := wb.commit(); err != nil {
return err
}
if err := wb.txn.Delete(k); err != nil {
wb.err.Store(err)
return err
}
return nil
}
// Caller to commit must hold a write lock.
func (wb *WriteBatch) commit() error {
if err := wb.Error(); err != nil {
return err
}
if wb.finished {
return y.ErrCommitAfterFinish
}
if err := wb.throttle.Do(); err != nil {
wb.err.Store(err)
return err
}
wb.txn.CommitWith(wb.callback)
wb.txn = wb.db.newTransaction(true, wb.isManaged)
wb.txn.commitTs = wb.commitTs
return wb.Error()
}
// Flush must be called at the end to ensure that any pending writes get committed to Badger. Flush
// returns any error stored by WriteBatch.
func (wb *WriteBatch) Flush() error {
wb.Lock()
err := wb.commit()
if err != nil {
wb.Unlock()
return err
}
wb.finished = true
wb.txn.Discard()
wb.Unlock()
if err := wb.throttle.Finish(); err != nil {
if wb.Error() != nil {
return fmt.Errorf("wb.err: %w err: %w", wb.Error(), err)
}
return err
}
return wb.Error()
}
// Error returns any errors encountered so far. No commits would be run once an error is detected.
func (wb *WriteBatch) Error() error {
// If the interface conversion fails, the err will be nil.
err, _ := wb.err.Load().(error)
return err
}
================================================
FILE: batch_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"fmt"
"os"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/dgraph-io/badger/v4/y"
)
func TestWriteBatch(t *testing.T) {
key := func(i int) []byte {
return []byte(fmt.Sprintf("%10d", i))
}
val := func(i int) []byte {
return []byte(fmt.Sprintf("%128d", i))
}
test := func(t *testing.T, db *DB) {
wb := db.NewWriteBatch()
defer wb.Cancel()
// Sanity check for SetEntryAt.
require.Error(t, wb.SetEntryAt(&Entry{}, 12))
N, M := 50000, 1000
start := time.Now()
for i := 0; i < N; i++ {
require.NoError(t, wb.Set(key(i), val(i)))
}
for i := 0; i < M; i++ {
require.NoError(t, wb.Delete(key(i)))
}
require.NoError(t, wb.Flush())
t.Logf("Time taken for %d writes (w/ test options): %s\n", N+M, time.Since(start))
err := db.View(func(txn *Txn) error {
itr := txn.NewIterator(DefaultIteratorOptions)
defer itr.Close()
i := M
for itr.Rewind(); itr.Valid(); itr.Next() {
item := itr.Item()
require.Equal(t, string(key(i)), string(item.Key()))
valcopy, err := item.ValueCopy(nil)
require.NoError(t, err)
require.Equal(t, val(i), valcopy)
i++
}
require.Equal(t, N, i)
return nil
})
require.NoError(t, err)
}
t.Run("disk mode", func(t *testing.T) {
opt := getTestOptions("")
// Set value threshold to 32 bytes otherwise write batch will generate
// too many files and we will crash with too many files open error.
opt.ValueThreshold = 32
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
test(t, db)
})
t.Logf("Disk mode done\n")
})
t.Run("InMemory mode", func(t *testing.T) {
t.Skipf("TODO(ibrahim): Please fix this")
opt := getTestOptions("")
opt.InMemory = true
db, err := Open(opt)
require.NoError(t, err)
test(t, db)
t.Logf("Disk mode done\n")
require.NoError(t, db.Close())
})
}
// This test ensures we don't end up in deadlock in case of empty writebatch.
func TestEmptyWriteBatch(t *testing.T) {
t.Run("normal mode", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
wb := db.NewWriteBatch()
require.NoError(t, wb.Flush())
wb = db.NewWriteBatch()
require.NoError(t, wb.Flush())
wb = db.NewWriteBatch()
// Flush commits inner txn and sets a new one instead.
// Thus we need to save it to check if it was discarded.
txn := wb.txn
require.NoError(t, wb.Flush())
// check that flushed txn was discarded and marked as read.
require.True(t, txn.discarded)
})
})
t.Run("managed mode", func(t *testing.T) {
opt := getTestOptions("")
opt.managedTxns = true
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
t.Run("WriteBatchAt", func(t *testing.T) {
wb := db.NewWriteBatchAt(2)
require.NoError(t, wb.Flush())
wb = db.NewWriteBatchAt(208)
require.NoError(t, wb.Flush())
wb = db.NewWriteBatchAt(31)
require.NoError(t, wb.Flush())
})
t.Run("ManagedWriteBatch", func(t *testing.T) {
wb := db.NewManagedWriteBatch()
require.NoError(t, wb.Flush())
wb = db.NewManagedWriteBatch()
require.NoError(t, wb.Flush())
wb = db.NewManagedWriteBatch()
require.NoError(t, wb.Flush())
})
})
})
}
// This test ensures we don't panic during flush.
// See issue: https://github.com/dgraph-io/badger/issues/1394
func TestFlushPanic(t *testing.T) {
t.Run("flush after flush", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
wb := db.NewWriteBatch()
wb.Flush()
require.Error(t, y.ErrCommitAfterFinish, wb.Flush())
})
})
t.Run("flush after cancel", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
wb := db.NewWriteBatch()
wb.Cancel()
require.Error(t, y.ErrCommitAfterFinish, wb.Flush())
})
})
}
func TestBatchErrDeadlock(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := DefaultOptions(dir)
db, err := OpenManaged(opt)
require.NoError(t, err)
wb := db.NewManagedWriteBatch()
require.NoError(t, wb.SetEntryAt(&Entry{Key: []byte("foo")}, 0))
require.Error(t, wb.Flush())
require.NoError(t, db.Close())
}
================================================
FILE: changes.sh
================================================
#!/bin/bash
set -e
GHORG=${GHORG:-dgraph-io}
GHREPO=${GHREPO:-badger}
cat < 0 {
r.right = kr.right
}
if kr.inf {
r.inf = true
}
}
func (r keyRange) overlapsWith(dst keyRange) bool {
// Empty keyRange always overlaps.
if r.isEmpty() {
return true
}
// TODO(ibrahim): Do you need this?
// Empty dst doesn't overlap with anything.
if dst.isEmpty() {
return false
}
if r.inf || dst.inf {
return true
}
// [dst.left, dst.right] ... [r.left, r.right]
// If my left is greater than dst right, we have no overlap.
if y.CompareKeys(r.left, dst.right) > 0 {
return false
}
// [r.left, r.right] ... [dst.left, dst.right]
// If my right is less than dst left, we have no overlap.
if y.CompareKeys(r.right, dst.left) < 0 {
return false
}
// We have overlap.
return true
}
// getKeyRange returns the smallest and the biggest in the list of tables.
// TODO(naman): Write a test for this. The smallest and the biggest should
// be the smallest of the leftmost table and the biggest of the right most table.
func getKeyRange(tables ...*table.Table) keyRange {
if len(tables) == 0 {
return keyRange{}
}
smallest := tables[0].Smallest()
biggest := tables[0].Biggest()
for i := 1; i < len(tables); i++ {
if y.CompareKeys(tables[i].Smallest(), smallest) < 0 {
smallest = tables[i].Smallest()
}
if y.CompareKeys(tables[i].Biggest(), biggest) > 0 {
biggest = tables[i].Biggest()
}
}
// We pick all the versions of the smallest and the biggest key. Note that version zero would
// be the rightmost key, considering versions are default sorted in descending order.
return keyRange{
left: y.KeyWithTs(y.ParseKey(smallest), math.MaxUint64),
right: y.KeyWithTs(y.ParseKey(biggest), 0),
}
}
type levelCompactStatus struct {
ranges []keyRange
delSize int64
}
func (lcs *levelCompactStatus) debug() string {
var b bytes.Buffer
for _, r := range lcs.ranges {
b.WriteString(r.String())
}
return b.String()
}
func (lcs *levelCompactStatus) overlapsWith(dst keyRange) bool {
for _, r := range lcs.ranges {
if r.overlapsWith(dst) {
return true
}
}
return false
}
func (lcs *levelCompactStatus) remove(dst keyRange) bool {
final := lcs.ranges[:0]
var found bool
for _, r := range lcs.ranges {
if !r.equals(dst) {
final = append(final, r)
} else {
found = true
}
}
lcs.ranges = final
return found
}
type compactStatus struct {
sync.RWMutex
levels []*levelCompactStatus
tables map[uint64]struct{}
}
func (cs *compactStatus) overlapsWith(level int, this keyRange) bool {
cs.RLock()
defer cs.RUnlock()
thisLevel := cs.levels[level]
return thisLevel.overlapsWith(this)
}
func (cs *compactStatus) delSize(l int) int64 {
cs.RLock()
defer cs.RUnlock()
return cs.levels[l].delSize
}
type thisAndNextLevelRLocked struct{}
// compareAndAdd will check whether we can run this compactDef. That it doesn't overlap with any
// other running compaction. If it can be run, it would store this run in the compactStatus state.
func (cs *compactStatus) compareAndAdd(_ thisAndNextLevelRLocked, cd compactDef) bool {
cs.Lock()
defer cs.Unlock()
tl := cd.thisLevel.level
y.AssertTruef(tl < len(cs.levels), "Got level %d. Max levels: %d", tl, len(cs.levels))
thisLevel := cs.levels[cd.thisLevel.level]
nextLevel := cs.levels[cd.nextLevel.level]
if thisLevel.overlapsWith(cd.thisRange) {
return false
}
if nextLevel.overlapsWith(cd.nextRange) {
return false
}
// Check whether this level really needs compaction or not. Otherwise, we'll end up
// running parallel compactions for the same level.
// Update: We should not be checking size here. Compaction priority already did the size checks.
// Here we should just be executing the wish of others.
thisLevel.ranges = append(thisLevel.ranges, cd.thisRange)
nextLevel.ranges = append(nextLevel.ranges, cd.nextRange)
thisLevel.delSize += cd.thisSize
for _, t := range append(cd.top, cd.bot...) {
cs.tables[t.ID()] = struct{}{}
}
return true
}
func (cs *compactStatus) delete(cd compactDef) {
cs.Lock()
defer cs.Unlock()
tl := cd.thisLevel.level
y.AssertTruef(tl < len(cs.levels), "Got level %d. Max levels: %d", tl, len(cs.levels))
thisLevel := cs.levels[cd.thisLevel.level]
nextLevel := cs.levels[cd.nextLevel.level]
thisLevel.delSize -= cd.thisSize
found := thisLevel.remove(cd.thisRange)
// The following check makes sense only if we're compacting more than one
// table. In case of the max level, we might rewrite a single table to
// remove stale data.
if cd.thisLevel != cd.nextLevel && !cd.nextRange.isEmpty() {
found = nextLevel.remove(cd.nextRange) && found
}
if !found {
this := cd.thisRange
next := cd.nextRange
fmt.Printf("Looking for: %s in this level %d.\n", this, tl)
fmt.Printf("This Level:\n%s\n", thisLevel.debug())
fmt.Println()
fmt.Printf("Looking for: %s in next level %d.\n", next, cd.nextLevel.level)
fmt.Printf("Next Level:\n%s\n", nextLevel.debug())
log.Fatal("keyRange not found")
}
for _, t := range append(cd.top, cd.bot...) {
_, ok := cs.tables[t.ID()]
y.AssertTrue(ok)
delete(cs.tables, t.ID())
}
}
================================================
FILE: contrib/RELEASE.md
================================================
# Badger Release Process
This document outlines the steps needed to build and push a new release of Badger.
1. Have a team member "at-the-ready" with github `writer` access (you'll need them to approve PRs).
1. Create a new branch (prepare-for-release-vXX.X.X, for instance).
1. Update dependencies in `go.mod` for Ristretto, if required.
1. Update the CHANGELOG.md. Opus 4.5 does a great job of doing this. Example prompt:
`I'm releasing vXX.X.X off the main branch, add a new entry for this release. Conform to the`
`"Keep a Changelog" format, use past entries as a formatting guide. Run the trunk linter.`
1. Validate the version does not have storage incompatibilities with the previous version. If so,
add a warning to the CHANGELOG.md that export/import of data will need to be run as part of the
upgrade process.
1. Commit and push your changes. Create a PR and have a team member approve it.
1. Once your "prepare for release branch" is merged into main, on the github
[releases page](https://github.com/dgraph-io/badger/releases), create a new draft release.
1. Start the deployment workflow from the
[CD workflow page](https://github.com/dgraph-io/badger/actions/workflows/cd-badger.yml).
The CD workflow handles the building and copying of release artifacts to the releases area.
1. For all major and minor releases (non-patches), create a release branch. In order to easily
backport fixes to the release branch, create a release branch from the tag head. For instance, if
we're releasing v4.9.0, create a branch called `release/v4.9` from the tag head (ensure you're on
the main branch from which you created the tag):
```sh
git checkout main
git pull origin main
git checkout -b release/v4.9
git push origin release/v4.9
```
1. Splash the "go index" cache to ensure that the latest release is available to the public with:
```sh
go list -m github.com/dgraph-io/badger/v4@vX.X.X
```
1. If needed, create a new announcement thread in the
[Discussions](https://github.com/orgs/dgraph-io/discussions) forum for the release.
================================================
FILE: db.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"bytes"
"context"
"encoding/binary"
"errors"
"expvar"
"fmt"
"math"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
humanize "github.com/dustin/go-humanize"
"github.com/dgraph-io/badger/v4/fb"
"github.com/dgraph-io/badger/v4/options"
"github.com/dgraph-io/badger/v4/pb"
"github.com/dgraph-io/badger/v4/skl"
"github.com/dgraph-io/badger/v4/table"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2"
"github.com/dgraph-io/ristretto/v2/z"
)
var (
badgerPrefix = []byte("!badger!") // Prefix for internal keys used by badger.
txnKey = []byte("!badger!txn") // For indicating end of entries in txn.
bannedNsKey = []byte("!badger!banned") // For storing the banned namespaces.
)
type closers struct {
updateSize *z.Closer
compactors *z.Closer
memtable *z.Closer
writes *z.Closer
valueGC *z.Closer
pub *z.Closer
cacheHealth *z.Closer
}
type lockedKeys struct {
sync.RWMutex
keys map[uint64]struct{}
}
func (lk *lockedKeys) add(key uint64) {
lk.Lock()
defer lk.Unlock()
lk.keys[key] = struct{}{}
}
func (lk *lockedKeys) has(key uint64) bool {
lk.RLock()
defer lk.RUnlock()
_, ok := lk.keys[key]
return ok
}
func (lk *lockedKeys) all() []uint64 {
lk.RLock()
defer lk.RUnlock()
keys := make([]uint64, 0, len(lk.keys))
for key := range lk.keys {
keys = append(keys, key)
}
return keys
}
// DB provides the various functions required to interact with Badger.
// DB is thread-safe.
type DB struct {
testOnlyDBExtensions
lock sync.RWMutex // Guards list of inmemory tables, not individual reads and writes.
dirLockGuard *directoryLockGuard
// nil if Dir and ValueDir are the same
valueDirGuard *directoryLockGuard
closers closers
mt *memTable // Our latest (actively written) in-memory table
imm []*memTable // Add here only AFTER pushing to flushChan.
// Initialized via openMemTables.
nextMemFid int
opt Options
manifest *manifestFile
lc *levelsController
vlog valueLog
writeCh chan *request
flushChan chan *memTable // For flushing memtables.
closeOnce sync.Once // For closing DB only once.
blockWrites atomic.Int32
isClosed atomic.Uint32
orc *oracle
bannedNamespaces *lockedKeys
threshold *vlogThreshold
pub *publisher
registry *KeyRegistry
blockCache *ristretto.Cache[[]byte, *table.Block]
indexCache *ristretto.Cache[uint64, *fb.TableIndex]
allocPool *z.AllocatorPool
}
const (
kvWriteChCapacity = 1000
)
func checkAndSetOptions(opt *Options) error {
// It's okay to have zero compactors which will disable all compactions but
// we cannot have just one compactor otherwise we will end up with all data
// on level 2.
if opt.NumCompactors == 1 {
return errors.New("Cannot have 1 compactor. Need at least 2")
}
if opt.InMemory && (opt.Dir != "" || opt.ValueDir != "") {
return errors.New("Cannot use badger in Disk-less mode with Dir or ValueDir set")
}
opt.maxBatchSize = (15 * opt.MemTableSize) / 100
opt.maxBatchCount = opt.maxBatchSize / int64(skl.MaxNodeSize)
// This is the maximum value, vlogThreshold can have if dynamic thresholding is enabled.
opt.maxValueThreshold = math.Min(maxValueThreshold, float64(opt.maxBatchSize))
if opt.VLogPercentile < 0.0 || opt.VLogPercentile > 1.0 {
return errors.New("vlogPercentile must be within range of 0.0-1.0")
}
// We are limiting opt.ValueThreshold to maxValueThreshold for now.
if opt.ValueThreshold > maxValueThreshold {
return fmt.Errorf("Invalid ValueThreshold, must be less or equal to %d",
maxValueThreshold)
}
// If ValueThreshold is greater than opt.maxBatchSize, we won't be able to push any data using
// the transaction APIs. Transaction batches entries into batches of size opt.maxBatchSize.
if opt.ValueThreshold > opt.maxBatchSize {
return fmt.Errorf("Valuethreshold %d greater than max batch size of %d. Either "+
"reduce opt.ValueThreshold or increase opt.BaseTableSize.",
opt.ValueThreshold, opt.maxBatchSize)
}
// ValueLogFileSize should be strictly LESS than 2<<30 otherwise we will
// overflow the uint32 when we mmap it in OpenMemtable.
if !(opt.ValueLogFileSize < 2<<30 && opt.ValueLogFileSize >= 1<<20) {
return ErrValueLogSize
}
if opt.ReadOnly {
// Do not perform compaction in read only mode.
opt.CompactL0OnClose = false
}
needCache := (opt.Compression != options.None) || (len(opt.EncryptionKey) > 0)
if needCache && opt.BlockCacheSize == 0 {
panic("BlockCacheSize should be set since compression/encryption are enabled")
}
return nil
}
// Open returns a new DB object.
func Open(opt Options) (*DB, error) {
if err := checkAndSetOptions(&opt); err != nil {
return nil, err
}
var dirLockGuard, valueDirLockGuard *directoryLockGuard
// Create directories and acquire lock on it only if badger is not running in InMemory mode.
// We don't have any directories/files in InMemory mode so we don't need to acquire
// any locks on them.
if !opt.InMemory {
if err := createDirs(opt); err != nil {
return nil, err
}
var err error
if !opt.BypassLockGuard {
dirLockGuard, err = acquireDirectoryLock(opt.Dir, lockFile, opt.ReadOnly)
if err != nil {
return nil, err
}
defer func() {
if dirLockGuard != nil {
_ = dirLockGuard.release()
}
}()
absDir, err := filepath.Abs(opt.Dir)
if err != nil {
return nil, err
}
absValueDir, err := filepath.Abs(opt.ValueDir)
if err != nil {
return nil, err
}
if absValueDir != absDir {
valueDirLockGuard, err = acquireDirectoryLock(opt.ValueDir, lockFile, opt.ReadOnly)
if err != nil {
return nil, err
}
defer func() {
if valueDirLockGuard != nil {
_ = valueDirLockGuard.release()
}
}()
}
}
}
manifestFile, manifest, err := openOrCreateManifestFile(opt)
if err != nil {
return nil, err
}
defer func() {
if manifestFile != nil {
_ = manifestFile.close()
}
}()
db := &DB{
imm: make([]*memTable, 0, opt.NumMemtables),
flushChan: make(chan *memTable, opt.NumMemtables),
writeCh: make(chan *request, kvWriteChCapacity),
opt: opt,
manifest: manifestFile,
dirLockGuard: dirLockGuard,
valueDirGuard: valueDirLockGuard,
orc: newOracle(opt),
pub: newPublisher(),
allocPool: z.NewAllocatorPool(8),
bannedNamespaces: &lockedKeys{keys: make(map[uint64]struct{})},
threshold: initVlogThreshold(&opt),
}
db.syncChan = opt.syncChan
// Cleanup all the goroutines started by badger in case of an error.
defer func() {
if err != nil {
opt.Errorf("Received err: %v. Cleaning up...", err)
db.cleanup()
db = nil
}
}()
if opt.BlockCacheSize > 0 {
numInCache := opt.BlockCacheSize / int64(opt.BlockSize)
if numInCache == 0 {
// Make the value of this variable at least one since the cache requires
// the number of counters to be greater than zero.
numInCache = 1
}
config := ristretto.Config[[]byte, *table.Block]{
NumCounters: numInCache * 8,
MaxCost: opt.BlockCacheSize,
BufferItems: 64,
Metrics: true,
OnExit: table.BlockEvictHandler,
}
db.blockCache, err = ristretto.NewCache[[]byte, *table.Block](&config)
if err != nil {
return nil, y.Wrap(err, "failed to create data cache")
}
}
if opt.IndexCacheSize > 0 {
// Index size is around 5% of the table size.
indexSz := int64(float64(opt.MemTableSize) * 0.05)
numInCache := opt.IndexCacheSize / indexSz
if numInCache == 0 {
// Make the value of this variable at least one since the cache requires
// the number of counters to be greater than zero.
numInCache = 1
}
config := ristretto.Config[uint64, *fb.TableIndex]{
NumCounters: numInCache * 8,
MaxCost: opt.IndexCacheSize,
BufferItems: 64,
Metrics: true,
}
db.indexCache, err = ristretto.NewCache(&config)
if err != nil {
return nil, y.Wrap(err, "failed to create bf cache")
}
}
db.closers.cacheHealth = z.NewCloser(1)
go db.monitorCache(db.closers.cacheHealth)
if db.opt.InMemory {
db.opt.SyncWrites = false
// If badger is running in memory mode, push everything into the LSM Tree.
db.opt.ValueThreshold = math.MaxInt32
}
krOpt := KeyRegistryOptions{
ReadOnly: opt.ReadOnly,
Dir: opt.Dir,
EncryptionKey: opt.EncryptionKey,
EncryptionKeyRotationDuration: opt.EncryptionKeyRotationDuration,
InMemory: opt.InMemory,
}
if db.registry, err = OpenKeyRegistry(krOpt); err != nil {
return db, err
}
db.calculateSize()
db.closers.updateSize = z.NewCloser(1)
go db.updateSize(db.closers.updateSize)
if err := db.openMemTables(db.opt); err != nil {
return nil, y.Wrapf(err, "while opening memtables")
}
if !db.opt.ReadOnly {
if db.mt, err = db.newMemTable(); err != nil {
return nil, y.Wrapf(err, "cannot create memtable")
}
}
// newLevelsController potentially loads files in directory.
if db.lc, err = newLevelsController(db, &manifest); err != nil {
return db, err
}
// Initialize vlog struct.
db.vlog.init(db)
if !opt.ReadOnly {
db.closers.compactors = z.NewCloser(1)
db.lc.startCompact(db.closers.compactors)
db.closers.memtable = z.NewCloser(1)
go func() {
db.flushMemtable(db.closers.memtable) // Need levels controller to be up.
}()
// Flush them to disk asap.
for _, mt := range db.imm {
db.flushChan <- mt
}
}
// We do increment nextTxnTs below. So, no need to do it here.
db.orc.nextTxnTs = db.MaxVersion()
db.opt.Infof("Set nextTxnTs to %d", db.orc.nextTxnTs)
if err = db.vlog.open(db); err != nil {
return db, y.Wrapf(err, "During db.vlog.open")
}
// Let's advance nextTxnTs to one more than whatever we observed via
// replaying the logs.
db.orc.txnMark.Done(db.orc.nextTxnTs)
// In normal mode, we must update readMark so older versions of keys can be removed during
// compaction when run in offline mode via the flatten tool.
db.orc.readMark.Done(db.orc.nextTxnTs)
db.orc.incrementNextTs()
go db.threshold.listenForValueThresholdUpdate()
if err := db.initBannedNamespaces(); err != nil {
return db, fmt.Errorf("While setting banned keys: %w", err)
}
db.closers.writes = z.NewCloser(1)
go db.doWrites(db.closers.writes)
if !db.opt.InMemory {
db.closers.valueGC = z.NewCloser(1)
go db.vlog.waitOnGC(db.closers.valueGC)
}
db.closers.pub = z.NewCloser(1)
go db.pub.listenForUpdates(db.closers.pub)
valueDirLockGuard = nil
dirLockGuard = nil
manifestFile = nil
return db, nil
}
// initBannedNamespaces retrieves the banned namespaces from the DB and updates in-memory structure.
func (db *DB) initBannedNamespaces() error {
if db.opt.NamespaceOffset < 0 {
return nil
}
return db.View(func(txn *Txn) error {
iopts := DefaultIteratorOptions
iopts.Prefix = bannedNsKey
iopts.PrefetchValues = false
iopts.InternalAccess = true
itr := txn.NewIterator(iopts)
defer itr.Close()
for itr.Rewind(); itr.Valid(); itr.Next() {
key := y.BytesToU64(itr.Item().Key()[len(bannedNsKey):])
db.bannedNamespaces.add(key)
}
return nil
})
}
func (db *DB) MaxVersion() uint64 {
var maxVersion uint64
update := func(a uint64) {
if a > maxVersion {
maxVersion = a
}
}
db.lock.Lock()
// In read only mode, we do not create new mem table.
if !db.opt.ReadOnly {
update(db.mt.maxVersion)
}
for _, mt := range db.imm {
update(mt.maxVersion)
}
db.lock.Unlock()
for _, ti := range db.Tables() {
update(ti.MaxVersion)
}
return maxVersion
}
func (db *DB) monitorCache(c *z.Closer) {
defer c.Done()
count := 0
analyze := func(name string, metrics *ristretto.Metrics) {
// If the mean life expectancy is less than 10 seconds, the cache
// might be too small.
le := metrics.LifeExpectancySeconds()
if le == nil {
return
}
lifeTooShort := le.Count > 0 && float64(le.Sum)/float64(le.Count) < 10
hitRatioTooLow := metrics.Ratio() > 0 && metrics.Ratio() < 0.4
if lifeTooShort && hitRatioTooLow {
db.opt.Warningf("%s might be too small. Metrics: %s\n", name, metrics)
db.opt.Warningf("Cache life expectancy (in seconds): %+v\n", le)
} else if le.Count > 1000 && count%5 == 0 {
db.opt.Infof("%s metrics: %s\n", name, metrics)
}
}
ticker := time.NewTicker(1 * time.Minute)
defer ticker.Stop()
for {
select {
case <-c.HasBeenClosed():
return
case <-ticker.C:
}
analyze("Block cache", db.BlockCacheMetrics())
analyze("Index cache", db.IndexCacheMetrics())
count++
}
}
// cleanup stops all the goroutines started by badger. This is used in open to
// cleanup goroutines in case of an error.
func (db *DB) cleanup() {
db.stopMemoryFlush()
db.stopCompactions()
db.blockCache.Close()
db.indexCache.Close()
if db.closers.updateSize != nil {
db.closers.updateSize.Signal()
}
if db.closers.valueGC != nil {
db.closers.valueGC.Signal()
}
if db.closers.writes != nil {
db.closers.writes.Signal()
}
if db.closers.pub != nil {
db.closers.pub.Signal()
}
db.orc.Stop()
// Do not use vlog.Close() here. vlog.Close truncates the files. We don't
// want to truncate files unless the user has specified the truncate flag.
}
// BlockCacheMetrics returns the metrics for the underlying block cache.
func (db *DB) BlockCacheMetrics() *ristretto.Metrics {
if db.blockCache != nil {
return db.blockCache.Metrics
}
return nil
}
// IndexCacheMetrics returns the metrics for the underlying index cache.
func (db *DB) IndexCacheMetrics() *ristretto.Metrics {
if db.indexCache != nil {
return db.indexCache.Metrics
}
return nil
}
// Close closes a DB. It's crucial to call it to ensure all the pending updates make their way to
// disk. Calling DB.Close() multiple times would still only close the DB once.
func (db *DB) Close() error {
var err error
db.closeOnce.Do(func() {
err = db.close()
})
return err
}
// IsClosed denotes if the badger DB is closed or not. A DB instance should not
// be used after closing it.
func (db *DB) IsClosed() bool {
return db.isClosed.Load() == 1
}
func (db *DB) close() (err error) {
defer db.allocPool.Release()
db.opt.Debugf("Closing database")
db.opt.Infof("Lifetime L0 stalled for: %s\n", time.Duration(db.lc.l0stallsMs.Load()))
db.blockWrites.Store(1)
db.isClosed.Store(1)
if !db.opt.InMemory {
// Stop value GC first.
db.closers.valueGC.SignalAndWait()
}
// Stop writes next.
db.closers.writes.SignalAndWait()
// Don't accept any more write.
close(db.writeCh)
db.closers.pub.SignalAndWait()
db.closers.cacheHealth.Signal()
// Make sure that block writer is done pushing stuff into memtable!
// Otherwise, you will have a race condition: we are trying to flush memtables
// and remove them completely, while the block / memtable writer is still
// trying to push stuff into the memtable. This will also resolve the value
// offset problem: as we push into memtable, we update value offsets there.
if db.mt != nil {
if db.mt.sl.Empty() {
// Remove the memtable if empty.
db.mt.DecrRef()
} else {
db.opt.Debugf("Flushing memtable")
for {
pushedMemTable := func() bool {
db.lock.Lock()
defer db.lock.Unlock()
y.AssertTrue(db.mt != nil)
select {
case db.flushChan <- db.mt:
db.imm = append(db.imm, db.mt) // Flusher will attempt to remove this from s.imm.
db.mt = nil // Will segfault if we try writing!
db.opt.Debugf("pushed to flush chan\n")
return true
default:
// If we fail to push, we need to unlock and wait for a short while.
// The flushing operation needs to update s.imm. Otherwise, we have a
// deadlock.
// TODO: Think about how to do this more cleanly, maybe without any locks.
}
return false
}()
if pushedMemTable {
break
}
time.Sleep(10 * time.Millisecond)
}
}
}
db.stopMemoryFlush()
db.stopCompactions()
// Force Compact L0
// We don't need to care about cstatus since no parallel compaction is running.
if db.opt.CompactL0OnClose {
err := db.lc.doCompact(173, compactionPriority{level: 0, score: 1.73})
switch err {
case errFillTables:
// This error only means that there might be enough tables to do a compaction. So, we
// should not report it to the end user to avoid confusing them.
case nil:
db.opt.Debugf("Force compaction on level 0 done")
default:
db.opt.Warningf("While forcing compaction on level 0: %v", err)
}
}
// Now close the value log.
if vlogErr := db.vlog.Close(); vlogErr != nil {
err = y.Wrap(vlogErr, "DB.Close")
}
db.opt.Infof(db.LevelsToString())
if lcErr := db.lc.close(); err == nil {
err = y.Wrap(lcErr, "DB.Close")
}
db.opt.Debugf("Waiting for closer")
db.closers.updateSize.SignalAndWait()
db.orc.Stop()
db.blockCache.Close()
db.indexCache.Close()
db.threshold.close()
if db.opt.InMemory {
return
}
if db.dirLockGuard != nil {
if guardErr := db.dirLockGuard.release(); err == nil {
err = y.Wrap(guardErr, "DB.Close")
}
}
if db.valueDirGuard != nil {
if guardErr := db.valueDirGuard.release(); err == nil {
err = y.Wrap(guardErr, "DB.Close")
}
}
if manifestErr := db.manifest.close(); err == nil {
err = y.Wrap(manifestErr, "DB.Close")
}
if registryErr := db.registry.Close(); err == nil {
err = y.Wrap(registryErr, "DB.Close")
}
// Fsync directories to ensure that lock file, and any other removed files whose directory
// we haven't specifically fsynced, are guaranteed to have their directory entry removal
// persisted to disk.
if syncErr := db.syncDir(db.opt.Dir); err == nil {
err = y.Wrap(syncErr, "DB.Close")
}
if syncErr := db.syncDir(db.opt.ValueDir); err == nil {
err = y.Wrap(syncErr, "DB.Close")
}
return err
}
// VerifyChecksum verifies checksum for all tables on all levels.
// This method can be used to verify checksum, if opt.ChecksumVerificationMode is NoVerification.
func (db *DB) VerifyChecksum() error {
return db.lc.verifyChecksum()
}
const (
lockFile = "LOCK"
)
// Sync syncs database content to disk. This function provides
// more control to user to sync data whenever required.
func (db *DB) Sync() error {
/**
Make an attempt to sync both the logs, the active memtable's WAL and the vLog (1847).
Cases:
- All_ok :: If both the logs sync successfully.
- Entry_Lost :: If an entry with a value pointer was present in the active memtable's WAL,
:: and the WAL was synced but there was an error in syncing the vLog.
:: The entry will be considered lost and this case will need to be handled during recovery.
- Entries_Lost :: If there were errors in syncing both the logs, multiple entries would be lost.
- Entries_Lost :: If the active memtable's WAL is not synced but the vLog is synced, it will
:: result in entries being lost because recovery of the active memtable is done from its WAL.
:: Check `UpdateSkipList` in memtable.go.
- Nothing_lost :: If an entry with its value was present in the active memtable's WAL, and the WAL was synced,
:: but there was an error in syncing the vLog.
:: Nothing is lost for this very specific entry because the entry is completely present in the memtable's WAL.
- Partially_lost :: If entries were written partially in either of the logs,
:: the logs will be truncated during recovery.
:: As a result of truncation, some entries might be lost.
:: Assume that 4KB of data is to be synced and invoking `Sync` results only in syncing 3KB
:: of data and then the machine shuts down or the disk failure happens,
:: this will result in partial writes. [[This case needs verification]]
*/
db.lock.RLock()
memtableSyncError := db.mt.SyncWAL()
db.lock.RUnlock()
vLogSyncError := db.vlog.sync()
return y.CombineErrors(memtableSyncError, vLogSyncError)
}
// getMemtables returns the current memtables and get references.
func (db *DB) getMemTables() ([]*memTable, func()) {
db.lock.RLock()
defer db.lock.RUnlock()
var tables []*memTable
// Mutable memtable does not exist in read-only mode.
if !db.opt.ReadOnly {
// Get mutable memtable.
tables = append(tables, db.mt)
db.mt.IncrRef()
}
// Get immutable memtables.
last := len(db.imm) - 1
for i := range db.imm {
tables = append(tables, db.imm[last-i])
db.imm[last-i].IncrRef()
}
return tables, func() {
for _, tbl := range tables {
tbl.DecrRef()
}
}
}
// get returns the value in memtable or disk for given key.
// Note that value will include meta byte.
//
// IMPORTANT: We should never write an entry with an older timestamp for the same key, We need to
// maintain this invariant to search for the latest value of a key, or else we need to search in all
// tables and find the max version among them. To maintain this invariant, we also need to ensure
// that all versions of a key are always present in the same table from level 1, because compaction
// can push any table down.
//
// Update(23/09/2020) - We have dropped the move key implementation. Earlier we
// were inserting move keys to fix the invalid value pointers but we no longer
// do that. For every get("fooX") call where X is the version, we will search
// for "fooX" in all the levels of the LSM tree. This is expensive but it
// removes the overhead of handling move keys completely.
func (db *DB) get(key []byte) (y.ValueStruct, error) {
if db.IsClosed() {
return y.ValueStruct{}, ErrDBClosed
}
tables, decr := db.getMemTables() // Lock should be released.
defer decr()
var maxVs y.ValueStruct
version := y.ParseTs(key)
y.NumGetsAdd(db.opt.MetricsEnabled, 1)
for i := 0; i < len(tables); i++ {
vs := tables[i].sl.Get(key)
y.NumMemtableGetsAdd(db.opt.MetricsEnabled, 1)
if vs.Meta == 0 && vs.Value == nil {
continue
}
// Found the required version of the key, return immediately.
if vs.Version == version {
y.NumGetsWithResultsAdd(db.opt.MetricsEnabled, 1)
return vs, nil
}
if maxVs.Version < vs.Version {
maxVs = vs
}
}
return db.lc.get(key, maxVs, 0)
}
var requestPool = sync.Pool{
New: func() interface{} {
return new(request)
},
}
func (db *DB) writeToLSM(b *request) error {
// We should check the length of b.Prts and b.Entries only when badger is not
// running in InMemory mode. In InMemory mode, we don't write anything to the
// value log and that's why the length of b.Ptrs will always be zero.
if !db.opt.InMemory && len(b.Ptrs) != len(b.Entries) {
return fmt.Errorf("Ptrs and Entries don't match: %+v", b)
}
for i, entry := range b.Entries {
var err error
if entry.skipVlogAndSetThreshold(db.valueThreshold()) {
// Will include deletion / tombstone case.
err = db.mt.Put(entry.Key,
y.ValueStruct{
Value: entry.Value,
// Ensure value pointer flag is removed. Otherwise, the value will fail
// to be retrieved during iterator prefetch. `bitValuePointer` is only
// known to be set in write to LSM when the entry is loaded from a backup
// with lower ValueThreshold and its value was stored in the value log.
Meta: entry.meta &^ bitValuePointer,
UserMeta: entry.UserMeta,
ExpiresAt: entry.ExpiresAt,
})
} else {
// Write pointer to Memtable.
err = db.mt.Put(entry.Key,
y.ValueStruct{
Value: b.Ptrs[i].Encode(),
Meta: entry.meta | bitValuePointer,
UserMeta: entry.UserMeta,
ExpiresAt: entry.ExpiresAt,
})
}
if err != nil {
return y.Wrapf(err, "while writing to memTable")
}
}
if db.opt.SyncWrites {
return db.mt.SyncWAL()
}
return nil
}
// writeRequests is called serially by only one goroutine.
func (db *DB) writeRequests(reqs []*request) error {
if len(reqs) == 0 {
return nil
}
done := func(err error) {
for _, r := range reqs {
r.Err = err
r.Wg.Done()
}
}
db.opt.Debugf("writeRequests called. Writing to value log")
err := db.vlog.write(reqs)
if err != nil {
done(err)
return err
}
db.opt.Debugf("Writing to memtable")
var count int
for _, b := range reqs {
if len(b.Entries) == 0 {
continue
}
count += len(b.Entries)
var i uint64
var err error
for err = db.ensureRoomForWrite(); err == errNoRoom; err = db.ensureRoomForWrite() {
i++
if i%100 == 0 {
db.opt.Debugf("Making room for writes")
}
// We need to poll a bit because both hasRoomForWrite and the flusher need access to s.imm.
// When flushChan is full and you are blocked there, and the flusher is trying to update s.imm,
// you will get a deadlock.
time.Sleep(10 * time.Millisecond)
}
if err != nil {
done(err)
return y.Wrap(err, "writeRequests")
}
if err := db.writeToLSM(b); err != nil {
done(err)
return y.Wrap(err, "writeRequests")
}
}
db.opt.Debugf("Sending updates to subscribers")
db.pub.sendUpdates(reqs)
done(nil)
db.opt.Debugf("%d entries written", count)
return nil
}
func (db *DB) sendToWriteCh(entries []*Entry) (*request, error) {
if db.blockWrites.Load() == 1 {
return nil, ErrBlockedWrites
}
var count, size int64
for _, e := range entries {
size += e.estimateSizeAndSetThreshold(db.valueThreshold())
count++
}
y.NumBytesWrittenUserAdd(db.opt.MetricsEnabled, size)
if count >= db.opt.maxBatchCount || size >= db.opt.maxBatchSize {
return nil, ErrTxnTooBig
}
// We can only service one request because we need each txn to be stored in a contiguous section.
// Txns should not interleave among other txns or rewrites.
req := requestPool.Get().(*request)
req.reset()
req.Entries = entries
req.Wg.Add(1)
req.IncrRef() // for db write
db.writeCh <- req // Handled in doWrites.
y.NumPutsAdd(db.opt.MetricsEnabled, int64(len(entries)))
return req, nil
}
func (db *DB) doWrites(lc *z.Closer) {
defer lc.Done()
pendingCh := make(chan struct{}, 1)
writeRequests := func(reqs []*request) {
if err := db.writeRequests(reqs); err != nil {
db.opt.Errorf("writeRequests: %v", err)
}
<-pendingCh
}
// This variable tracks the number of pending writes.
reqLen := new(expvar.Int)
y.PendingWritesSet(db.opt.MetricsEnabled, db.opt.Dir, reqLen)
reqs := make([]*request, 0, 10)
for {
var r *request
select {
case r = <-db.writeCh:
case <-lc.HasBeenClosed():
goto closedCase
}
for {
reqs = append(reqs, r)
reqLen.Set(int64(len(reqs)))
if len(reqs) >= 3*kvWriteChCapacity {
pendingCh <- struct{}{} // blocking.
goto writeCase
}
select {
// Either push to pending, or continue to pick from writeCh.
case r = <-db.writeCh:
case pendingCh <- struct{}{}:
goto writeCase
case <-lc.HasBeenClosed():
goto closedCase
}
}
closedCase:
// All the pending request are drained.
// Don't close the writeCh, because it has be used in several places.
for {
select {
case r = <-db.writeCh:
reqs = append(reqs, r)
default:
pendingCh <- struct{}{} // Push to pending before doing a write.
writeRequests(reqs)
return
}
}
writeCase:
go writeRequests(reqs)
reqs = make([]*request, 0, 10)
reqLen.Set(0)
}
}
// batchSet applies a list of badger.Entry. If a request level error occurs it
// will be returned.
//
// Check(kv.BatchSet(entries))
func (db *DB) batchSet(entries []*Entry) error {
req, err := db.sendToWriteCh(entries)
if err != nil {
return err
}
return req.Wait()
}
// batchSetAsync is the asynchronous version of batchSet. It accepts a callback
// function which is called when all the sets are complete. If a request level
// error occurs, it will be passed back via the callback.
//
// err := kv.BatchSetAsync(entries, func(err error)) {
// Check(err)
// }
func (db *DB) batchSetAsync(entries []*Entry, f func(error)) error {
req, err := db.sendToWriteCh(entries)
if err != nil {
return err
}
go func() {
err := req.Wait()
// Write is complete. Let's call the callback function now.
f(err)
}()
return nil
}
var errNoRoom = errors.New("No room for write")
// ensureRoomForWrite is always called serially.
func (db *DB) ensureRoomForWrite() error {
var err error
db.lock.Lock()
defer db.lock.Unlock()
y.AssertTrue(db.mt != nil) // A nil mt indicates that DB is being closed.
if !db.mt.isFull() {
return nil
}
select {
case db.flushChan <- db.mt:
db.opt.Debugf("Flushing memtable, mt.size=%d size of flushChan: %d\n",
db.mt.sl.MemSize(), len(db.flushChan))
// We manage to push this task. Let's modify imm.
db.imm = append(db.imm, db.mt)
db.mt, err = db.newMemTable()
if err != nil {
return y.Wrapf(err, "cannot create new mem table")
}
// New memtable is empty. We certainly have room.
return nil
default:
// We need to do this to unlock and allow the flusher to modify imm.
return errNoRoom
}
}
func arenaSize(opt Options) int64 {
return opt.MemTableSize + opt.maxBatchSize + opt.maxBatchCount*int64(skl.MaxNodeSize)
}
// buildL0Table builds a new table from the memtable.
func buildL0Table(iter y.Iterator, dropPrefixes [][]byte, bopts table.Options) *table.Builder {
defer iter.Close()
b := table.NewTableBuilder(bopts)
for iter.Rewind(); iter.Valid(); iter.Next() {
if len(dropPrefixes) > 0 && hasAnyPrefixes(iter.Key(), dropPrefixes) {
continue
}
vs := iter.Value()
var vp valuePointer
if vs.Meta&bitValuePointer > 0 {
vp.Decode(vs.Value)
}
b.Add(iter.Key(), iter.Value(), vp.Len)
}
return b
}
// handleMemTableFlush must be run serially.
func (db *DB) handleMemTableFlush(mt *memTable, dropPrefixes [][]byte) error {
bopts := buildTableOptions(db)
itr := mt.sl.NewUniIterator(false)
builder := buildL0Table(itr, nil, bopts)
defer builder.Close()
// buildL0Table can return nil if the none of the items in the skiplist are
// added to the builder. This can happen when drop prefix is set and all
// the items are skipped.
if builder.Empty() {
builder.Finish()
return nil
}
fileID := db.lc.reserveFileID()
var tbl *table.Table
var err error
if db.opt.InMemory {
data := builder.Finish()
tbl, err = table.OpenInMemoryTable(data, fileID, &bopts)
} else {
tbl, err = table.CreateTable(table.NewFilename(fileID, db.opt.Dir), builder)
}
if err != nil {
return y.Wrap(err, "error while creating table")
}
// We own a ref on tbl.
err = db.lc.addLevel0Table(tbl) // This will incrRef
_ = tbl.DecrRef() // Releases our ref.
return err
}
// flushMemtable must keep running until we send it an empty memtable. If there
// are errors during handling the memtable flush, we'll retry indefinitely.
func (db *DB) flushMemtable(lc *z.Closer) {
defer lc.Done()
for mt := range db.flushChan {
if mt == nil {
continue
}
for {
if err := db.handleMemTableFlush(mt, nil); err != nil {
// Encountered error. Retry indefinitely.
db.opt.Errorf("error flushing memtable to disk: %v, retrying", err)
time.Sleep(time.Second)
continue
}
// Update s.imm. Need a lock.
db.lock.Lock()
// This is a single-threaded operation. mt corresponds to the head of
// db.imm list. Once we flush it, we advance db.imm. The next mt
// which would arrive here would match db.imm[0], because we acquire a
// lock over DB when pushing to flushChan.
// TODO: This logic is dirty AF. Any change and this could easily break.
y.AssertTrue(mt == db.imm[0])
db.imm = db.imm[1:]
mt.DecrRef() // Return memory.
// unlock
db.lock.Unlock()
break
}
}
}
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return true, err
}
// This function does a filewalk, calculates the size of vlog and sst files and stores it in
// y.LSMSize and y.VlogSize.
func (db *DB) calculateSize() {
if db.opt.InMemory {
return
}
newInt := func(val int64) *expvar.Int {
v := new(expvar.Int)
v.Add(val)
return v
}
totalSize := func(dir string) (int64, int64) {
var lsmSize, vlogSize int64
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
ext := filepath.Ext(path)
switch ext {
case ".sst":
lsmSize += info.Size()
case ".vlog":
vlogSize += info.Size()
}
return nil
})
if err != nil {
db.opt.Debugf("Got error while calculating total size of directory: %s", dir)
}
return lsmSize, vlogSize
}
lsmSize, vlogSize := totalSize(db.opt.Dir)
y.LSMSizeSet(db.opt.MetricsEnabled, db.opt.Dir, newInt(lsmSize))
// If valueDir is different from dir, we'd have to do another walk.
if db.opt.ValueDir != db.opt.Dir {
_, vlogSize = totalSize(db.opt.ValueDir)
}
y.VlogSizeSet(db.opt.MetricsEnabled, db.opt.ValueDir, newInt(vlogSize))
}
func (db *DB) updateSize(lc *z.Closer) {
defer lc.Done()
if db.opt.InMemory {
return
}
metricsTicker := time.NewTicker(time.Minute)
defer metricsTicker.Stop()
for {
select {
case <-metricsTicker.C:
db.calculateSize()
case <-lc.HasBeenClosed():
return
}
}
}
// RunValueLogGC triggers a value log garbage collection.
//
// It picks value log files to perform GC based on statistics that are collected
// during compactions. If no such statistics are available, then log files are
// picked in random order. The process stops as soon as the first log file is
// encountered which does not result in garbage collection.
//
// When a log file is picked, it is first sampled. If the sample shows that we
// can discard at least discardRatio space of that file, it would be rewritten.
//
// If a call to RunValueLogGC results in no rewrites, then an ErrNoRewrite is
// thrown indicating that the call resulted in no file rewrites.
//
// We recommend setting discardRatio to 0.5, thus indicating that a file be
// rewritten if half the space can be discarded. This results in a lifetime
// value log write amplification of 2 (1 from original write + 0.5 rewrite +
// 0.25 + 0.125 + ... = 2). Setting it to higher value would result in fewer
// space reclaims, while setting it to a lower value would result in more space
// reclaims at the cost of increased activity on the LSM tree. discardRatio
// must be in the range (0.0, 1.0), both endpoints excluded, otherwise an
// ErrInvalidRequest is returned.
//
// Only one GC is allowed at a time. If another value log GC is running, or DB
// has been closed, this would return an ErrRejected.
//
// Note: Every time GC is run, it would produce a spike of activity on the LSM
// tree.
func (db *DB) RunValueLogGC(discardRatio float64) error {
if db.opt.InMemory {
return ErrGCInMemoryMode
}
if discardRatio >= 1.0 || discardRatio <= 0.0 {
return ErrInvalidRequest
}
// Pick a log file and run GC
return db.vlog.runGC(discardRatio)
}
// Size returns the size of lsm and value log files in bytes. It can be used to decide how often to
// call RunValueLogGC.
func (db *DB) Size() (lsm, vlog int64) {
if y.LSMSizeGet(db.opt.MetricsEnabled, db.opt.Dir) == nil {
lsm, vlog = 0, 0
return
}
lsm = y.LSMSizeGet(db.opt.MetricsEnabled, db.opt.Dir).(*expvar.Int).Value()
vlog = y.VlogSizeGet(db.opt.MetricsEnabled, db.opt.ValueDir).(*expvar.Int).Value()
return
}
// Sequence represents a Badger sequence.
type Sequence struct {
lock sync.Mutex
db *DB
key []byte
next uint64
leased uint64
bandwidth uint64
}
// Next would return the next integer in the sequence, updating the lease by running a transaction
// if needed.
func (seq *Sequence) Next() (uint64, error) {
seq.lock.Lock()
defer seq.lock.Unlock()
if seq.next >= seq.leased {
if err := seq.updateLease(); err != nil {
return 0, err
}
}
val := seq.next
seq.next++
return val, nil
}
// Release the leased sequence to avoid wasted integers. This should be done right
// before closing the associated DB. However it is valid to use the sequence after
// it was released, causing a new lease with full bandwidth.
func (seq *Sequence) Release() error {
seq.lock.Lock()
defer seq.lock.Unlock()
err := seq.db.Update(func(txn *Txn) error {
item, err := txn.Get(seq.key)
if err != nil {
return err
}
var num uint64
if err := item.Value(func(v []byte) error {
num = binary.BigEndian.Uint64(v)
return nil
}); err != nil {
return err
}
if num == seq.leased {
var buf [8]byte
binary.BigEndian.PutUint64(buf[:], seq.next)
return txn.SetEntry(NewEntry(seq.key, buf[:]))
}
return nil
})
if err != nil {
return err
}
seq.leased = seq.next
return nil
}
func (seq *Sequence) updateLease() error {
return seq.db.Update(func(txn *Txn) error {
item, err := txn.Get(seq.key)
switch {
case err == ErrKeyNotFound:
seq.next = 0
case err != nil:
return err
default:
var num uint64
if err := item.Value(func(v []byte) error {
num = binary.BigEndian.Uint64(v)
return nil
}); err != nil {
return err
}
seq.next = num
}
lease := seq.next + seq.bandwidth
var buf [8]byte
binary.BigEndian.PutUint64(buf[:], lease)
if err = txn.SetEntry(NewEntry(seq.key, buf[:])); err != nil {
return err
}
seq.leased = lease
return nil
})
}
// GetSequence would initiate a new sequence object, generating it from the stored lease, if
// available, in the database. Sequence can be used to get a list of monotonically increasing
// integers. Multiple sequences can be created by providing different keys. Bandwidth sets the
// size of the lease, determining how many Next() requests can be served from memory.
//
// GetSequence is not supported on ManagedDB. Calling this would result in a panic.
func (db *DB) GetSequence(key []byte, bandwidth uint64) (*Sequence, error) {
if db.opt.managedTxns {
panic("Cannot use GetSequence with managedDB=true.")
}
switch {
case len(key) == 0:
return nil, ErrEmptyKey
case bandwidth == 0:
return nil, ErrZeroBandwidth
}
seq := &Sequence{
db: db,
key: key,
next: 0,
leased: 0,
bandwidth: bandwidth,
}
err := seq.updateLease()
return seq, err
}
// Tables gets the TableInfo objects from the level controller. If withKeysCount
// is true, TableInfo objects also contain counts of keys for the tables.
func (db *DB) Tables() []TableInfo {
return db.lc.getTableInfo()
}
// Levels gets the LevelInfo.
func (db *DB) Levels() []LevelInfo {
return db.lc.getLevelInfo()
}
// EstimateSize can be used to get rough estimate of data size for a given prefix.
func (db *DB) EstimateSize(prefix []byte) (uint64, uint64) {
var onDiskSize, uncompressedSize uint64
tables := db.Tables()
for _, ti := range tables {
if bytes.HasPrefix(ti.Left, prefix) && bytes.HasPrefix(ti.Right, prefix) {
onDiskSize += uint64(ti.OnDiskSize)
uncompressedSize += uint64(ti.UncompressedSize)
}
}
return onDiskSize, uncompressedSize
}
// Ranges can be used to get rough key ranges to divide up iteration over the DB. The ranges here
// would consider the prefix, but would not necessarily start or end with the prefix. In fact, the
// first range would have nil as left key, and the last range would have nil as the right key.
func (db *DB) Ranges(prefix []byte, numRanges int) []*keyRange {
var splits []string
tables := db.Tables()
// We just want table ranges here and not keys count.
for _, ti := range tables {
// We don't use ti.Left, because that has a tendency to store !badger keys. Skip over tables
// at upper levels. Only choose tables from the last level.
if ti.Level != db.opt.MaxLevels-1 {
continue
}
if bytes.HasPrefix(ti.Right, prefix) {
splits = append(splits, string(ti.Right))
}
}
// If the number of splits is low, look at the offsets inside the
// tables to generate more splits.
if len(splits) < 32 {
numTables := len(tables)
if numTables == 0 {
numTables = 1
}
numPerTable := 32 / numTables
if numPerTable == 0 {
numPerTable = 1
}
splits = db.lc.keySplits(numPerTable, prefix)
}
// If the number of splits is still < 32, then look at the memtables.
if len(splits) < 32 {
maxPerSplit := 10000
mtSplits := func(mt *memTable) {
if mt == nil {
return
}
count := 0
iter := mt.sl.NewIterator()
for iter.SeekToFirst(); iter.Valid(); iter.Next() {
if count%maxPerSplit == 0 {
// Add a split every maxPerSplit keys.
if bytes.HasPrefix(iter.Key(), prefix) {
splits = append(splits, string(iter.Key()))
}
}
count += 1
}
_ = iter.Close()
}
db.lock.Lock()
defer db.lock.Unlock()
var memTables []*memTable
memTables = append(memTables, db.imm...)
for _, mt := range memTables {
mtSplits(mt)
}
mtSplits(db.mt)
}
// We have our splits now. Let's convert them to ranges.
sort.Strings(splits)
var ranges []*keyRange
var start []byte
for _, key := range splits {
ranges = append(ranges, &keyRange{left: start, right: y.SafeCopy(nil, []byte(key))})
start = y.SafeCopy(nil, []byte(key))
}
ranges = append(ranges, &keyRange{left: start})
// Figure out the approximate table size this range has to deal with.
for _, t := range tables {
tr := keyRange{left: t.Left, right: t.Right}
for _, r := range ranges {
if len(r.left) == 0 || len(r.right) == 0 {
continue
}
if r.overlapsWith(tr) {
r.size += int64(t.UncompressedSize)
}
}
}
var total int64
for _, r := range ranges {
total += r.size
}
if total == 0 {
return ranges
}
// Figure out the average size, so we know how to bin the ranges together.
avg := total / int64(numRanges)
var out []*keyRange
var i int
for i < len(ranges) {
r := ranges[i]
cur := &keyRange{left: r.left, size: r.size, right: r.right}
i++
for ; i < len(ranges); i++ {
next := ranges[i]
if cur.size+next.size > avg {
break
}
cur.right = next.right
cur.size += next.size
}
out = append(out, cur)
}
return out
}
// MaxBatchCount returns max possible entries in batch
func (db *DB) MaxBatchCount() int64 {
return db.opt.maxBatchCount
}
// MaxBatchSize returns max possible batch size
func (db *DB) MaxBatchSize() int64 {
return db.opt.maxBatchSize
}
func (db *DB) stopMemoryFlush() {
// Stop memtable flushes.
if db.closers.memtable != nil {
close(db.flushChan)
db.closers.memtable.SignalAndWait()
}
}
func (db *DB) stopCompactions() {
// Stop compactions.
if db.closers.compactors != nil {
db.closers.compactors.SignalAndWait()
}
}
func (db *DB) startCompactions() {
// Resume compactions.
if db.closers.compactors != nil {
db.closers.compactors = z.NewCloser(1)
db.lc.startCompact(db.closers.compactors)
}
}
func (db *DB) startMemoryFlush() {
// Start memory fluhser.
if db.closers.memtable != nil {
db.flushChan = make(chan *memTable, db.opt.NumMemtables)
db.closers.memtable = z.NewCloser(1)
go func() {
db.flushMemtable(db.closers.memtable)
}()
}
}
// Flatten can be used to force compactions on the LSM tree so all the tables fall on the same
// level. This ensures that all the versions of keys are colocated and not split across multiple
// levels, which is necessary after a restore from backup. During Flatten, live compactions are
// stopped. Ideally, no writes are going on during Flatten. Otherwise, it would create competition
// between flattening the tree and new tables being created at level zero.
func (db *DB) Flatten(workers int) error {
db.stopCompactions()
defer db.startCompactions()
compactAway := func(cp compactionPriority) error {
db.opt.Infof("Attempting to compact with %+v\n", cp)
errCh := make(chan error, 1)
for i := 0; i < workers; i++ {
go func() {
errCh <- db.lc.doCompact(175, cp)
}()
}
var success int
var rerr error
for i := 0; i < workers; i++ {
err := <-errCh
if err != nil {
rerr = err
db.opt.Warningf("While running doCompact with %+v. Error: %v\n", cp, err)
} else {
success++
}
}
if success == 0 {
return rerr
}
// We could do at least one successful compaction. So, we'll consider this a success.
db.opt.Infof("%d compactor(s) succeeded. One or more tables from level %d compacted.\n",
success, cp.level)
return nil
}
hbytes := func(sz int64) string {
return humanize.IBytes(uint64(sz))
}
t := db.lc.levelTargets()
for {
db.opt.Infof("\n")
var levels []int
for i, l := range db.lc.levels {
sz := l.getTotalSize()
db.opt.Infof("Level: %d. %8s Size. %8s Max.\n",
i, hbytes(l.getTotalSize()), hbytes(t.targetSz[i]))
if sz > 0 {
levels = append(levels, i)
}
}
if len(levels) <= 1 {
prios := db.lc.pickCompactLevels(nil)
if len(prios) == 0 || prios[0].score <= 1.0 {
db.opt.Infof("All tables consolidated into one level. Flattening done.\n")
return nil
}
if err := compactAway(prios[0]); err != nil {
return err
}
continue
}
// Create an artificial compaction priority, to ensure that we compact the level.
cp := compactionPriority{level: levels[0], score: 1.71}
if err := compactAway(cp); err != nil {
return err
}
}
}
func (db *DB) blockWrite() error {
// Stop accepting new writes.
if !db.blockWrites.CompareAndSwap(0, 1) {
return ErrBlockedWrites
}
// Make all pending writes finish. The following will also close writeCh.
db.closers.writes.SignalAndWait()
db.opt.Infof("Writes flushed. Stopping compactions now...")
return nil
}
func (db *DB) unblockWrite() {
db.closers.writes = z.NewCloser(1)
go db.doWrites(db.closers.writes)
// Resume writes.
db.blockWrites.Store(0)
}
func (db *DB) prepareToDrop() (func(), error) {
if db.opt.ReadOnly {
panic("Attempting to drop data in read-only mode.")
}
// In order prepare for drop, we need to block the incoming writes and
// write it to db. Then, flush all the pending memtable. So that, we
// don't miss any entries.
if err := db.blockWrite(); err != nil {
return func() {}, err
}
reqs := make([]*request, 0, 10)
for {
select {
case r := <-db.writeCh:
reqs = append(reqs, r)
default:
if err := db.writeRequests(reqs); err != nil {
db.opt.Errorf("writeRequests: %v", err)
}
db.stopMemoryFlush()
return func() {
db.opt.Infof("Resuming writes")
db.startMemoryFlush()
db.unblockWrite()
}, nil
}
}
}
// DropAll would drop all the data stored in Badger. It does this in the following way.
// - Stop accepting new writes.
// - Pause memtable flushes and compactions.
// - Pick all tables from all levels, create a changeset to delete all these
// tables and apply it to manifest.
// - Pick all log files from value log, and delete all of them. Restart value log files from zero.
// - Resume memtable flushes and compactions.
//
// NOTE: DropAll is resilient to concurrent writes, but not to reads. It is up to the user to not do
// any reads while DropAll is going on, otherwise they may result in panics. Ideally, both reads and
// writes are paused before running DropAll, and resumed after it is finished.
func (db *DB) DropAll() error {
f, err := db.dropAll()
if f != nil {
f()
}
return err
}
func (db *DB) dropAll() (func(), error) {
db.opt.Infof("DropAll called. Blocking writes...")
f, err := db.prepareToDrop()
if err != nil {
return f, err
}
// prepareToDrop will stop all the incoming write and flushes any pending memtables.
// Before we drop, we'll stop the compaction because anyways all the data are going to
// be deleted.
db.stopCompactions()
resume := func() {
db.startCompactions()
f()
}
// Block all foreign interactions with memory tables.
db.lock.Lock()
defer db.lock.Unlock()
// Remove inmemory tables. Calling DecrRef for safety. Not sure if they're absolutely needed.
db.mt.DecrRef()
for _, mt := range db.imm {
mt.DecrRef()
}
db.imm = db.imm[:0]
db.mt, err = db.newMemTable() // Set it up for future writes.
if err != nil {
return resume, y.Wrapf(err, "cannot open new memtable")
}
num, err := db.lc.dropTree()
if err != nil {
return resume, err
}
db.opt.Infof("Deleted %d SSTables. Now deleting value logs...\n", num)
num, err = db.vlog.dropAll()
if err != nil {
return resume, err
}
db.lc.nextFileID.Store(1)
db.opt.Infof("Deleted %d value log files. DropAll done.\n", num)
db.blockCache.Clear()
db.indexCache.Clear()
db.threshold.Clear(db.opt)
return resume, nil
}
// DropPrefix would drop all the keys with the provided prefix. It does this in the following way:
// - Stop accepting new writes.
// - Stop memtable flushes before acquiring lock. Because we're acquiring lock here
// and memtable flush stalls for lock, which leads to deadlock
// - Flush out all memtables, skipping over keys with the given prefix, Kp.
// - Write out the value log header to memtables when flushing, so we don't accidentally bring Kp
// back after a restart.
// - Stop compaction.
// - Compact L0->L1, skipping over Kp.
// - Compact rest of the levels, Li->Li, picking tables which have Kp.
// - Resume memtable flushes, compactions and writes.
func (db *DB) DropPrefix(prefixes ...[]byte) error {
if len(prefixes) == 0 {
return nil
}
db.opt.Infof("DropPrefix called for %s", prefixes)
f, err := db.prepareToDrop()
if err != nil {
return err
}
defer f()
var filtered [][]byte
if filtered, err = db.filterPrefixesToDrop(prefixes); err != nil {
return err
}
// If there is no prefix for which the data already exist, do not do anything.
if len(filtered) == 0 {
db.opt.Infof("No prefixes to drop")
return nil
}
// Block all foreign interactions with memory tables.
db.lock.Lock()
defer db.lock.Unlock()
db.imm = append(db.imm, db.mt)
for _, memtable := range db.imm {
if memtable.sl.Empty() {
memtable.DecrRef()
continue
}
db.opt.Debugf("Flushing memtable")
if err := db.handleMemTableFlush(memtable, filtered); err != nil {
db.opt.Errorf("While trying to flush memtable: %v", err)
return err
}
memtable.DecrRef()
}
db.stopCompactions()
defer db.startCompactions()
db.imm = db.imm[:0]
db.mt, err = db.newMemTable()
if err != nil {
return y.Wrapf(err, "cannot create new mem table")
}
// Drop prefixes from the levels.
if err := db.lc.dropPrefixes(filtered); err != nil {
return err
}
db.opt.Infof("DropPrefix done")
return nil
}
func (db *DB) filterPrefixesToDrop(prefixes [][]byte) ([][]byte, error) {
var filtered [][]byte
for _, prefix := range prefixes {
err := db.View(func(txn *Txn) error {
iopts := DefaultIteratorOptions
iopts.Prefix = prefix
iopts.PrefetchValues = false
itr := txn.NewIterator(iopts)
defer itr.Close()
itr.Rewind()
if itr.ValidForPrefix(prefix) {
filtered = append(filtered, prefix)
}
return nil
})
if err != nil {
return filtered, err
}
}
return filtered, nil
}
// Checks if the key is banned. Returns the respective error if the key belongs to any of the banned
// namepspaces. Else it returns nil.
func (db *DB) isBanned(key []byte) error {
if db.opt.NamespaceOffset < 0 {
return nil
}
if len(key) <= db.opt.NamespaceOffset+8 {
return nil
}
if db.bannedNamespaces.has(y.BytesToU64(key[db.opt.NamespaceOffset:])) {
return ErrBannedKey
}
return nil
}
// BanNamespace bans a namespace. Read/write to keys belonging to any of such namespace is denied.
func (db *DB) BanNamespace(ns uint64) error {
if db.opt.NamespaceOffset < 0 {
return ErrNamespaceMode
}
db.opt.Infof("Banning namespace: %d", ns)
// First set the banned namespaces in DB and then update the in-memory structure.
key := y.KeyWithTs(append(bannedNsKey, y.U64ToBytes(ns)...), 1)
entry := []*Entry{{
Key: key,
Value: nil,
}}
req, err := db.sendToWriteCh(entry)
if err != nil {
return err
}
if err := req.Wait(); err != nil {
return err
}
db.bannedNamespaces.add(ns)
return nil
}
// BannedNamespaces returns the list of prefixes banned for DB.
func (db *DB) BannedNamespaces() []uint64 {
return db.bannedNamespaces.all()
}
// KVList contains a list of key-value pairs.
type KVList = pb.KVList
// Subscribe can be used to watch key changes for the given key prefixes and the ignore string.
// At least one prefix should be passed, or an error will be returned.
// You can use an empty prefix to monitor all changes to the DB.
// Ignore string is the byte ranges for which prefix matching will be ignored.
// For example: ignore = "2-3", and prefix = "abc" will match for keys "abxxc", "abdfc" etc.
// This function blocks until the given context is done or an error occurs.
// The given function will be called with a new KVList containing the modified keys and the
// corresponding values.
func (db *DB) Subscribe(ctx context.Context, cb func(kv *KVList) error, matches []pb.Match) error {
if cb == nil {
return ErrNilCallback
}
c := z.NewCloser(1)
s, err := db.pub.newSubscriber(c, matches)
if err != nil {
return y.Wrapf(err, "while creating a new subscriber")
}
slurp := func(batch *pb.KVList) error {
for {
select {
case kvs := <-s.sendCh:
batch.Kv = append(batch.Kv, kvs.Kv...)
default:
if len(batch.GetKv()) > 0 {
return cb(batch)
}
return nil
}
}
}
drain := func() {
for {
select {
case _, ok := <-s.sendCh:
if !ok {
// Channel is closed.
return
}
default:
return
}
}
}
for {
select {
case <-c.HasBeenClosed():
// No need to delete here. Closer will be called only while
// closing DB. Subscriber will be deleted by cleanSubscribers.
err := slurp(new(pb.KVList))
// Drain if any pending updates.
c.Done()
return err
case <-ctx.Done():
c.Done()
s.active.Store(0)
drain()
db.pub.deleteSubscriber(s.id)
// Delete the subscriber to avoid further updates.
return ctx.Err()
case batch := <-s.sendCh:
err := slurp(batch)
if err != nil {
c.Done()
s.active.Store(0)
drain()
// Delete the subscriber if there is an error by the callback.
db.pub.deleteSubscriber(s.id)
return err
}
}
}
}
func (db *DB) syncDir(dir string) error {
if db.opt.InMemory {
return nil
}
return syncDir(dir)
}
func createDirs(opt Options) error {
for _, path := range []string{opt.Dir, opt.ValueDir} {
dirExists, err := exists(path)
if err != nil {
return y.Wrapf(err, "Invalid Dir: %q", path)
}
if !dirExists {
if opt.ReadOnly {
return fmt.Errorf("Cannot find directory %q for read-only open", path)
}
// Try to create the directory
err = os.MkdirAll(path, 0700)
if err != nil {
return y.Wrapf(err, "Error Creating Dir: %q", path)
}
}
}
return nil
}
// Stream the contents of this DB to a new DB with options outOptions that will be
// created in outDir.
func (db *DB) StreamDB(outOptions Options) error {
outDir := outOptions.Dir
// Open output DB.
outDB, err := OpenManaged(outOptions)
if err != nil {
return y.Wrapf(err, "cannot open out DB at %s", outDir)
}
defer outDB.Close()
writer := outDB.NewStreamWriter()
if err := writer.Prepare(); err != nil {
return y.Wrapf(err, "cannot create stream writer in out DB at %s", outDir)
}
// Stream contents of DB to the output DB.
stream := db.NewStreamAt(math.MaxUint64)
stream.LogPrefix = fmt.Sprintf("Streaming DB to new DB at %s", outDir)
stream.Send = func(buf *z.Buffer) error {
return writer.Write(buf)
}
if err := stream.Orchestrate(context.Background()); err != nil {
return y.Wrapf(err, "cannot stream DB to out DB at %s", outDir)
}
if err := writer.Flush(); err != nil {
return y.Wrapf(err, "cannot flush writer")
}
return nil
}
// Opts returns a copy of the DB options.
func (db *DB) Opts() Options {
return db.opt
}
type CacheType int
const (
BlockCache CacheType = iota
IndexCache
)
// CacheMaxCost updates the max cost of the given cache (either block or index cache).
// The call will have an effect only if the DB was created with the cache. Otherwise it is
// a no-op. If you pass a negative value, the function will return the current value
// without updating it.
func (db *DB) CacheMaxCost(cache CacheType, maxCost int64) (int64, error) {
if db == nil {
return 0, nil
}
if maxCost < 0 {
switch cache {
case BlockCache:
return db.blockCache.MaxCost(), nil
case IndexCache:
return db.indexCache.MaxCost(), nil
default:
return 0, errors.New("invalid cache type")
}
}
switch cache {
case BlockCache:
db.blockCache.UpdateMaxCost(maxCost)
return maxCost, nil
case IndexCache:
db.indexCache.UpdateMaxCost(maxCost)
return maxCost, nil
default:
return 0, errors.New("invalid cache type")
}
}
func (db *DB) LevelsToString() string {
levels := db.Levels()
h := func(sz int64) string {
return humanize.IBytes(uint64(sz))
}
base := func(b bool) string {
if b {
return "B"
}
return " "
}
var b strings.Builder
b.WriteRune('\n')
for _, li := range levels {
b.WriteString(fmt.Sprintf(
"Level %d [%s]: NumTables: %02d. Size: %s of %s. Score: %.2f->%.2f"+
" StaleData: %s Target FileSize: %s\n",
li.Level, base(li.IsBaseLevel), li.NumTables,
h(li.Size), h(li.TargetSize), li.Score, li.Adjusted, h(li.StaleDatSize),
h(li.TargetFileSize)))
}
b.WriteString("Level Done\n")
return b.String()
}
================================================
FILE: db2_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"bytes"
"context"
"encoding/binary"
"flag"
"fmt"
"log"
"math"
"math/rand"
"os"
"path/filepath"
"regexp"
"runtime"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/dgraph-io/badger/v4/options"
"github.com/dgraph-io/badger/v4/pb"
"github.com/dgraph-io/badger/v4/table"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2/z"
)
func TestTruncateVlogWithClose(t *testing.T) {
key := func(i int) []byte {
return []byte(fmt.Sprintf("%d%10d", i, i))
}
data := func(l int) []byte {
m := make([]byte, l)
_, err := rand.Read(m)
require.NoError(t, err)
return m
}
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := getTestOptions(dir)
opt.SyncWrites = true
opt.ValueThreshold = 1 // Force all reads from value log.
db, err := Open(opt)
require.NoError(t, err)
err = db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry(key(0), data(4055)))
})
require.NoError(t, err)
// Close the DB.
require.NoError(t, db.Close())
// We start value logs at 1.
require.NoError(t, os.Truncate(filepath.Join(dir, "000001.vlog"), 4090))
// Reopen and write some new data.
db, err = Open(opt)
require.NoError(t, err)
for i := 0; i < 32; i++ {
err := db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry(key(i), data(10)))
})
require.NoError(t, err)
}
// Read it back to ensure that we can read it now.
for i := 0; i < 32; i++ {
err := db.View(func(txn *Txn) error {
item, err := txn.Get(key(i))
require.NoError(t, err)
val := getItemValue(t, item)
require.Equal(t, 10, len(val))
return nil
})
require.NoError(t, err)
}
require.NoError(t, db.Close())
// Reopen and read the data again.
db, err = Open(opt)
require.NoError(t, err)
for i := 0; i < 32; i++ {
err := db.View(func(txn *Txn) error {
item, err := txn.Get(key(i))
require.NoError(t, err, "key: %s", key(i))
val := getItemValue(t, item)
require.Equal(t, 10, len(val))
return nil
})
require.NoError(t, err)
}
require.NoError(t, db.Close())
}
var manual = flag.Bool("manual", false, "Set when manually running some tests.")
// Badger dir to be used for performing db.Open benchmark.
var benchDir = flag.String("benchdir", "", "Set when running db.Open benchmark")
// The following 3 TruncateVlogNoClose tests should be run one after another.
// None of these close the DB, simulating a crash. They should be run with a
// script, which truncates the value log to 4090, lining up with the end of the
// first entry in the txn. At <4090, it would cause the entry to be truncated
// immediately, at >4090, same thing.
func TestTruncateVlogNoClose(t *testing.T) {
if !*manual {
t.Skip("Skipping test meant to be run manually.")
return
}
dir := "p"
opts := getTestOptions(dir)
opts.SyncWrites = true
kv, err := Open(opts)
require.NoError(t, err)
key := func(i int) string {
return fmt.Sprintf("%d%10d", i, i)
}
data := fmt.Sprintf("%4055d", 1)
err = kv.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry([]byte(key(0)), []byte(data)))
})
require.NoError(t, err)
}
func TestTruncateVlogNoClose2(t *testing.T) {
if !*manual {
t.Skip("Skipping test meant to be run manually.")
return
}
dir := "p"
opts := getTestOptions(dir)
opts.SyncWrites = true
kv, err := Open(opts)
require.NoError(t, err)
key := func(i int) string {
return fmt.Sprintf("%d%10d", i, i)
}
data := fmt.Sprintf("%10d", 1)
for i := 32; i < 64; i++ {
err := kv.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry([]byte(key(i)), []byte(data)))
})
require.NoError(t, err)
}
for i := 32; i < 64; i++ {
require.NoError(t, kv.View(func(txn *Txn) error {
item, err := txn.Get([]byte(key(i)))
require.NoError(t, err)
val := getItemValue(t, item)
require.NotNil(t, val)
require.True(t, len(val) > 0)
return nil
}))
}
}
func TestTruncateVlogNoClose3(t *testing.T) {
if !*manual {
t.Skip("Skipping test meant to be run manually.")
return
}
fmt.Print("Running")
dir := "p"
opts := getTestOptions(dir)
opts.SyncWrites = true
kv, err := Open(opts)
require.NoError(t, err)
key := func(i int) string {
return fmt.Sprintf("%d%10d", i, i)
}
for i := 32; i < 64; i++ {
require.NoError(t, kv.View(func(txn *Txn) error {
item, err := txn.Get([]byte(key(i)))
require.NoError(t, err)
val := getItemValue(t, item)
require.NotNil(t, val)
require.True(t, len(val) > 0)
return nil
}))
}
}
func TestBigKeyValuePairs(t *testing.T) {
// This test takes too much memory. So, run separately.
if !*manual {
t.Skip("Skipping test meant to be run manually.")
return
}
// Passing an empty directory since it will be filled by runBadgerTest.
opts := DefaultOptions("").
WithBaseTableSize(1 << 20).
WithValueLogMaxEntries(64)
runBadgerTest(t, &opts, func(t *testing.T, db *DB) {
bigK := make([]byte, 65001)
bigV := make([]byte, db.opt.ValueLogFileSize+1)
small := make([]byte, 65000)
txn := db.NewTransaction(true)
require.Regexp(t, regexp.MustCompile("Key.*exceeded"), txn.SetEntry(NewEntry(bigK, small)))
require.Regexp(t, regexp.MustCompile("Value.*exceeded"),
txn.SetEntry(NewEntry(small, bigV)))
require.NoError(t, txn.SetEntry(NewEntry(small, small)))
require.Regexp(t, regexp.MustCompile("Key.*exceeded"), txn.SetEntry(NewEntry(bigK, bigV)))
require.NoError(t, db.View(func(txn *Txn) error {
_, err := txn.Get(small)
require.Equal(t, ErrKeyNotFound, err)
return nil
}))
// Now run a longer test, which involves value log GC.
data := fmt.Sprintf("%100d", 1)
key := func(i int) string {
return fmt.Sprintf("%65000d", i)
}
saveByKey := func(key string, value []byte) error {
return db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry([]byte(key), value))
})
}
getByKey := func(key string) error {
return db.View(func(txn *Txn) error {
item, err := txn.Get([]byte(key))
if err != nil {
return err
}
return item.Value(func(val []byte) error {
if len(val) == 0 {
log.Fatalf("key not found %q", len(key))
}
return nil
})
})
}
for i := 0; i < 32; i++ {
if i < 30 {
require.NoError(t, saveByKey(key(i), []byte(data)))
} else {
require.NoError(t, saveByKey(key(i), []byte(fmt.Sprintf("%100d", i))))
}
}
for j := 0; j < 5; j++ {
for i := 0; i < 32; i++ {
if i < 30 {
require.NoError(t, saveByKey(key(i), []byte(data)))
} else {
require.NoError(t, saveByKey(key(i), []byte(fmt.Sprintf("%100d", i))))
}
}
}
for i := 0; i < 32; i++ {
require.NoError(t, getByKey(key(i)))
}
var loops int
var err error
for err == nil {
err = db.RunValueLogGC(0.5)
require.NotRegexp(t, regexp.MustCompile("truncate"), err)
loops++
}
t.Logf("Ran value log GC %d times. Last error: %v\n", loops, err)
})
}
// The following test checks for issue #585.
func TestPushValueLogLimit(t *testing.T) {
// This test takes too much memory. So, run separately.
if !*manual {
t.Skip("Skipping test meant to be run manually.")
return
}
// Passing an empty directory since it will be filled by runBadgerTest.
opt := DefaultOptions("").
WithValueLogMaxEntries(64).
WithValueLogFileSize(2<<30 - 1)
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
data := []byte(fmt.Sprintf("%30d", 1))
key := func(i int) string {
return fmt.Sprintf("%100d", i)
}
for i := 0; i < 32; i++ {
if i == 4 {
v := make([]byte, math.MaxInt32)
err := db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry([]byte(key(i)), v))
})
require.NoError(t, err)
} else {
err := db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry([]byte(key(i)), data))
})
require.NoError(t, err)
}
}
for i := 0; i < 32; i++ {
err := db.View(func(txn *Txn) error {
item, err := txn.Get([]byte(key(i)))
require.NoError(t, err, "Getting key: %s", key(i))
err = item.Value(func(v []byte) error {
_ = v
return nil
})
require.NoError(t, err, "Getting value: %s", key(i))
return nil
})
require.NoError(t, err)
}
})
}
// The following benchmark test is supposed to be run against a badger directory with some data.
// Use badger fill to create data if it doesn't exist.
func BenchmarkDBOpen(b *testing.B) {
if *benchDir == "" {
b.Skip("Please set -benchdir to badger directory")
}
dir := *benchDir
// Passing an empty directory since it will be filled by runBadgerTest.
opt := DefaultOptions(dir).
WithReadOnly(true)
for i := 0; i < b.N; i++ {
db, err := Open(opt)
require.NoError(b, err)
require.NoError(b, db.Close())
}
}
// Test for values of size uint32.
func TestBigValues(t *testing.T) {
if !*manual {
t.Skip("Skipping test meant to be run manually.")
return
}
opts := DefaultOptions("").
WithValueThreshold(1 << 20).
WithValueLogMaxEntries(100)
test := func(t *testing.T, db *DB) {
keyCount := 1000
data := bytes.Repeat([]byte("a"), (1 << 20)) // Valuesize 1 MB.
key := func(i int) string {
return fmt.Sprintf("%65000d", i)
}
saveByKey := func(key string, value []byte) error {
return db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry([]byte(key), value))
})
}
getByKey := func(key string) error {
return db.View(func(txn *Txn) error {
item, err := txn.Get([]byte(key))
if err != nil {
return err
}
return item.Value(func(val []byte) error {
if len(val) == 0 || len(val) != len(data) || !bytes.Equal(val, data) {
log.Fatalf("key not found %q", len(key))
}
return nil
})
})
}
for i := 0; i < keyCount; i++ {
require.NoError(t, saveByKey(key(i), data))
}
for i := 0; i < keyCount; i++ {
require.NoError(t, getByKey(key(i)))
}
}
t.Run("disk mode", func(t *testing.T) {
runBadgerTest(t, &opts, func(t *testing.T, db *DB) {
test(t, db)
})
})
t.Run("InMemory mode", func(t *testing.T) {
opts.InMemory = true
opts.Dir = ""
opts.ValueDir = ""
db, err := Open(opts)
require.NoError(t, err)
test(t, db)
require.NoError(t, db.Close())
})
}
// This test is for compaction file picking testing. We are creating db with two levels. We have 10
// tables on level 3 and 3 tables on level 2. Tables on level 2 have overlap with 2, 4, 3 tables on
// level 3.
func TestCompactionFilePicking(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
db, err := Open(DefaultOptions(dir))
require.NoError(t, err, "error while opening db")
defer func() {
require.NoError(t, db.Close())
}()
l3 := db.lc.levels[3]
for i := 1; i <= 10; i++ {
// Each table has difference of 1 between smallest and largest key.
tab := createTableWithRange(t, db, 2*i-1, 2*i)
addToManifest(t, db, tab, 3, db.opt)
require.NoError(t, l3.replaceTables([]*table.Table{}, []*table.Table{tab}))
}
l2 := db.lc.levels[2]
// First table has keys 1 and 4.
tab := createTableWithRange(t, db, 1, 4)
addToManifest(t, db, tab, 2, db.opt)
require.NoError(t, l2.replaceTables([]*table.Table{}, []*table.Table{tab}))
// Second table has keys 5 and 12.
tab = createTableWithRange(t, db, 5, 12)
addToManifest(t, db, tab, 2, db.opt)
require.NoError(t, l2.replaceTables([]*table.Table{}, []*table.Table{tab}))
// Third table has keys 13 and 18.
tab = createTableWithRange(t, db, 13, 18)
addToManifest(t, db, tab, 2, db.opt)
require.NoError(t, l2.replaceTables([]*table.Table{}, []*table.Table{tab}))
cdef := &compactDef{
thisLevel: db.lc.levels[2],
nextLevel: db.lc.levels[3],
}
tables := db.lc.levels[2].tables
db.lc.sortByHeuristic(tables, cdef)
var expKey [8]byte
// First table should be with smallest and biggest keys as 1 and 4 which
// has the lowest version.
binary.BigEndian.PutUint64(expKey[:], uint64(1))
require.Equal(t, expKey[:], y.ParseKey(tables[0].Smallest()))
binary.BigEndian.PutUint64(expKey[:], uint64(4))
require.Equal(t, expKey[:], y.ParseKey(tables[0].Biggest()))
// Second table should be with smallest and biggest keys as 13 and 18
// which has the second lowest version.
binary.BigEndian.PutUint64(expKey[:], uint64(13))
require.Equal(t, expKey[:], y.ParseKey(tables[2].Smallest()))
binary.BigEndian.PutUint64(expKey[:], uint64(18))
require.Equal(t, expKey[:], y.ParseKey(tables[2].Biggest()))
// Third table should be with smallest and biggest keys as 5 and 12 which
// has the maximum version.
binary.BigEndian.PutUint64(expKey[:], uint64(5))
require.Equal(t, expKey[:], y.ParseKey(tables[1].Smallest()))
binary.BigEndian.PutUint64(expKey[:], uint64(12))
require.Equal(t, expKey[:], y.ParseKey(tables[1].Biggest()))
}
// addToManifest function is used in TestCompactionFilePicking. It adds table to db manifest.
func addToManifest(t *testing.T, db *DB, tab *table.Table, level uint32, opt Options) {
change := &pb.ManifestChange{
Id: tab.ID(),
Op: pb.ManifestChange_CREATE,
Level: level,
Compression: uint32(tab.CompressionType()),
}
require.NoError(t, db.manifest.addChanges([]*pb.ManifestChange{change}, opt),
"unable to add to manifest")
}
// createTableWithRange function is used in TestCompactionFilePicking. It creates
// a table with key starting from start and ending with end.
func createTableWithRange(t *testing.T, db *DB, start, end int) *table.Table {
bopts := buildTableOptions(db)
b := table.NewTableBuilder(bopts)
defer b.Close()
nums := []int{start, end}
for _, i := range nums {
key := make([]byte, 8)
binary.BigEndian.PutUint64(key[:], uint64(i))
key = y.KeyWithTs(key, uint64(0))
val := y.ValueStruct{Value: []byte(fmt.Sprintf("%d", i))}
b.Add(key, val, 0)
}
fileID := db.lc.reserveFileID()
tab, err := table.CreateTable(table.NewFilename(fileID, db.opt.Dir), b)
require.NoError(t, err)
return tab
}
func TestReadSameVlog(t *testing.T) {
key := func(i int) []byte {
return []byte(fmt.Sprintf("%d%10d", i, i))
}
testReadingSameKey := func(t *testing.T, db *DB) {
// Forcing to read all values from vlog.
for i := 0; i < 50; i++ {
err := db.Update(func(txn *Txn) error {
return txn.Set(key(i), key(i))
})
require.NoError(t, err)
}
// reading it again several times
for i := 0; i < 50; i++ {
for j := 0; j < 10; j++ {
err := db.View(func(txn *Txn) error {
item, err := txn.Get(key(i))
require.NoError(t, err)
require.Equal(t, key(i), getItemValue(t, item))
return nil
})
require.NoError(t, err)
}
}
}
t.Run("Test Read Again Plain Text", func(t *testing.T) {
opt := getTestOptions("")
// Forcing to read from vlog
opt.ValueThreshold = 1
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
testReadingSameKey(t, db)
})
})
t.Run("Test Read Again Encryption", func(t *testing.T) {
opt := getTestOptions("")
opt.ValueThreshold = 1
// Generate encryption key.
eKey := make([]byte, 32)
_, err := rand.Read(eKey)
require.NoError(t, err)
opt.EncryptionKey = eKey
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
testReadingSameKey(t, db)
})
})
}
// The test ensures we don't lose data when badger is opened with KeepL0InMemory and GC is being
// done.
func TestL0GCBug(t *testing.T) {
t.Skipf("TestL0GCBug is DISABLED. TODO(ibrahim): Do we need this?")
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
// Do not change any of the options below unless it's necessary.
opts := getTestOptions(dir)
opts.NumLevelZeroTables = 50
opts.NumLevelZeroTablesStall = 51
opts.ValueLogMaxEntries = 2
opts.ValueThreshold = 2
// Setting LoadingMode to mmap seems to cause segmentation fault while closing DB.
db1, err := Open(opts)
require.NoError(t, err)
key := func(i int) []byte {
return []byte(fmt.Sprintf("%10d", i))
}
val := []byte{1, 1, 1, 1, 1, 1, 1, 1}
// Insert 100 entries. This will create about 50*3 vlog files and 6 SST files.
for i := 0; i < 3; i++ {
for j := 0; j < 100; j++ {
err = db1.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry(key(j), val))
})
require.NoError(t, err)
}
}
// Run value log GC multiple times. This would ensure at least
// one value log file is garbage collected.
success := 0
for i := 0; i < 10; i++ {
err := db1.RunValueLogGC(0.01)
if err == nil {
success++
}
if err != nil && err != ErrNoRewrite {
t.Fatalf(err.Error())
}
}
// Ensure at least one GC call was successful.
require.NotZero(t, success)
// CheckKeys reads all the keys previously stored.
checkKeys := func(db *DB) {
for i := 0; i < 100; i++ {
err := db.View(func(txn *Txn) error {
item, err := txn.Get(key(i))
require.NoError(t, err)
val1 := getItemValue(t, item)
require.Equal(t, val, val1)
return nil
})
require.NoError(t, err)
}
}
checkKeys(db1)
// Simulate a crash by not closing db1 but releasing the locks.
if db1.dirLockGuard != nil {
require.NoError(t, db1.dirLockGuard.release())
db1.dirLockGuard = nil
}
if db1.valueDirGuard != nil {
require.NoError(t, db1.valueDirGuard.release())
db1.valueDirGuard = nil
}
require.NoError(t, db1.Close())
db2, err := Open(opts)
require.NoError(t, err)
// Ensure we still have all the keys.
checkKeys(db2)
require.NoError(t, db2.Close())
}
// Regression test for https://github.com/dgraph-io/badger/issues/1126
//
// The test has 3 steps
// Step 1 - Create badger data. It is necessary that the value size is
//
// greater than valuethreshold. The value log file size after
// this step is around 170 bytes.
//
// Step 2 - Re-open the same badger and simulate a crash. The value log file
//
// size after this crash is around 2 GB (we increase the file size to mmap it).
//
// Step 3 - Re-open the same badger. We should be able to read all the data
//
// inserted in the first step.
func TestWindowsDataLoss(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("The test is only for Windows.")
}
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := DefaultOptions(dir).WithSyncWrites(true)
opt.ValueThreshold = 32
db, err := Open(opt)
require.NoError(t, err)
keyCount := 20
var keyList [][]byte // Stores all the keys generated.
for i := 0; i < keyCount; i++ {
// It is important that we create different transactions for each request.
err := db.Update(func(txn *Txn) error {
key := []byte(fmt.Sprintf("%d", i))
v := []byte("barValuebarValuebarValuebarValuebarValue")
require.Greater(t, len(v), db.valueThreshold())
// 32 bytes length and now it's not working
err := txn.Set(key, v)
require.NoError(t, err)
keyList = append(keyList, key)
return nil
})
require.NoError(t, err)
}
require.NoError(t, db.Close())
db, err = Open(opt)
require.NoError(t, err)
// Return after reading one entry. We're simulating a crash.
// Simulate a crash by not closing db but releasing the locks.
if db.dirLockGuard != nil {
require.NoError(t, db.dirLockGuard.release())
}
if db.valueDirGuard != nil {
require.NoError(t, db.valueDirGuard.release())
}
// Don't use vlog.Close here. We don't want to fix the file size. Only un-mmap
// the data so that we can truncate the file during the next vlog.Open.
require.NoError(t, z.Munmap(db.vlog.filesMap[db.vlog.maxFid].Data))
for _, f := range db.vlog.filesMap {
require.NoError(t, f.Fd.Close())
}
require.NoError(t, db.registry.Close())
require.NoError(t, db.manifest.close())
require.NoError(t, db.lc.close())
db, err = Open(opt)
require.NoError(t, err)
defer db.Close()
txn := db.NewTransaction(false)
defer txn.Discard()
it := txn.NewIterator(DefaultIteratorOptions)
defer it.Close()
var result [][]byte // stores all the keys read from the db.
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
k := item.Key()
err := item.Value(func(v []byte) error {
_ = v
return nil
})
require.NoError(t, err)
result = append(result, k)
}
require.ElementsMatch(t, keyList, result)
}
func TestDropPrefixWithNoData(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
val := []byte("value")
require.NoError(t, db.Update(func(txn *Txn) error {
require.NoError(t, txn.Set([]byte("aaa"), val))
require.NoError(t, txn.Set([]byte("aab"), val))
require.NoError(t, txn.Set([]byte("aba"), val))
require.NoError(t, txn.Set([]byte("aca"), val))
return nil
}))
// If we drop prefix, we flush the memtables and create a new mutable memtable. Hence, the
// nextMemFid increases by 1. But if there does not exist any data for the prefixes, we
// don't do that.
memFid := db.nextMemFid
prefixes := [][]byte{[]byte("bbb")}
require.NoError(t, db.DropPrefix(prefixes...))
require.Equal(t, memFid, db.nextMemFid)
prefixes = [][]byte{[]byte("aba"), []byte("bbb")}
require.NoError(t, db.DropPrefix(prefixes...))
require.Equal(t, memFid+1, db.nextMemFid)
})
}
func TestDropAllDropPrefix(t *testing.T) {
key := func(i int) []byte {
return []byte(fmt.Sprintf("%10d", i))
}
val := func(i int) []byte {
return []byte(fmt.Sprintf("%128d", i))
}
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
wb := db.NewWriteBatch()
defer wb.Cancel()
N := 50000
for i := 0; i < N; i++ {
require.NoError(t, wb.Set(key(i), val(i)))
}
require.NoError(t, wb.Flush())
var wg sync.WaitGroup
wg.Add(3)
go func() {
defer wg.Done()
err := db.DropPrefix([]byte("000"))
for err == ErrBlockedWrites {
err = db.DropPrefix([]byte("000"))
time.Sleep(time.Millisecond * 500)
}
require.NoError(t, err)
}()
go func() {
defer wg.Done()
err := db.DropPrefix([]byte("111"))
for err == ErrBlockedWrites {
err = db.DropPrefix([]byte("111"))
time.Sleep(time.Millisecond * 500)
}
require.NoError(t, err)
}()
go func() {
time.Sleep(time.Millisecond) // Let drop prefix run first.
defer wg.Done()
err := db.DropAll()
for err == ErrBlockedWrites {
err = db.DropAll()
time.Sleep(time.Millisecond * 300)
}
require.NoError(t, err)
}()
wg.Wait()
})
}
func TestIsClosed(t *testing.T) {
test := func(inMemory bool) {
opt := DefaultOptions("")
if inMemory {
opt.InMemory = true
} else {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt.Dir = dir
opt.ValueDir = dir
}
db, err := Open(opt)
require.NoError(t, err)
require.False(t, db.IsClosed())
require.NoError(t, db.Close())
require.True(t, db.IsClosed())
}
t.Run("normal", func(t *testing.T) {
test(false)
})
t.Run("in-memory", func(t *testing.T) {
test(true)
})
}
// This test is failing currently because we're returning version+1 from MaxVersion()
func TestMaxVersion(t *testing.T) {
N := 10000
key := func(i int) []byte {
return []byte(fmt.Sprintf("%d%10d", i, i))
}
t.Run("normal", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
// This will create commits from 1 to N.
for i := 0; i < N; i++ {
txnSet(t, db, key(i), nil, 0)
}
ver := db.MaxVersion()
require.Equal(t, N, int(ver))
})
})
t.Run("multiple versions", func(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := getTestOptions(dir)
opt.NumVersionsToKeep = 100
db, err := OpenManaged(opt)
require.NoError(t, err)
wb := db.NewManagedWriteBatch()
defer wb.Cancel()
k := make([]byte, 100)
rand.Read(k)
// Create multiple version of the same key.
for i := 1; i <= N; i++ {
require.NoError(t, wb.SetEntryAt(&Entry{Key: k}, uint64(i)))
}
require.NoError(t, wb.Flush())
ver := db.MaxVersion()
require.Equal(t, N, int(ver))
require.NoError(t, db.Close())
})
t.Run("Managed mode", func(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := getTestOptions(dir)
db, err := OpenManaged(opt)
require.NoError(t, err)
wb := db.NewManagedWriteBatch()
defer wb.Cancel()
// This will create commits from 1 to N.
for i := 1; i <= N; i++ {
require.NoError(t, wb.SetEntryAt(&Entry{Key: []byte(fmt.Sprintf("%d", i))}, uint64(i)))
}
require.NoError(t, wb.Flush())
ver := db.MaxVersion()
require.NoError(t, err)
require.Equal(t, N, int(ver))
require.NoError(t, db.Close())
})
}
func TestTxnReadTs(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := DefaultOptions(dir)
db, err := Open(opt)
require.NoError(t, err)
require.Equal(t, 0, int(db.orc.readTs()))
txnSet(t, db, []byte("foo"), nil, 0)
require.Equal(t, 1, int(db.orc.readTs()))
require.NoError(t, db.Close())
require.Equal(t, 1, int(db.orc.readTs()))
db, err = Open(opt)
require.NoError(t, err)
require.Equal(t, 1, int(db.orc.readTs()))
}
// This tests failed for stream writer with jemalloc and compression enabled.
func TestKeyCount(t *testing.T) {
if !*manual {
t.Skip("Skipping test meant to be run manually.")
return
}
writeSorted := func(db *DB, num uint64) {
valSz := 128
value := make([]byte, valSz)
y.Check2(rand.Read(value))
es := 8 + valSz // key size is 8 bytes and value size is valSz
writer := db.NewStreamWriter()
require.NoError(t, writer.Prepare())
wg := &sync.WaitGroup{}
writeCh := make(chan *pb.KVList, 3)
writeRange := func(start, end uint64, streamId uint32) {
// end is not included.
defer wg.Done()
kvs := &pb.KVList{}
var sz int
for i := start; i < end; i++ {
key := make([]byte, 8)
binary.BigEndian.PutUint64(key, i)
kvs.Kv = append(kvs.Kv, &pb.KV{
Key: key,
Value: value,
Version: 1,
StreamId: streamId,
})
sz += es
if sz >= 4<<20 { // 4 MB
writeCh <- kvs
kvs = &pb.KVList{}
sz = 0
}
}
writeCh <- kvs
}
// Let's create some streams.
width := num / 16
streamID := uint32(0)
for start := uint64(0); start < num; start += width {
end := start + width
if end > num {
end = num
}
streamID++
wg.Add(1)
go writeRange(start, end, streamID)
}
go func() {
wg.Wait()
close(writeCh)
}()
write := func(kvs *pb.KVList) error {
buf := z.NewBuffer(1<<20, "test")
defer func() { require.NoError(t, buf.Release()) }()
for _, kv := range kvs.Kv {
KVToBuffer(kv, buf)
}
require.NoError(t, writer.Write(buf))
return nil
}
for kvs := range writeCh {
require.NoError(t, write(kvs))
}
require.NoError(t, writer.Flush())
}
N := uint64(10 * 1e6) // 10 million entries
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := DefaultOptions(dir).
WithBlockCacheSize(100 << 20).
WithCompression(options.ZSTD)
db, err := Open(opt)
y.Check(err)
defer db.Close()
writeSorted(db, N)
require.NoError(t, db.Close())
t.Logf("Writing DONE\n")
// Read the db
db2, err := Open(DefaultOptions(dir))
y.Check(err)
defer db.Close()
lastKey := -1
count := 0
streams := make(map[uint32]int)
stream := db2.NewStream()
stream.Send = func(buf *z.Buffer) error {
list, err := BufferToKVList(buf)
if err != nil {
return err
}
for _, kv := range list.Kv {
last := streams[kv.StreamId]
key := binary.BigEndian.Uint64(kv.Key)
// The following should happen as we're writing sorted data.
if last > 0 {
require.Equalf(t, last+1, int(key), "Expected key: %d, Found Key: %d", lastKey+1, int(key))
}
streams[kv.StreamId] = int(key)
}
count += len(list.Kv)
return nil
}
require.NoError(t, stream.Orchestrate(context.Background()))
require.Equal(t, N, uint64(count))
}
func TestAssertValueLogIsNotWrittenToOnStartup(t *testing.T) {
opt := DefaultOptions("").WithValueLogFileSize(1 << 20).WithValueThreshold(1 << 4)
dir, err := os.MkdirTemp(".", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
openDb := func(readonly bool) *DB {
opts := &opt
opts.Dir = dir
opts.ValueDir = dir
if readonly {
opts.ReadOnly = true
}
if opts.InMemory {
opts.Dir = ""
opts.ValueDir = ""
}
db, err := Open(*opts)
require.NoError(t, err)
return db
}
key := func(i int) string {
return fmt.Sprintf("key%100d", i)
}
assertOnLoadDb := func(db *DB) uint32 {
data := []byte(fmt.Sprintf("value%100d", 1))
for i := 0; i < 20; i++ {
err := db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry([]byte(key(i)), data))
})
require.NoError(t, err)
}
return db.vlog.maxFid
}
latestVLogFileSize := func(db *DB, vLogId uint32) uint32 {
return db.vlog.filesMap[vLogId].size.Load()
}
assertOnReadDb := func(db *DB) {
for i := 0; i < 20; i++ {
err := db.View(func(txn *Txn) error {
item, err := txn.Get([]byte(key(i)))
require.NoError(t, err, "Getting key: %s", key(i))
err = item.Value(func(v []byte) error {
_ = v
return nil
})
require.NoError(t, err, "Getting value for the key: %s", key(i))
return nil
})
require.NoError(t, err)
}
}
db := openDb(false)
vLogFileSize := latestVLogFileSize(db, assertOnLoadDb(db))
assertOnReadDb(db)
require.NoError(t, db.Sync())
require.NoError(t, db.Close())
db = openDb(true)
defer func() {
require.NoError(t, db.Close())
}()
assertOnReadDb(db)
require.Equal(t, latestVLogFileSize(db, db.vlog.maxFid), vLogFileSize)
}
================================================
FILE: db_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"bytes"
"context"
"encoding/binary"
"flag"
"fmt"
"math"
"math/rand"
"os"
"path/filepath"
"runtime"
"sort"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/dgraph-io/badger/v4/options"
"github.com/dgraph-io/badger/v4/pb"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2/z"
)
// waitForMessage(ch, expected, count, timeout, t) will block until either
// `timeout` seconds have occurred or `count` instances of the string `expected`
// have occurred on the channel `ch`. We log messages or generate errors using `t`.
func waitForMessage(ch chan string, expected string, count int, timeout int, t *testing.T) {
if count <= 0 {
t.Logf("Will skip waiting for %s since expected count <= 0.",
expected)
return
}
tout := time.NewTimer(time.Duration(timeout) * time.Second)
remaining := count
for {
select {
case curMsg, ok := <-ch:
if !ok {
t.Errorf("Test channel closed while waiting for "+
"message %s with %d remaining instances expected",
expected, remaining)
return
}
t.Logf("Found message: %s", curMsg)
if curMsg == expected {
remaining--
if remaining == 0 {
return
}
}
case <-tout.C:
t.Errorf("Timed out after %d seconds while waiting on test chan "+
"for message '%s' with %d remaining instances expected",
timeout, expected, remaining)
return
}
}
}
// summary is produced when DB is closed. Currently it is used only for testing.
type summary struct {
fileIDs map[uint64]bool
}
func (s *levelsController) getSummary() *summary {
out := &summary{
fileIDs: make(map[uint64]bool),
}
for _, l := range s.levels {
l.getSummary(out)
}
return out
}
func (s *levelHandler) getSummary(sum *summary) {
s.RLock()
defer s.RUnlock()
for _, t := range s.tables {
sum.fileIDs[t.ID()] = true
}
}
func (s *DB) validate() error { return s.lc.validate() }
func getTestOptions(dir string) Options {
opt := DefaultOptions(dir).
WithSyncWrites(false).
WithLoggingLevel(WARNING)
return opt
}
func getItemValue(t *testing.T, item *Item) (val []byte) {
t.Helper()
var v []byte
err := item.Value(func(val []byte) error {
v = append(v, val...)
return nil
})
if err != nil {
t.Error(err)
}
if v == nil {
return nil
}
another, err := item.ValueCopy(nil)
require.NoError(t, err)
require.Equal(t, v, another)
return v
}
func txnSet(t *testing.T, kv *DB, key []byte, val []byte, meta byte) {
txn := kv.NewTransaction(true)
require.NoError(t, txn.SetEntry(NewEntry(key, val).WithMeta(meta)))
require.NoError(t, txn.Commit())
}
func txnDelete(t *testing.T, kv *DB, key []byte) {
txn := kv.NewTransaction(true)
require.NoError(t, txn.Delete(key))
require.NoError(t, txn.Commit())
}
// Opens a badger db and runs a a test on it.
func runBadgerTest(t *testing.T, opts *Options, test func(t *testing.T, db *DB)) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
if opts == nil {
opts = new(Options)
*opts = getTestOptions(dir)
} else {
opts.Dir = dir
opts.ValueDir = dir
}
if opts.InMemory {
opts.Dir = ""
opts.ValueDir = ""
}
db, err := Open(*opts)
require.NoError(t, err)
defer func() {
require.NoError(t, db.Close())
}()
test(t, db)
}
func TestReverseIterator(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
key := make([]byte, 6)
err := db.Update(func(txn *Txn) error {
binary.BigEndian.PutUint16(key, 5)
binary.BigEndian.PutUint32(key[2:], 1)
err1 := txn.Set(key, []byte("value1"))
require.NoError(t, err1)
binary.BigEndian.PutUint32(key[2:], 2)
err1 = txn.Set(key, []byte("value2"))
require.NoError(t, err1)
return nil
})
require.NoError(t, err)
err = db.View(func(txn *Txn) error {
searchBuffer := make([]byte, 3)
binary.BigEndian.PutUint16(searchBuffer, 5)
searchBuffer[2] = 0xFF
iteratorOptions := DefaultIteratorOptions
iteratorOptions.Reverse = true
iteratorOptions.PrefetchValues = false
iteratorOptions.Prefix = searchBuffer
it := txn.NewIterator(iteratorOptions)
defer it.Close()
it.Rewind()
require.Equal(t, it.Item().Key(), key)
return nil
})
require.NoError(t, err)
})
}
func TestWrite(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
for i := 0; i < 100; i++ {
txnSet(t, db, []byte(fmt.Sprintf("key%d", i)), []byte(fmt.Sprintf("val%d", i)), 0x00)
}
})
}
func TestUpdateAndView(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
err := db.Update(func(txn *Txn) error {
for i := 0; i < 10; i++ {
entry := NewEntry([]byte(fmt.Sprintf("key%d", i)), []byte(fmt.Sprintf("val%d", i)))
if err := txn.SetEntry(entry); err != nil {
return err
}
}
return nil
})
require.NoError(t, err)
err = db.View(func(txn *Txn) error {
for i := 0; i < 10; i++ {
item, err := txn.Get([]byte(fmt.Sprintf("key%d", i)))
if err != nil {
return err
}
expected := []byte(fmt.Sprintf("val%d", i))
if err := item.Value(func(val []byte) error {
require.Equal(t, expected, val,
"Invalid value for key %q. expected: %q, actual: %q",
item.Key(), expected, val)
return nil
}); err != nil {
return err
}
}
return nil
})
require.NoError(t, err)
})
}
func TestConcurrentWrite(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
// Not a benchmark. Just a simple test for concurrent writes.
n := 20
m := 500
var wg sync.WaitGroup
for i := 0; i < n; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
for j := 0; j < m; j++ {
txnSet(t, db, []byte(fmt.Sprintf("k%05d_%08d", i, j)),
[]byte(fmt.Sprintf("v%05d_%08d", i, j)), byte(j%127))
}
}(i)
}
wg.Wait()
t.Log("Starting iteration")
opt := IteratorOptions{}
opt.Reverse = false
opt.PrefetchSize = 10
opt.PrefetchValues = true
txn := db.NewTransaction(true)
it := txn.NewIterator(opt)
defer it.Close()
var i, j int
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
k := item.Key()
if k == nil {
break // end of iteration.
}
require.EqualValues(t, fmt.Sprintf("k%05d_%08d", i, j), string(k))
v := getItemValue(t, item)
require.EqualValues(t, fmt.Sprintf("v%05d_%08d", i, j), string(v))
require.Equal(t, item.UserMeta(), byte(j%127))
j++
if j == m {
i++
j = 0
}
}
require.EqualValues(t, n, i)
require.EqualValues(t, 0, j)
})
}
func TestGet(t *testing.T) {
test := func(t *testing.T, db *DB) {
txnSet(t, db, []byte("key1"), []byte("val1"), 0x08)
txn := db.NewTransaction(false)
item, err := txn.Get([]byte("key1"))
require.NoError(t, err)
require.EqualValues(t, "val1", getItemValue(t, item))
require.Equal(t, byte(0x08), item.UserMeta())
txn.Discard()
txnSet(t, db, []byte("key1"), []byte("val2"), 0x09)
txn = db.NewTransaction(false)
item, err = txn.Get([]byte("key1"))
require.NoError(t, err)
require.EqualValues(t, "val2", getItemValue(t, item))
require.Equal(t, byte(0x09), item.UserMeta())
txn.Discard()
txnDelete(t, db, []byte("key1"))
txn = db.NewTransaction(false)
_, err = txn.Get([]byte("key1"))
require.Equal(t, ErrKeyNotFound, err)
txn.Discard()
txnSet(t, db, []byte("key1"), []byte("val3"), 0x01)
txn = db.NewTransaction(false)
item, err = txn.Get([]byte("key1"))
require.NoError(t, err)
require.EqualValues(t, "val3", getItemValue(t, item))
require.Equal(t, byte(0x01), item.UserMeta())
longVal := make([]byte, 1000)
txnSet(t, db, []byte("key1"), longVal, 0x00)
txn = db.NewTransaction(false)
item, err = txn.Get([]byte("key1"))
require.NoError(t, err)
require.EqualValues(t, longVal, getItemValue(t, item))
txn.Discard()
}
t.Run("disk mode", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
test(t, db)
})
})
t.Run("InMemory mode", func(t *testing.T) {
opts := DefaultOptions("").WithInMemory(true)
db, err := Open(opts)
require.NoError(t, err)
test(t, db)
require.NoError(t, db.Close())
})
t.Run("cache enabled", func(t *testing.T) {
opts := DefaultOptions("").WithBlockCacheSize(10 << 20)
runBadgerTest(t, &opts, func(t *testing.T, db *DB) {
test(t, db)
})
})
}
func TestGetAfterDelete(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
// populate with one entry
key := []byte("key")
txnSet(t, db, key, []byte("val1"), 0x00)
require.NoError(t, db.Update(func(txn *Txn) error {
err := txn.Delete(key)
require.NoError(t, err)
_, err = txn.Get(key)
require.Equal(t, ErrKeyNotFound, err)
return nil
}))
})
}
func TestTxnTooBig(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
data := func(i int) []byte {
return []byte(fmt.Sprintf("%b", i))
}
// n := 500000
n := 1000
txn := db.NewTransaction(true)
for i := 0; i < n; {
if err := txn.SetEntry(NewEntry(data(i), data(i))); err != nil {
require.NoError(t, txn.Commit())
txn = db.NewTransaction(true)
} else {
i++
}
}
require.NoError(t, txn.Commit())
txn = db.NewTransaction(true)
for i := 0; i < n; {
if err := txn.Delete(data(i)); err != nil {
require.NoError(t, txn.Commit())
txn = db.NewTransaction(true)
} else {
i++
}
}
require.NoError(t, txn.Commit())
})
}
func TestForceCompactL0(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
// This test relies on CompactL0OnClose
opts := getTestOptions(dir).WithCompactL0OnClose(true)
opts.ValueLogFileSize = 15 << 20
opts.managedTxns = true
db, err := Open(opts)
require.NoError(t, err)
data := func(i int) []byte {
return []byte(fmt.Sprintf("%b", i))
}
n := 80
m := 45 // Increasing would cause ErrTxnTooBig
sz := 32 << 10
v := make([]byte, sz)
for i := 0; i < n; i += 2 {
version := uint64(i)
txn := db.NewTransactionAt(version, true)
for j := 0; j < m; j++ {
require.NoError(t, txn.SetEntry(NewEntry(data(j), v)))
}
require.NoError(t, txn.CommitAt(version+1, nil))
}
db.Close()
opts.managedTxns = true
db, err = Open(opts)
require.NoError(t, err)
require.Equal(t, len(db.lc.levels[0].tables), 0)
require.NoError(t, db.Close())
}
func TestStreamDB(t *testing.T) {
check := func(db *DB) {
for i := 0; i < 100; i++ {
key := []byte(fmt.Sprintf("key%d", i))
val := []byte(fmt.Sprintf("val%d", i))
txn := db.NewTransactionAt(1, false)
item, err := txn.Get(key)
require.NoError(t, err)
require.EqualValues(t, val, getItemValue(t, item))
require.Equal(t, byte(0x00), item.UserMeta())
txn.Discard()
}
}
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opts := getTestOptions(dir).
WithCompression(options.ZSTD).
WithBlockCacheSize(100 << 20)
db, err := OpenManaged(opts)
require.NoError(t, err)
defer func() {
require.NoError(t, db.Close())
}()
writer := db.NewManagedWriteBatch()
for i := 0; i < 100; i++ {
key := []byte(fmt.Sprintf("key%d", i))
val := []byte(fmt.Sprintf("val%d", i))
require.NoError(t, writer.SetEntryAt(NewEntry(key, val).WithMeta(0x00), 1))
}
require.NoError(t, writer.Flush())
check(db)
outDir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
outOpt := getTestOptions(outDir)
require.NoError(t, db.StreamDB(outOpt))
outDB, err := OpenManaged(outOpt)
require.NoError(t, err)
defer func() {
require.NoError(t, outDB.Close())
}()
check(outDB)
}
func dirSize(path string) (int64, error) {
var size int64
err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
if !info.IsDir() {
size += info.Size()
}
return err
})
return (size >> 20), err
}
// BenchmarkDbGrowth ensures DB does not grow with repeated adds and deletes.
//
// New keys are created with each for-loop iteration. During each
// iteration, the previous for-loop iteration's keys are deleted.
//
// To reproduce continuous growth problem due to `badgerMove` keys,
// update `value.go` `discardEntry` line 1628 to return false
//
// Also with PR #1303, the delete keys are properly cleaned which
// further reduces disk size.
func BenchmarkDbGrowth(b *testing.B) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(b, err)
defer removeDir(dir)
start := 0
lastStart := 0
numKeys := 2000
valueSize := 1024
value := make([]byte, valueSize)
discardRatio := 0.001
maxWrites := 200
opts := getTestOptions(dir)
opts.ValueLogFileSize = 64 << 15
opts.BaseTableSize = 4 << 15
opts.BaseLevelSize = 16 << 15
opts.NumVersionsToKeep = 1
opts.NumLevelZeroTables = 1
opts.NumLevelZeroTablesStall = 2
opts.ValueThreshold = 1024
opts.MemTableSize = 1 << 20
db, err := Open(opts)
require.NoError(b, err)
for numWrites := 0; numWrites < maxWrites; numWrites++ {
txn := db.NewTransaction(true)
if start > 0 {
for i := lastStart; i < start; i++ {
key := make([]byte, 8)
binary.BigEndian.PutUint64(key[:], uint64(i))
err := txn.Delete(key)
if err == ErrTxnTooBig {
require.NoError(b, txn.Commit())
txn = db.NewTransaction(true)
} else {
require.NoError(b, err)
}
}
}
for i := start; i < numKeys+start; i++ {
key := make([]byte, 8)
binary.BigEndian.PutUint64(key[:], uint64(i))
err := txn.SetEntry(NewEntry(key, value))
if err == ErrTxnTooBig {
require.NoError(b, txn.Commit())
txn = db.NewTransaction(true)
} else {
require.NoError(b, err)
}
}
require.NoError(b, txn.Commit())
require.NoError(b, db.Flatten(1))
for {
err = db.RunValueLogGC(discardRatio)
if err == ErrNoRewrite {
break
} else {
require.NoError(b, err)
}
}
size, err := dirSize(dir)
require.NoError(b, err)
fmt.Printf("Badger DB Size = %dMB\n", size)
lastStart = start
start += numKeys
}
db.Close()
size, err := dirSize(dir)
require.NoError(b, err)
require.LessOrEqual(b, size, int64(16))
fmt.Printf("Badger DB Size = %dMB\n", size)
}
// Put a lot of data to move some data to disk.
// WARNING: This test might take a while but it should pass!
func TestGetMore(t *testing.T) {
if !*manual {
t.Skip("Skipping test meant to be run manually.")
return
}
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
data := func(i int) []byte {
return []byte(fmt.Sprintf("%b", i))
}
n := 200000
m := 45 // Increasing would cause ErrTxnTooBig
for i := 0; i < n; i += m {
if (i % 10000) == 0 {
fmt.Printf("Inserting i=%d\n", i)
}
txn := db.NewTransaction(true)
for j := i; j < i+m && j < n; j++ {
require.NoError(t, txn.SetEntry(NewEntry(data(j), data(j))))
}
require.NoError(t, txn.Commit())
}
require.NoError(t, db.validate())
for i := 0; i < n; i++ {
txn := db.NewTransaction(false)
item, err := txn.Get(data(i))
if err != nil {
t.Error(err)
}
require.EqualValues(t, string(data(i)), string(getItemValue(t, item)))
txn.Discard()
}
// Overwrite
for i := 0; i < n; i += m {
txn := db.NewTransaction(true)
for j := i; j < i+m && j < n; j++ {
require.NoError(t, txn.SetEntry(NewEntry(data(j),
// Use a long value that will certainly exceed value threshold.
[]byte(fmt.Sprintf("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz%9d", j)))))
}
require.NoError(t, txn.Commit())
}
require.NoError(t, db.validate())
for i := 0; i < n; i++ {
expectedValue := fmt.Sprintf("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz%9d", i)
k := data(i)
txn := db.NewTransaction(false)
item, err := txn.Get(k)
if err != nil {
t.Error(err)
}
got := string(getItemValue(t, item))
if expectedValue != got {
vs, err := db.get(y.KeyWithTs(k, math.MaxUint64))
require.NoError(t, err)
fmt.Printf("wanted=%q Item: %s\n", k, item)
fmt.Printf("on re-run, got version: %+v\n", vs)
txn := db.NewTransaction(false)
itr := txn.NewIterator(DefaultIteratorOptions)
for itr.Seek(k); itr.Valid(); itr.Next() {
item := itr.Item()
fmt.Printf("item=%s\n", item)
if !bytes.Equal(item.Key(), k) {
break
}
}
itr.Close()
txn.Discard()
}
require.EqualValues(t, expectedValue, string(getItemValue(t, item)), "wanted=%q Item: %s\n", k, item)
txn.Discard()
}
// "Delete" key.
for i := 0; i < n; i += m {
if (i % 10000) == 0 {
fmt.Printf("Deleting i=%d\n", i)
}
txn := db.NewTransaction(true)
for j := i; j < i+m && j < n; j++ {
require.NoError(t, txn.Delete(data(j)))
}
require.NoError(t, txn.Commit())
}
require.NoError(t, db.validate())
for i := 0; i < n; i++ {
if (i % 10000) == 0 {
// Display some progress. Right now, it's not very fast with no caching.
fmt.Printf("Testing i=%d\n", i)
}
k := data(i)
txn := db.NewTransaction(false)
_, err := txn.Get(k)
require.Equal(t, ErrKeyNotFound, err, "should not have found k: %q", k)
txn.Discard()
}
})
}
// Put a lot of data to move some data to disk.
// WARNING: This test might take a while but it should pass!
func TestExistsMore(t *testing.T) {
test := func(t *testing.T, db *DB) {
// n := 500000
n := 10000
m := 45
for i := 0; i < n; i += m {
if (i % 1000) == 0 {
t.Logf("Putting i=%d\n", i)
}
txn := db.NewTransaction(true)
for j := i; j < i+m && j < n; j++ {
require.NoError(t, txn.SetEntry(NewEntry([]byte(fmt.Sprintf("%09d", j)),
[]byte(fmt.Sprintf("%09d", j)))))
}
require.NoError(t, txn.Commit())
}
require.NoError(t, db.validate())
for i := 0; i < n; i++ {
if (i % 1000) == 0 {
fmt.Printf("Testing i=%d\n", i)
}
k := fmt.Sprintf("%09d", i)
require.NoError(t, db.View(func(txn *Txn) error {
_, err := txn.Get([]byte(k))
require.NoError(t, err)
return nil
}))
}
require.NoError(t, db.View(func(txn *Txn) error {
_, err := txn.Get([]byte("non-exists"))
require.Error(t, err)
return nil
}))
// "Delete" key.
for i := 0; i < n; i += m {
if (i % 1000) == 0 {
fmt.Printf("Deleting i=%d\n", i)
}
txn := db.NewTransaction(true)
for j := i; j < i+m && j < n; j++ {
require.NoError(t, txn.Delete([]byte(fmt.Sprintf("%09d", j))))
}
require.NoError(t, txn.Commit())
}
require.NoError(t, db.validate())
for i := 0; i < n; i++ {
if (i % 10000) == 0 {
// Display some progress. Right now, it's not very fast with no caching.
fmt.Printf("Testing i=%d\n", i)
}
k := fmt.Sprintf("%09d", i)
require.NoError(t, db.View(func(txn *Txn) error {
_, err := txn.Get([]byte(k))
require.Error(t, err)
return nil
}))
}
fmt.Println("Done and closing")
}
t.Run("disk mode", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
test(t, db)
})
})
t.Run("InMemory mode", func(t *testing.T) {
opt := DefaultOptions("").WithInMemory(true)
db, err := Open(opt)
require.NoError(t, err)
test(t, db)
require.NoError(t, db.Close())
})
}
func TestIterate2Basic(t *testing.T) {
test := func(t *testing.T, db *DB) {
bkey := func(i int) []byte {
return []byte(fmt.Sprintf("%09d", i))
}
bval := func(i int) []byte {
return []byte(fmt.Sprintf("%025d", i))
}
// n := 500000
n := 10000
for i := 0; i < n; i++ {
if (i % 1000) == 0 {
t.Logf("Put i=%d\n", i)
}
txnSet(t, db, bkey(i), bval(i), byte(i%127))
}
opt := IteratorOptions{}
opt.PrefetchValues = true
opt.PrefetchSize = 10
txn := db.NewTransaction(false)
it := txn.NewIterator(opt)
{
var count int
rewind := true
t.Log("Starting first basic iteration")
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
key := item.Key()
if rewind && count == 5000 {
// Rewind would skip /head/ key, and it.Next() would skip 0.
count = 1
it.Rewind()
t.Log("Rewinding from 5000 to zero.")
rewind = false
continue
}
require.EqualValues(t, bkey(count), string(key))
val := getItemValue(t, item)
require.EqualValues(t, bval(count), string(val))
require.Equal(t, byte(count%127), item.UserMeta())
count++
}
require.EqualValues(t, n, count)
}
{
t.Log("Starting second basic iteration")
idx := 5030
for it.Seek(bkey(idx)); it.Valid(); it.Next() {
item := it.Item()
require.EqualValues(t, bkey(idx), string(item.Key()))
require.EqualValues(t, bval(idx), string(getItemValue(t, item)))
idx++
}
}
it.Close()
}
t.Run("disk mode", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
test(t, db)
})
})
t.Run("InMemory mode", func(t *testing.T) {
opt := DefaultOptions("").WithInMemory(true)
db, err := Open(opt)
require.NoError(t, err)
test(t, db)
require.NoError(t, db.Close())
})
}
func TestLoad(t *testing.T) {
testLoad := func(t *testing.T, opt Options) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt.Dir = dir
opt.ValueDir = dir
n := 10000
{
kv, err := Open(opt)
require.NoError(t, err)
for i := 0; i < n; i++ {
if (i % 10000) == 0 {
fmt.Printf("Putting i=%d\n", i)
}
k := []byte(fmt.Sprintf("%09d", i))
txnSet(t, kv, k, k, 0x00)
}
require.Equal(t, 10000, int(kv.orc.readTs()))
kv.Close()
}
kv, err := Open(opt)
require.NoError(t, err)
require.Equal(t, 10000, int(kv.orc.readTs()))
for i := 0; i < n; i++ {
if (i % 10000) == 0 {
fmt.Printf("Testing i=%d\n", i)
}
k := fmt.Sprintf("%09d", i)
require.NoError(t, kv.View(func(txn *Txn) error {
item, err := txn.Get([]byte(k))
require.NoError(t, err)
require.EqualValues(t, k, string(getItemValue(t, item)))
return nil
}))
}
kv.Close()
summary := kv.lc.getSummary()
// Check that files are garbage collected.
idMap := getIDMap(dir)
for fileID := range idMap {
// Check that name is in summary.filenames.
require.True(t, summary.fileIDs[fileID], "%d", fileID)
}
require.EqualValues(t, len(idMap), len(summary.fileIDs))
var fileIDs []uint64
for k := range summary.fileIDs { // Map to array.
fileIDs = append(fileIDs, k)
}
sort.Slice(fileIDs, func(i, j int) bool { return fileIDs[i] < fileIDs[j] })
fmt.Printf("FileIDs: %v\n", fileIDs)
}
t.Run("TestLoad Without Encryption/Compression", func(t *testing.T) {
opt := getTestOptions("")
opt.Compression = options.None
testLoad(t, opt)
})
t.Run("TestLoad With Encryption and no compression", func(t *testing.T) {
key := make([]byte, 32)
_, err := rand.Read(key)
require.NoError(t, err)
opt := getTestOptions("")
opt.EncryptionKey = key
opt.BlockCacheSize = 100 << 20
opt.IndexCacheSize = 100 << 20
opt.Compression = options.None
testLoad(t, opt)
})
t.Run("TestLoad With Encryption and compression", func(t *testing.T) {
key := make([]byte, 32)
_, err := rand.Read(key)
require.NoError(t, err)
opt := getTestOptions("")
opt.EncryptionKey = key
opt.Compression = options.ZSTD
opt.BlockCacheSize = 100 << 20
opt.IndexCacheSize = 100 << 20
testLoad(t, opt)
})
t.Run("TestLoad without Encryption and with compression", func(t *testing.T) {
opt := getTestOptions("")
opt.Compression = options.ZSTD
opt.BlockCacheSize = 100 << 20
testLoad(t, opt)
})
}
func TestIterateDeleted(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
txnSet(t, db, []byte("Key1"), []byte("Value1"), 0x00)
txnSet(t, db, []byte("Key2"), []byte("Value2"), 0x00)
iterOpt := DefaultIteratorOptions
iterOpt.PrefetchValues = false
txn := db.NewTransaction(false)
idxIt := txn.NewIterator(iterOpt)
defer idxIt.Close()
count := 0
txn2 := db.NewTransaction(true)
prefix := []byte("Key")
for idxIt.Seek(prefix); idxIt.ValidForPrefix(prefix); idxIt.Next() {
key := idxIt.Item().Key()
count++
newKey := make([]byte, len(key))
copy(newKey, key)
require.NoError(t, txn2.Delete(newKey))
}
require.Equal(t, 2, count)
require.NoError(t, txn2.Commit())
for _, prefetch := range [...]bool{true, false} {
t.Run(fmt.Sprintf("Prefetch=%t", prefetch), func(t *testing.T) {
txn := db.NewTransaction(false)
iterOpt = DefaultIteratorOptions
iterOpt.PrefetchValues = prefetch
idxIt = txn.NewIterator(iterOpt)
var estSize int64
var idxKeys []string
for idxIt.Seek(prefix); idxIt.Valid(); idxIt.Next() {
item := idxIt.Item()
key := item.Key()
estSize += item.EstimatedSize()
if !bytes.HasPrefix(key, prefix) {
break
}
idxKeys = append(idxKeys, string(key))
t.Logf("%+v\n", idxIt.Item())
}
require.Equal(t, 0, len(idxKeys))
require.Equal(t, int64(0), estSize)
})
}
})
}
func TestIterateParallel(t *testing.T) {
if !*manual {
t.Skip("Skipping test meant to be run manually.")
return
}
key := func(account int) []byte {
var b [4]byte
binary.BigEndian.PutUint32(b[:], uint32(account))
return append([]byte("account-"), b[:]...)
}
N := 100000
iterate := func(txn *Txn, wg *sync.WaitGroup) {
defer wg.Done()
itr := txn.NewIterator(DefaultIteratorOptions)
defer itr.Close()
var count int
for itr.Rewind(); itr.Valid(); itr.Next() {
count++
item := itr.Item()
require.Equal(t, "account-", string(item.Key()[0:8]))
err := item.Value(func(val []byte) error {
require.Equal(t, "1000", string(val))
return nil
})
require.NoError(t, err)
}
require.Equal(t, N, count)
itr.Close() // Double close.
}
opt := DefaultOptions("")
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
var wg sync.WaitGroup
var txns []*Txn
for i := 0; i < N; i++ {
wg.Add(1)
txn := db.NewTransaction(true)
require.NoError(t, txn.SetEntry(NewEntry(key(i), []byte("1000"))))
txns = append(txns, txn)
}
for _, txn := range txns {
txn.CommitWith(func(err error) {
y.Check(err)
wg.Done()
})
}
wg.Wait()
// Check that a RW txn can run multiple iterators.
txn := db.NewTransaction(true)
itr := txn.NewIterator(DefaultIteratorOptions)
require.NotPanics(t, func() {
// Now that multiple iterators are supported in read-write
// transactions, make sure this does not panic anymore. Then just
// close the iterator.
txn.NewIterator(DefaultIteratorOptions).Close()
})
// The transaction should still panic since there is still one pending
// iterator that is open.
require.Panics(t, txn.Discard)
itr.Close()
txn.Discard()
// (Regression) Make sure that creating multiple concurrent iterators
// within a read only transaction continues to work.
t.Run("multiple read-only iterators", func(t *testing.T) {
// Run multiple iterators for a RO txn.
txn = db.NewTransaction(false)
defer txn.Discard()
wg.Add(3)
go iterate(txn, &wg)
go iterate(txn, &wg)
go iterate(txn, &wg)
wg.Wait()
})
// Make sure that when we create multiple concurrent iterators within a
// read-write transaction that it actually iterates successfully.
t.Run("multiple read-write iterators", func(t *testing.T) {
// Run multiple iterators for a RO txn.
txn = db.NewTransaction(true)
defer txn.Discard()
wg.Add(3)
go iterate(txn, &wg)
go iterate(txn, &wg)
go iterate(txn, &wg)
wg.Wait()
})
})
}
func TestDeleteWithoutSyncWrite(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
kv, err := Open(DefaultOptions(dir))
if err != nil {
t.Error(err)
t.Fail()
}
key := []byte("k1")
// Set a value with size > value threshold so that its written to value log.
txnSet(t, kv, key, []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789FOOBARZOGZOG"), 0x00)
txnDelete(t, kv, key)
kv.Close()
// Reopen KV
kv, err = Open(DefaultOptions(dir))
if err != nil {
t.Error(err)
t.Fail()
}
defer kv.Close()
require.NoError(t, kv.View(func(txn *Txn) error {
_, err := txn.Get(key)
require.Equal(t, ErrKeyNotFound, err)
return nil
}))
}
func TestPidFile(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
// Reopen database
_, err := Open(getTestOptions(db.opt.Dir))
require.Error(t, err)
require.Contains(t, err.Error(), "Another process is using this Badger database")
})
}
func TestInvalidKey(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
err := db.Update(func(txn *Txn) error {
err := txn.SetEntry(NewEntry([]byte("!badger!head"), nil))
require.Equal(t, ErrInvalidKey, err)
err = txn.SetEntry(NewEntry([]byte("!badger!"), nil))
require.Equal(t, ErrInvalidKey, err)
err = txn.SetEntry(NewEntry([]byte("!badger"), []byte("BadgerDB")))
require.NoError(t, err)
return err
})
require.NoError(t, err)
require.NoError(t, db.View(func(txn *Txn) error {
item, err := txn.Get([]byte("!badger"))
if err != nil {
return err
}
require.NoError(t, item.Value(func(val []byte) error {
require.Equal(t, []byte("BadgerDB"), val)
return nil
}))
return nil
}))
})
}
func TestIteratorPrefetchSize(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
bkey := func(i int) []byte {
return []byte(fmt.Sprintf("%09d", i))
}
bval := func(i int) []byte {
return []byte(fmt.Sprintf("%025d", i))
}
n := 100
for i := 0; i < n; i++ {
// if (i % 10) == 0 {
// t.Logf("Put i=%d\n", i)
// }
txnSet(t, db, bkey(i), bval(i), byte(i%127))
}
getIteratorCount := func(prefetchSize int) int {
opt := IteratorOptions{}
opt.PrefetchValues = true
opt.PrefetchSize = prefetchSize
var count int
txn := db.NewTransaction(false)
it := txn.NewIterator(opt)
{
t.Log("Starting first basic iteration")
for it.Rewind(); it.Valid(); it.Next() {
count++
}
require.EqualValues(t, n, count)
}
return count
}
var sizes = []int{-10, 0, 1, 10}
for _, size := range sizes {
c := getIteratorCount(size)
require.Equal(t, 100, c)
}
})
}
func TestSetIfAbsentAsync(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
kv, _ := Open(getTestOptions(dir))
bkey := func(i int) []byte {
return []byte(fmt.Sprintf("%09d", i))
}
f := func(err error) {}
n := 1000
for i := 0; i < n; i++ {
// if (i % 10) == 0 {
// t.Logf("Put i=%d\n", i)
// }
txn := kv.NewTransaction(true)
_, err = txn.Get(bkey(i))
require.Equal(t, ErrKeyNotFound, err)
require.NoError(t, txn.SetEntry(NewEntry(bkey(i), nil).WithMeta(byte(i%127))))
txn.CommitWith(f)
}
require.NoError(t, kv.Close())
kv, err = Open(getTestOptions(dir))
require.NoError(t, err)
opt := DefaultIteratorOptions
txn := kv.NewTransaction(false)
var count int
it := txn.NewIterator(opt)
{
t.Log("Starting first basic iteration")
for it.Rewind(); it.Valid(); it.Next() {
count++
}
require.EqualValues(t, n, count)
}
require.Equal(t, n, count)
require.NoError(t, kv.Close())
}
func TestGetSetRace(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
data := make([]byte, 4096)
_, err := rand.Read(data)
require.NoError(t, err)
var (
numOp = 100
wg sync.WaitGroup
keyCh = make(chan string)
)
// writer
wg.Add(1)
go func() {
defer func() {
wg.Done()
close(keyCh)
}()
for i := 0; i < numOp; i++ {
key := fmt.Sprintf("%d", i)
txnSet(t, db, []byte(key), data, 0x00)
keyCh <- key
}
}()
// reader
wg.Add(1)
go func() {
defer wg.Done()
for key := range keyCh {
require.NoError(t, db.View(func(txn *Txn) error {
item, err := txn.Get([]byte(key))
require.NoError(t, err)
err = item.Value(nil)
require.NoError(t, err)
return nil
}))
}
}()
wg.Wait()
})
}
func TestDiscardVersionsBelow(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
// Write 4 versions of the same key
for i := 0; i < 4; i++ {
err := db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry([]byte("answer"), []byte(fmt.Sprintf("%d", i))))
})
require.NoError(t, err)
}
opts := DefaultIteratorOptions
opts.AllVersions = true
opts.PrefetchValues = false
// Verify that there are 4 versions, and record 3rd version (2nd from top in iteration)
require.NoError(t, db.View(func(txn *Txn) error {
it := txn.NewIterator(opts)
defer it.Close()
var count int
for it.Rewind(); it.Valid(); it.Next() {
count++
item := it.Item()
require.Equal(t, []byte("answer"), item.Key())
if item.DiscardEarlierVersions() {
break
}
}
require.Equal(t, 4, count)
return nil
}))
// Set new version and discard older ones.
err := db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry([]byte("answer"), []byte("5")).WithDiscard())
})
require.NoError(t, err)
// Verify that there are only 2 versions left, and versions
// below ts have been deleted.
require.NoError(t, db.View(func(txn *Txn) error {
it := txn.NewIterator(opts)
defer it.Close()
var count int
for it.Rewind(); it.Valid(); it.Next() {
count++
item := it.Item()
require.Equal(t, []byte("answer"), item.Key())
if item.DiscardEarlierVersions() {
break
}
}
require.Equal(t, 1, count)
return nil
}))
})
}
func TestExpiry(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
// Write two keys, one with a TTL
err := db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry([]byte("answer1"), []byte("42")))
})
require.NoError(t, err)
err = db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry([]byte("answer2"), []byte("43")).WithTTL(1 * time.Second))
})
require.NoError(t, err)
time.Sleep(2 * time.Second)
// Verify that only unexpired key is found during iteration
err = db.View(func(txn *Txn) error {
_, err := txn.Get([]byte("answer1"))
require.NoError(t, err)
_, err = txn.Get([]byte("answer2"))
require.Equal(t, ErrKeyNotFound, err)
return nil
})
require.NoError(t, err)
// Verify that only one key is found during iteration
opts := DefaultIteratorOptions
opts.PrefetchValues = false
err = db.View(func(txn *Txn) error {
it := txn.NewIterator(opts)
defer it.Close()
var count int
for it.Rewind(); it.Valid(); it.Next() {
count++
item := it.Item()
require.Equal(t, []byte("answer1"), item.Key())
}
require.Equal(t, 1, count)
return nil
})
require.NoError(t, err)
})
}
func TestExpiryImproperDBClose(t *testing.T) {
testReplay := func(opt Options) {
// L0 compaction doesn't affect the test in any way. It is set to allow
// graceful shutdown of db0.
db0, err := Open(opt.WithCompactL0OnClose(false))
require.NoError(t, err)
dur := 1 * time.Hour
expiryTime := uint64(time.Now().Add(dur).Unix())
err = db0.Update(func(txn *Txn) error {
err = txn.SetEntry(NewEntry([]byte("test_key"), []byte("test_value")).WithTTL(dur))
require.NoError(t, err)
return nil
})
require.NoError(t, err)
// Simulate a crash by not closing db0, but releasing the locks.
if db0.dirLockGuard != nil {
require.NoError(t, db0.dirLockGuard.release())
db0.dirLockGuard = nil
}
if db0.valueDirGuard != nil {
require.NoError(t, db0.valueDirGuard.release())
db0.valueDirGuard = nil
}
require.NoError(t, db0.Close())
db1, err := Open(opt)
require.NoError(t, err)
err = db1.View(func(txn *Txn) error {
itm, err := txn.Get([]byte("test_key"))
require.NoError(t, err)
require.True(t, expiryTime <= itm.ExpiresAt() && itm.ExpiresAt() <= uint64(time.Now().Add(dur).Unix()),
"expiry time of entry is invalid")
return nil
})
require.NoError(t, err)
require.NoError(t, db1.Close())
}
t.Run("Test plain text", func(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := getTestOptions(dir)
testReplay(opt)
})
t.Run("Test encryption", func(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := getTestOptions(dir)
key := make([]byte, 32)
_, err = rand.Read(key)
require.NoError(t, err)
opt.EncryptionKey = key
opt.BlockCacheSize = 10 << 20
opt.IndexCacheSize = 10 << 20
testReplay(opt)
})
}
func randBytes(n int) []byte {
recv := make([]byte, n)
in, err := rand.Read(recv)
if err != nil {
panic(err)
}
return recv[:in]
}
var benchmarkData = []struct {
key, value []byte
success bool // represent if KV should be inserted successfully or not
}{
{randBytes(100), nil, true},
{randBytes(1000), []byte("foo"), true},
{[]byte("foo"), randBytes(1000), true},
{[]byte(""), randBytes(1000), false},
{nil, randBytes(1000000), false},
{randBytes(100000), nil, false},
{randBytes(1000000), nil, false},
}
func TestLargeKeys(t *testing.T) {
test := func(t *testing.T, opt Options) {
db, err := Open(opt)
require.NoError(t, err)
for i := 0; i < 1000; i++ {
tx := db.NewTransaction(true)
for _, kv := range benchmarkData {
k := make([]byte, len(kv.key))
copy(k, kv.key)
v := make([]byte, len(kv.value))
copy(v, kv.value)
if err := tx.SetEntry(NewEntry(k, v)); err != nil {
// check is success should be true
if kv.success {
t.Fatalf("failed with: %s", err)
}
} else if !kv.success {
t.Fatal("insertion should fail")
}
}
if err := tx.Commit(); err != nil {
t.Fatalf("#%d: batchSet err: %v", i, err)
}
}
require.NoError(t, db.Close())
}
t.Run("disk mode", func(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := DefaultOptions(dir).WithValueLogFileSize(1024 * 1024 * 1024)
test(t, opt)
})
t.Run("InMemory mode", func(t *testing.T) {
opt := DefaultOptions("").WithValueLogFileSize(1024 * 1024 * 1024)
opt.InMemory = true
test(t, opt)
})
}
func TestCreateDirs(t *testing.T) {
dir, err := os.MkdirTemp("", "parent")
require.NoError(t, err)
defer removeDir(dir)
db, err := Open(DefaultOptions(filepath.Join(dir, "badger")))
require.NoError(t, err)
require.NoError(t, db.Close())
_, err = os.Stat(dir)
require.NoError(t, err)
}
func TestGetSetDeadlock(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
fmt.Println(dir)
require.NoError(t, err)
defer removeDir(dir)
db, err := Open(DefaultOptions(dir).WithValueLogFileSize(1 << 20))
require.NoError(t, err)
defer func() { require.NoError(t, db.Close()) }()
val := make([]byte, 1<<19)
key := []byte("key1")
require.NoError(t, db.Update(func(txn *Txn) error {
rand.Read(val)
require.NoError(t, txn.SetEntry(NewEntry(key, val)))
return nil
}))
timeout, done := time.After(10*time.Second), make(chan bool)
go func() {
require.NoError(t, db.Update(func(txn *Txn) error {
item, err := txn.Get(key)
require.NoError(t, err)
err = item.Value(nil) // This take a RLock on file
require.NoError(t, err)
rand.Read(val)
require.NoError(t, txn.SetEntry(NewEntry(key, val)))
require.NoError(t, txn.SetEntry(NewEntry([]byte("key2"), val)))
return nil
}))
done <- true
}()
select {
case <-timeout:
t.Fatal("db.Update did not finish within 10s, assuming deadlock.")
case <-done:
t.Log("db.Update finished.")
}
}
func TestWriteDeadlock(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
db, err := Open(DefaultOptions(dir).WithValueLogFileSize(10 << 20))
require.NoError(t, err)
defer func() { require.NoError(t, db.Close()) }()
print := func(count *int) {
*count++
if *count%100 == 0 {
fmt.Printf("%05d\r", *count)
}
}
var count int
val := make([]byte, 10000)
require.NoError(t, db.Update(func(txn *Txn) error {
for i := 0; i < 1000; i++ {
key := fmt.Sprintf("%d", i)
rand.Read(val)
require.NoError(t, txn.SetEntry(NewEntry([]byte(key), val)))
print(&count)
}
return nil
}))
count = 0
fmt.Println("\nWrites done. Iteration and updates starting...")
err = db.Update(func(txn *Txn) error {
opt := DefaultIteratorOptions
opt.PrefetchValues = false
it := txn.NewIterator(opt)
defer it.Close()
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
// Using Value() would cause deadlock.
// item.Value()
out, err := item.ValueCopy(nil)
require.NoError(t, err)
require.Equal(t, len(val), len(out))
key := y.Copy(item.Key())
rand.Read(val)
require.NoError(t, txn.SetEntry(NewEntry(key, val)))
print(&count)
}
return nil
})
require.NoError(t, err)
}
func TestSequence(t *testing.T) {
key0 := []byte("seq0")
key1 := []byte("seq1")
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
seq0, err := db.GetSequence(key0, 10)
require.NoError(t, err)
seq1, err := db.GetSequence(key1, 100)
require.NoError(t, err)
for i := uint64(0); i < uint64(105); i++ {
num, err := seq0.Next()
require.NoError(t, err)
require.Equal(t, i, num)
num, err = seq1.Next()
require.NoError(t, err)
require.Equal(t, i, num)
}
err = db.View(func(txn *Txn) error {
item, err := txn.Get(key0)
if err != nil {
return err
}
var num0 uint64
if err := item.Value(func(val []byte) error {
num0 = binary.BigEndian.Uint64(val)
return nil
}); err != nil {
return err
}
require.Equal(t, uint64(110), num0)
item, err = txn.Get(key1)
if err != nil {
return err
}
var num1 uint64
if err := item.Value(func(val []byte) error {
num1 = binary.BigEndian.Uint64(val)
return nil
}); err != nil {
return err
}
require.Equal(t, uint64(200), num1)
return nil
})
require.NoError(t, err)
})
}
func TestSequence_Release(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
// get sequence, use once and release
key := []byte("key")
seq, err := db.GetSequence(key, 1000)
require.NoError(t, err)
num, err := seq.Next()
require.NoError(t, err)
require.Equal(t, uint64(0), num)
require.NoError(t, seq.Release())
// we used up 0 and 1 should be stored now
err = db.View(func(txn *Txn) error {
item, err := txn.Get(key)
if err != nil {
return err
}
val, err := item.ValueCopy(nil)
if err != nil {
return err
}
require.Equal(t, num+1, binary.BigEndian.Uint64(val))
return nil
})
require.NoError(t, err)
// using it again will lease 1+1000
num, err = seq.Next()
require.NoError(t, err)
require.Equal(t, uint64(1), num)
err = db.View(func(txn *Txn) error {
item, err := txn.Get(key)
if err != nil {
return err
}
val, err := item.ValueCopy(nil)
if err != nil {
return err
}
require.Equal(t, uint64(1001), binary.BigEndian.Uint64(val))
return nil
})
require.NoError(t, err)
})
}
func TestTestSequence2(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
key := []byte("key")
seq1, err := db.GetSequence(key, 2)
require.NoError(t, err)
seq2, err := db.GetSequence(key, 2)
require.NoError(t, err)
num, err := seq2.Next()
require.NoError(t, err)
require.Equal(t, uint64(2), num)
require.NoError(t, seq2.Release())
require.NoError(t, seq1.Release())
seq3, err := db.GetSequence(key, 2)
require.NoError(t, err)
for i := 0; i < 5; i++ {
num2, err := seq3.Next()
require.NoError(t, err)
require.Equal(t, uint64(i)+3, num2)
}
require.NoError(t, seq3.Release())
})
}
func TestReadOnly(t *testing.T) {
t.Skipf("TODO: ReadOnly needs truncation, so this fails")
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opts := getTestOptions(dir)
// Create the DB
db, err := Open(opts)
require.NoError(t, err)
for i := 0; i < 10000; i++ {
txnSet(t, db, []byte(fmt.Sprintf("key%d", i)), []byte(fmt.Sprintf("value%d", i)), 0x00)
}
// Attempt a read-only open while it's open read-write.
opts.ReadOnly = true
_, err = Open(opts)
require.Error(t, err)
if err == ErrWindowsNotSupported {
require.NoError(t, db.Close())
return
}
require.Contains(t, err.Error(), "Another process is using this Badger database")
db.Close()
// Open one read-only
opts.ReadOnly = true
kv1, err := Open(opts)
require.NoError(t, err)
defer kv1.Close()
// Open another read-only
kv2, err := Open(opts)
require.NoError(t, err)
defer kv2.Close()
// Attempt a read-write open while it's open for read-only
opts.ReadOnly = false
_, err = Open(opts)
require.Error(t, err)
require.Contains(t, err.Error(), "Another process is using this Badger database")
// Get a thing from the DB
txn1 := kv1.NewTransaction(true)
v1, err := txn1.Get([]byte("key1"))
require.NoError(t, err)
b1, err := v1.ValueCopy(nil)
require.NoError(t, err)
require.Equal(t, b1, []byte("value1"))
err = txn1.Commit()
require.NoError(t, err)
// Get a thing from the DB via the other connection
txn2 := kv2.NewTransaction(true)
v2, err := txn2.Get([]byte("key2000"))
require.NoError(t, err)
b2, err := v2.ValueCopy(nil)
require.NoError(t, err)
require.Equal(t, b2, []byte("value2000"))
err = txn2.Commit()
require.NoError(t, err)
// Attempt to set a value on a read-only connection
txn := kv1.NewTransaction(true)
err = txn.SetEntry(NewEntry([]byte("key"), []byte("value")))
require.Error(t, err)
require.Contains(t, err.Error(), "No sets or deletes are allowed in a read-only transaction")
err = txn.Commit()
require.NoError(t, err)
}
func TestLSMOnly(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opts := LSMOnlyOptions(dir)
dopts := DefaultOptions(dir)
dopts.ValueThreshold = 1 << 21
_, err = Open(dopts)
require.Contains(t, err.Error(), "Invalid ValueThreshold")
// Also test for error, when ValueThresholdSize is greater than maxBatchSize.
dopts.ValueThreshold = LSMOnlyOptions(dir).ValueThreshold
// maxBatchSize is calculated from BaseTableSize.
dopts.MemTableSize = LSMOnlyOptions(dir).ValueThreshold
_, err = Open(dopts)
require.Error(t, err, "db creation should have been failed")
require.Contains(t, err.Error(),
fmt.Sprintf("Valuethreshold %d greater than max batch size", dopts.ValueThreshold))
opts.ValueLogMaxEntries = 100
db, err := Open(opts)
require.NoError(t, err)
value := make([]byte, 128)
_, err = rand.Read(value)
for i := 0; i < 500; i++ {
require.NoError(t, err)
txnSet(t, db, []byte(fmt.Sprintf("key%d", i)), value, 0x00)
}
require.NoError(t, db.Close())
}
// This test function is doing some intricate sorcery.
func TestMinReadTs(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
for i := 0; i < 10; i++ {
require.NoError(t, db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry([]byte("x"), []byte("y")))
}))
}
time.Sleep(time.Millisecond)
readTxn0 := db.NewTransaction(false)
require.Equal(t, uint64(10), readTxn0.readTs)
min := db.orc.readMark.DoneUntil()
require.Equal(t, uint64(9), min)
readTxn := db.NewTransaction(false)
for i := 0; i < 10; i++ {
require.NoError(t, db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry([]byte("x"), []byte("y")))
}))
}
require.Equal(t, uint64(20), db.orc.readTs())
time.Sleep(time.Millisecond)
require.Equal(t, min, db.orc.readMark.DoneUntil())
readTxn0.Discard()
readTxn.Discard()
time.Sleep(time.Millisecond)
require.Equal(t, uint64(19), db.orc.readMark.DoneUntil())
db.orc.readMark.Done(uint64(20)) // Because we called readTs.
for i := 0; i < 10; i++ {
require.NoError(t, db.View(func(txn *Txn) error {
return nil
}))
}
time.Sleep(time.Millisecond)
require.Equal(t, uint64(20), db.orc.readMark.DoneUntil())
})
}
func TestGoroutineLeak(t *testing.T) {
if !*manual {
t.Skip("Skipping test meant to be run manually.")
return
}
test := func(t *testing.T, opt *Options) {
time.Sleep(1 * time.Second)
before := runtime.NumGoroutine()
t.Logf("Num go: %d", before)
for i := 0; i < 12; i++ {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
updated := false
ctx, cancel := context.WithCancel(context.Background())
var wg sync.WaitGroup
wg.Add(1)
go func() {
match := pb.Match{Prefix: []byte("key"), IgnoreBytes: ""}
err := db.Subscribe(ctx, func(kvs *pb.KVList) error {
require.Equal(t, []byte("value"), kvs.Kv[0].GetValue())
updated = true
wg.Done()
return nil
}, []pb.Match{match})
if err != nil {
require.Equal(t, err.Error(), context.Canceled.Error())
}
}()
// Wait for the go routine to be scheduled.
time.Sleep(time.Second)
err := db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry([]byte("key"), []byte("value")))
})
require.NoError(t, err)
wg.Wait()
cancel()
require.Equal(t, true, updated)
})
}
time.Sleep(2 * time.Second)
require.Equal(t, before, runtime.NumGoroutine())
}
t.Run("disk mode", func(t *testing.T) {
test(t, nil)
})
t.Run("InMemory mode", func(t *testing.T) {
opt := DefaultOptions("").WithInMemory(true)
test(t, &opt)
})
}
func ExampleOpen() {
dir, err := os.MkdirTemp("", "badger-test")
if err != nil {
panic(err)
}
defer removeDir(dir)
db, err := Open(DefaultOptions(dir))
if err != nil {
panic(err)
}
defer func() { y.Check(db.Close()) }()
err = db.View(func(txn *Txn) error {
_, err := txn.Get([]byte("key"))
// We expect ErrKeyNotFound
fmt.Println(err)
return nil
})
if err != nil {
panic(err)
}
txn := db.NewTransaction(true) // Read-write txn
err = txn.SetEntry(NewEntry([]byte("key"), []byte("value")))
if err != nil {
panic(err)
}
err = txn.Commit()
if err != nil {
panic(err)
}
err = db.View(func(txn *Txn) error {
item, err := txn.Get([]byte("key"))
if err != nil {
return err
}
val, err := item.ValueCopy(nil)
if err != nil {
return err
}
fmt.Printf("%s\n", string(val))
return nil
})
if err != nil {
panic(err)
}
// Output:
// Key not found
// value
}
func ExampleTxn_NewIterator() {
dir, err := os.MkdirTemp("", "badger-test")
if err != nil {
panic(err)
}
defer removeDir(dir)
db, err := Open(DefaultOptions(dir))
if err != nil {
panic(err)
}
defer func() { y.Check(db.Close()) }()
bkey := func(i int) []byte {
return []byte(fmt.Sprintf("%09d", i))
}
bval := func(i int) []byte {
return []byte(fmt.Sprintf("%025d", i))
}
txn := db.NewTransaction(true)
// Fill in 1000 items
n := 1000
for i := 0; i < n; i++ {
err := txn.SetEntry(NewEntry(bkey(i), bval(i)))
if err != nil {
panic(err)
}
}
if err := txn.Commit(); err != nil {
panic(err)
}
opt := DefaultIteratorOptions
opt.PrefetchSize = 10
// Iterate over 1000 items
var count int
err = db.View(func(txn *Txn) error {
it := txn.NewIterator(opt)
defer it.Close()
for it.Rewind(); it.Valid(); it.Next() {
count++
}
return nil
})
if err != nil {
panic(err)
}
fmt.Printf("Counted %d elements", count)
// Output:
// Counted 1000 elements
}
func TestSyncForRace(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
db, err := Open(DefaultOptions(dir).WithSyncWrites(false))
require.NoError(t, err)
defer func() { require.NoError(t, db.Close()) }()
closeChan := make(chan struct{})
doneChan := make(chan struct{})
go func() {
ticker := time.NewTicker(100 * time.Microsecond)
for {
select {
case <-ticker.C:
if err := db.Sync(); err != nil {
require.NoError(t, err)
}
db.opt.Debugf("Sync Iteration completed")
case <-closeChan:
close(doneChan)
return
}
}
}()
sz := 128 << 10 // 5 entries per value log file.
v := make([]byte, sz)
rand.Read(v[:rand.Intn(sz)])
txn := db.NewTransaction(true)
for i := 0; i < 10000; i++ {
require.NoError(t, txn.SetEntry(NewEntry([]byte(fmt.Sprintf("key%d", i)), v)))
if i%3 == 0 {
require.NoError(t, txn.Commit())
txn = db.NewTransaction(true)
}
if i%100 == 0 {
db.opt.Debugf("next 100 entries added to DB")
}
}
require.NoError(t, txn.Commit())
close(closeChan)
<-doneChan
}
func TestSyncForNoErrors(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
db, err := Open(DefaultOptions(dir).WithSyncWrites(false))
require.NoError(t, err)
defer func() { require.NoError(t, db.Close()) }()
txn := db.NewTransaction(true)
for i := 0; i < 10; i++ {
require.NoError(
t,
txn.SetEntry(NewEntry(
[]byte(fmt.Sprintf("key%d", i)),
[]byte(fmt.Sprintf("value%d", i)),
)),
)
}
require.NoError(t, txn.Commit())
if err := db.Sync(); err != nil {
require.NoError(t, err)
}
}
func TestSyncForReadingTheEntriesThatWereSynced(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
db, err := Open(DefaultOptions(dir).WithSyncWrites(false))
require.NoError(t, err)
defer func() { require.NoError(t, db.Close()) }()
txn := db.NewTransaction(true)
for i := 0; i < 10; i++ {
require.NoError(
t,
txn.SetEntry(NewEntry(
[]byte(fmt.Sprintf("key%d", i)),
[]byte(fmt.Sprintf("value%d", i)),
)),
)
}
require.NoError(t, txn.Commit())
if err := db.Sync(); err != nil {
require.NoError(t, err)
}
readOnlyTxn := db.NewTransaction(false)
for i := 0; i < 10; i++ {
item, err := readOnlyTxn.Get([]byte(fmt.Sprintf("key%d", i)))
require.NoError(t, err)
value := getItemValue(t, item)
require.Equal(t, []byte(fmt.Sprintf("value%d", i)), value)
}
}
func TestForceFlushMemtable(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err, "temp dir for badger could not be created")
ops := getTestOptions(dir)
ops.ValueLogMaxEntries = 1
db, err := Open(ops)
require.NoError(t, err, "error while opening db")
defer func() { require.NoError(t, db.Close()) }()
for i := 0; i < 3; i++ {
err = db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry([]byte(fmt.Sprintf("key-%d", i)),
[]byte(fmt.Sprintf("value-%d", i))))
})
require.NoError(t, err, "unable to set key and value")
}
time.Sleep(1 * time.Second)
// We want to make sure that memtable is flushed on disk. While flushing memtable to disk,
// latest head is also stored in it. Hence we will try to read head from disk. To make sure
// this. we will truncate all memtables.
db.lock.Lock()
db.mt.DecrRef()
for _, mt := range db.imm {
mt.DecrRef()
}
db.imm = db.imm[:0]
db.mt, err = db.newMemTable()
require.NoError(t, err)
db.lock.Unlock()
// Since we are inserting 3 entries and ValueLogMaxEntries is 1, there will be 3 rotation.
require.True(t, db.nextMemFid == 3,
fmt.Sprintf("expected fid: %d, actual fid: %d", 2, db.nextMemFid))
}
func TestVerifyChecksum(t *testing.T) {
testVerfiyCheckSum := func(t *testing.T, opt Options) {
path, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer os.Remove(path)
opt.ValueDir = path
opt.Dir = path
// use stream write for writing.
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
value := make([]byte, 32)
y.Check2(rand.Read(value))
st := 0
buf := z.NewBuffer(10<<20, "test")
defer func() { require.NoError(t, buf.Release()) }()
for i := 0; i < 1000; i++ {
key := make([]byte, 8)
binary.BigEndian.PutUint64(key, uint64(i))
KVToBuffer(&pb.KV{
Key: key,
Value: value,
StreamId: uint32(st),
Version: 1,
}, buf)
if i%100 == 0 {
st++
}
}
sw := db.NewStreamWriter()
require.NoError(t, sw.Prepare(), "sw.Prepare() failed")
require.NoError(t, sw.Write(buf), "sw.Write() failed")
require.NoError(t, sw.Flush(), "sw.Flush() failed")
require.NoError(t, db.VerifyChecksum(), "checksum verification failed for DB")
})
}
t.Run("Testing Verify Checksum without encryption", func(t *testing.T) {
testVerfiyCheckSum(t, getTestOptions(""))
})
t.Run("Testing Verify Checksum with Encryption", func(t *testing.T) {
key := make([]byte, 32)
_, err := rand.Read(key)
require.NoError(t, err)
opt := getTestOptions("")
opt.EncryptionKey = key
opt.BlockCacheSize = 1 << 20
opt.IndexCacheSize = 1 << 20
testVerfiyCheckSum(t, opt)
})
}
func TestMain(m *testing.M) {
flag.Parse()
os.Exit(m.Run())
}
func removeDir(dir string) {
if err := os.RemoveAll(dir); err != nil {
panic(err)
}
}
func TestWriteInemory(t *testing.T) {
opt := DefaultOptions("").WithInMemory(true)
db, err := Open(opt)
require.NoError(t, err)
defer func() {
require.NoError(t, db.Close())
}()
for i := 0; i < 100; i++ {
txnSet(t, db, []byte(fmt.Sprintf("key%d", i)), []byte(fmt.Sprintf("val%d", i)), 0x00)
}
err = db.View(func(txn *Txn) error {
for j := 0; j < 100; j++ {
item, err := txn.Get([]byte(fmt.Sprintf("key%d", j)))
require.NoError(t, err)
expected := []byte(fmt.Sprintf("val%d", j))
require.NoError(t, item.Value(func(val []byte) error {
require.Equal(t, expected, val,
"Invalid value for key %q. expected: %q, actual: %q",
item.Key(), expected, val)
return nil
}))
}
return nil
})
require.NoError(t, err)
}
func TestMinCacheSize(t *testing.T) {
opt := DefaultOptions("").
WithInMemory(true).
WithIndexCacheSize(16).
WithBlockCacheSize(16)
db, err := Open(opt)
require.NoError(t, err)
defer func() {
require.NoError(t, db.Close())
}()
}
func TestUpdateMaxCost(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err, "temp dir for badger could not be created")
defer os.RemoveAll(dir)
ops := getTestOptions(dir).
WithBlockCacheSize(1 << 20).
WithIndexCacheSize(2 << 20)
db, err := Open(ops)
require.NoError(t, err)
cost, err := db.CacheMaxCost(BlockCache, -1)
require.NoError(t, err)
require.Equal(t, int64(1<<20), cost)
cost, err = db.CacheMaxCost(IndexCache, -1)
require.NoError(t, err)
require.Equal(t, int64(2<<20), cost)
_, err = db.CacheMaxCost(BlockCache, 2<<20)
require.NoError(t, err)
cost, err = db.CacheMaxCost(BlockCache, -1)
require.NoError(t, err)
require.Equal(t, int64(2<<20), cost)
_, err = db.CacheMaxCost(IndexCache, 4<<20)
require.NoError(t, err)
cost, err = db.CacheMaxCost(IndexCache, -1)
require.NoError(t, err)
require.Equal(t, int64(4<<20), cost)
}
func TestOpenDBReadOnly(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer os.RemoveAll(dir)
mp := make(map[string][]byte)
ops := getTestOptions(dir)
ops.ReadOnly = false
db, err := Open(ops)
require.NoError(t, err)
// Add bunch of entries that don't go into value log.
require.NoError(t, db.Update(func(txn *Txn) error {
val := make([]byte, 10)
rand.Read(val)
for i := 0; i < 10; i++ {
key := fmt.Sprintf("key-%05d", i)
require.NoError(t, txn.Set([]byte(key), val))
mp[key] = val
}
return nil
}))
require.NoError(t, db.Close())
ops.ReadOnly = true
db, err = Open(ops)
require.NoError(t, err)
require.NoError(t, db.Close())
db, err = Open(ops)
require.NoError(t, err)
var count int
read := func() {
count = 0
require.NoError(t, db.View(func(txn *Txn) error {
it := txn.NewIterator(DefaultIteratorOptions)
defer it.Close()
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
require.NoError(t, item.Value(func(val []byte) error {
require.Equal(t, mp[string(item.Key())], val)
return nil
}))
count++
}
return nil
}))
}
read()
require.Equal(t, 10, count)
require.NoError(t, db.Close())
ops.ReadOnly = false
db, err = Open(ops)
require.NoError(t, err)
// Add bunch of entries that go into value log.
require.NoError(t, db.Update(func(txn *Txn) error {
require.Greater(t, db.valueThreshold(), int64(10))
val := make([]byte, db.valueThreshold()+10)
rand.Read(val)
for i := 0; i < 10; i++ {
key := fmt.Sprintf("KEY-%05d", i)
require.NoError(t, txn.Set([]byte(key), val))
mp[key] = val
}
return nil
}))
require.NoError(t, db.Close())
ops.ReadOnly = true
db, err = Open(ops)
require.NoError(t, err)
read()
require.Equal(t, 20, count)
require.NoError(t, db.Close())
}
func TestBannedPrefixes(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err, "temp dir for badger could not be created")
defer os.RemoveAll(dir)
opt := getTestOptions(dir).WithNamespaceOffset(3)
// All values go into vlog files. This is for checking if banned keys are properly decoded on DB
// restart.
opt.ValueThreshold = 0
opt.ValueLogMaxEntries = 2
// We store the uint64 namespace at idx=3, so first 3 bytes are insignificant to us.
initialBytes := make([]byte, opt.NamespaceOffset)
db, err := Open(opt)
require.NoError(t, err)
require.Equal(t, 1, len(db.vlog.filesMap))
var keys [][]byte
var allPrefixes []uint64 = []uint64{1234, 3456, 5678, 7890, 901234}
for _, p := range allPrefixes {
prefix := y.U64ToBytes(p)
for i := 0; i < 10; i++ {
// We store the uint64 namespace at idx=3, so first 3 bytes are insignificant to us.
key := []byte(fmt.Sprintf("%s%s-key%02d", initialBytes, prefix, i))
keys = append(keys, key)
}
}
bannedPrefixes := make(map[uint64]struct{})
isBanned := func(key []byte) bool {
prefix := y.BytesToU64(key[3:])
if _, ok := bannedPrefixes[prefix]; ok {
return true
}
return false
}
validate := func() {
// Validate read/write.
for _, key := range keys {
txn := db.NewTransaction(true)
_, rerr := txn.Get(key)
werr := txn.Set(key, []byte("value"))
txn.Discard()
if isBanned(key) {
require.Equal(t, ErrBannedKey, rerr)
require.Equal(t, ErrBannedKey, werr)
} else {
require.NoError(t, rerr)
require.NoError(t, werr)
}
}
}
for _, key := range keys {
require.NoError(t, db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry(key, []byte("value")))
}))
}
validate()
// Ban a couple of prefix and validate that we should not be able to read/write them.
require.NoError(t, db.BanNamespace(1234))
bannedPrefixes[1234] = struct{}{}
validate()
require.NoError(t, db.BanNamespace(5678))
bannedPrefixes[5678] = struct{}{}
validate()
require.Greater(t, len(db.vlog.filesMap), 1)
require.NoError(t, db.Close())
db, err = Open(opt)
require.NoError(t, err)
validate()
require.NoError(t, db.Close())
}
// Tests that the iterator skips the banned prefixes. Sets keys with multiple versions in
// different namespaces and maintains a sorted list of those keys in-memory.
// Then, ban few prefixes and iterate over the DB and match it with the corresponding keys from the
// in-memory list. Simulate the skipping in in-memory list as well.
func TestIterateWithBanned(t *testing.T) {
opt := DefaultOptions("").WithNamespaceOffset(3)
opt.NumVersionsToKeep = math.MaxInt64
// We store the uint64 namespace at idx=3, so first 3 bytes are insignificant to us.
initialBytes := make([]byte, opt.NamespaceOffset)
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
bkey := func(prefix uint64, i int) []byte {
return []byte(fmt.Sprintf("%s%s-%04d", initialBytes, y.U64ToBytes(prefix), i))
}
N := 100
V := 3
// Generate 26*N keys, each with V versions (versions set by txnSet())
var keys [][]byte
for i := 'a'; i <= 'z'; i++ {
for j := 0; j < N; j++ {
for v := 0; v < V; v++ {
keys = append(keys, bkey(uint64(i*1000), j))
}
}
}
for _, key := range keys {
txnSet(t, db, key, key, 0)
}
// Validate that we don't see the banned keys in iterating.
// Pass it the iterator options, idx to start from in the in-memory list, and the number of
// keys we expect to see through iteration.
validate := func(iopts IteratorOptions, idx, expected int) {
txn := db.NewTransaction(false)
defer txn.Discard()
itr := txn.NewIterator(iopts)
defer itr.Close()
incIdx := func() {
n := 1
// If AllVersions is set, then we need to skip V keys.
if !iopts.AllVersions {
n *= V
}
// If Reverse iterating, then decrement the index of in-memory list.
if iopts.Reverse {
idx -= n
} else {
idx += n
}
}
count := 0
for itr.Seek(itr.opt.Prefix); itr.Valid(); itr.Next() {
// Iterator should skip the banned keys, so should we.
for db.isBanned(keys[idx]) != nil {
incIdx()
}
count++
require.Equalf(t, keys[idx], itr.Item().Key(), "count:%d", count)
incIdx()
}
require.Equal(t, expected, count)
}
getIterablePrefix := func(i int) []byte {
return []byte(fmt.Sprintf("%s%s", initialBytes, y.U64ToBytes(uint64(i*1000))))
}
validate(IteratorOptions{}, 0, 26*N)
validate(IteratorOptions{Reverse: true, AllVersions: true}, 26*N*V-1, 26*N*V)
validate(IteratorOptions{Prefix: getIterablePrefix('f')}, 5*N*V, N)
require.NoError(t, db.BanNamespace(uint64('a'*1000)))
validate(IteratorOptions{}, 1*N*V, 25*N)
validate(IteratorOptions{AllVersions: true}, 1*N*V, 25*N*V)
validate(IteratorOptions{Reverse: true, AllVersions: true}, 26*N*V-1, 25*N*V)
require.NoError(t, db.BanNamespace(uint64('b'*1000)))
validate(IteratorOptions{}, 2*N*V, 24*N)
validate(IteratorOptions{AllVersions: true}, 2*N*V, 24*N*V)
require.NoError(t, db.BanNamespace(uint64('d'*1000)))
validate(IteratorOptions{}, 2*N*V, 23*N)
validate(IteratorOptions{AllVersions: true}, 2*N*V, 23*N*V)
validate(IteratorOptions{Prefix: getIterablePrefix('f')}, 5*N*V, N)
validate(IteratorOptions{Prefix: getIterablePrefix('f'), AllVersions: true}, 5*N*V, N*V)
require.NoError(t, db.BanNamespace(uint64('g')*1000))
validate(IteratorOptions{AllVersions: true}, 2*N*V, 22*N*V)
require.NoError(t, db.BanNamespace(uint64('r'*1000)))
validate(IteratorOptions{}, 2*N*V, 21*N)
validate(IteratorOptions{Reverse: true, AllVersions: true}, 26*N*V-1, 21*N*V)
// Iterate over the banned prefix. Passing -1 as we don't expect to access keys.
validate(IteratorOptions{Prefix: getIterablePrefix('g')}, -1, 0)
validate(IteratorOptions{Prefix: getIterablePrefix('g'), Reverse: true, AllVersions: true},
-1, 0)
require.NoError(t, db.BanNamespace(uint64('z'*1000)))
validate(IteratorOptions{}, 2*N*V, 20*N)
validate(IteratorOptions{AllVersions: true}, 2*N*V, 20*N*V)
validate(IteratorOptions{Reverse: true, AllVersions: true}, 25*N*V-1, 20*N*V)
})
}
// A basic test that checks if the DB works even if user is not using the DefaultOptions.
func TestBannedAtZeroOffset(t *testing.T) {
opt := getTestOptions("")
// When DefaultOptions is not used, NamespaceOffset will be set to 0.
opt.NamespaceOffset = 0
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
require.Equal(t, 0, db.opt.NamespaceOffset)
err := db.Update(func(txn *Txn) error {
for i := 0; i < 10; i++ {
entry := NewEntry([]byte(fmt.Sprintf("key%d", i)), []byte(fmt.Sprintf("val%d", i)))
if err := txn.SetEntry(entry); err != nil {
return err
}
}
return nil
})
require.NoError(t, err)
err = db.View(func(txn *Txn) error {
for i := 0; i < 10; i++ {
item, err := txn.Get([]byte(fmt.Sprintf("key%d", i)))
if err != nil {
return err
}
expected := []byte(fmt.Sprintf("val%d", i))
if err := item.Value(func(val []byte) error {
require.Equal(t, expected, val,
"Invalid value for key %q. expected: %q, actual: %q",
item.Key(), expected, val)
return nil
}); err != nil {
return err
}
}
return nil
})
require.NoError(t, err)
})
}
func TestCompactL0OnClose(t *testing.T) {
opt := getTestOptions("")
opt.CompactL0OnClose = true
opt.ValueThreshold = 1 // Every value goes to value log
opt.NumVersionsToKeep = 1
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
var keys [][]byte
val := make([]byte, 1<<12)
for i := 0; i < 10; i++ {
key := make([]byte, 40)
_, err := rand.Read(key)
require.NoError(t, err)
keys = append(keys, key)
err = db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry(key, val))
})
require.NoError(t, err)
}
for _, key := range keys {
err := db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry(key, val))
})
require.NoError(t, err)
}
})
}
func TestCloseDBWhileReading(t *testing.T) {
dir := t.TempDir()
db, err := Open(DefaultOptions(dir))
require.NoError(t, err)
key := []byte("key")
err = db.Update(func(txn *Txn) error {
return txn.Set(key, []byte("value"))
})
require.NoError(t, err)
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for {
err := db.View(func(txn *Txn) error {
_, err := txn.Get(key)
return err
})
if err != nil {
require.Contains(t, err.Error(), "DB Closed")
break
}
}
}()
}
time.Sleep(time.Second)
require.NoError(t, db.Close())
wg.Wait()
}
================================================
FILE: dir_aix.go
================================================
//go:build aix
// +build aix
/*
* SPDX-FileCopyrightText: © 2017-2026 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"errors"
"fmt"
"os"
"path/filepath"
"sync"
"golang.org/x/sys/unix"
"github.com/dgraph-io/badger/v4/y"
)
// AIX flock locks files, not descriptors. So, multiple descriptors cannot
// be used in the same file. The first to close removals the lock on the
// file.
type directoryLockGuard struct {
// The absolute path to our pid file.
path string
// Was this a shared lock for a read-only database?
readOnly bool
}
// AIX flocking is file x process, not fd x file x process like linux. We can
// only hold one descriptor with a lock open at any given time.
type aixFlock struct {
file *os.File
count int
readOnly bool
}
// Keep a map of locks synchronized by a mutex.
var aixFlockMap = map[string]*aixFlock{}
var aixFlockMapLock sync.Mutex
// acquireDirectoryLock gets a lock on the directory (using flock). If
// this is not read-only, it will also write our pid to
// dirPath/pidFileName for convenience.
func acquireDirectoryLock(dirPath string, pidFileName string, readOnly bool) (
*directoryLockGuard, error) {
// Convert to absolute path so that Release still works even if we do an unbalanced
// chdir in the meantime.
absPidFilePath, err := filepath.Abs(filepath.Join(dirPath, pidFileName))
if err != nil {
return nil, y.Wrapf(err, "cannot get absolute path for pid lock file")
}
aixFlockMapLock.Lock()
defer aixFlockMapLock.Unlock()
lg := &directoryLockGuard{absPidFilePath, readOnly}
if lock, fnd := aixFlockMap[absPidFilePath]; fnd {
if !readOnly || lock.readOnly != readOnly {
return nil, fmt.Errorf(
"Cannot acquire directory lock on %q. Another process is using this Badger database.", dirPath)
}
lock.count++
} else {
// This is the first acquirer, set up a lock file and register it.
f, err := os.OpenFile(absPidFilePath, os.O_RDWR|os.O_CREATE, 0666)
if err != nil {
return nil, y.Wrapf(err, "cannot create/open pid file %q", absPidFilePath)
}
opts := unix.F_WRLCK
if readOnly {
opts = unix.F_RDLCK
}
flckt := unix.Flock_t{int16(opts), 0, 0, 0, 0, 0, 0}
err = unix.FcntlFlock(uintptr(f.Fd()), unix.F_SETLK, &flckt)
if err != nil {
f.Close()
return nil, y.Wrapf(err,
"Cannot acquire directory lock on %q. Another process is using this Badger database.", dirPath)
}
if !readOnly {
f.Truncate(0)
// Write our pid to the file.
_, err = f.Write([]byte(fmt.Sprintf("%d\n", os.Getpid())))
if err != nil {
f.Close()
return nil, y.Wrapf(err,
"Cannot write pid file %q", absPidFilePath)
}
}
aixFlockMap[absPidFilePath] = &aixFlock{f, 1, readOnly}
}
return lg, nil
}
// Release deletes the pid file and releases our lock on the directory.
func (guard *directoryLockGuard) release() error {
var err error
aixFlockMapLock.Lock()
defer aixFlockMapLock.Unlock()
if lock, fnd := aixFlockMap[guard.path]; fnd {
lock.count--
if lock.count == 0 {
if !lock.readOnly {
// Try to clear the PID if we succeed.
lock.file.Truncate(0)
os.Remove(guard.path)
}
if closeErr := lock.file.Close(); err == nil {
err = closeErr
}
delete(aixFlockMap, guard.path)
guard.path = ""
}
} else {
err = errors.New(fmt.Sprintf("unknown lock %v", guard.path))
}
return err
}
// openDir opens a directory for syncing.
func openDir(path string) (*os.File, error) { return os.Open(path) }
// When you create or delete a file, you have to ensure the directory entry for the file is synced
// in order to guarantee the file is visible (if the system crashes). (See the man page for fsync,
// or see https://github.com/coreos/etcd/issues/6368 for an example.)
func syncDir(dir string) error {
var err error
// AIX does not support fsync on a directory.
// Data durability on crash may be affected.
return err
}
================================================
FILE: dir_other.go
================================================
//go:build js || wasip1
// +build js wasip1
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"fmt"
"os"
"path/filepath"
"github.com/dgraph-io/badger/v4/y"
)
// directoryLockGuard holds a lock on a directory and a pid file inside. The pid file isn't part
// of the locking mechanism, it's just advisory.
type directoryLockGuard struct {
// File handle on the directory, which we've flocked.
f *os.File
// The absolute path to our pid file.
path string
// Was this a shared lock for a read-only database?
readOnly bool
}
// acquireDirectoryLock gets a lock on the directory (using flock). If
// this is not read-only, it will also write our pid to
// dirPath/pidFileName for convenience.
func acquireDirectoryLock(dirPath string, pidFileName string, readOnly bool) (
*directoryLockGuard, error) {
// Convert to absolute path so that Release still works even if we do an unbalanced
// chdir in the meantime.
absPidFilePath, err := filepath.Abs(filepath.Join(dirPath, pidFileName))
if err != nil {
return nil, y.Wrapf(err, "cannot get absolute path for pid lock file")
}
f, err := os.Open(dirPath)
if err != nil {
return nil, y.Wrapf(err, "cannot open directory %q", dirPath)
}
// NOTE: Here is where we would normally call flock.
// This is not supported in js / wasm, so skip it.
if !readOnly {
// Yes, we happily overwrite a pre-existing pid file. We're the
// only read-write badger process using this directory.
err = os.WriteFile(absPidFilePath, []byte(fmt.Sprintf("%d\n", os.Getpid())), 0666)
if err != nil {
f.Close()
return nil, y.Wrapf(err,
"Cannot write pid file %q", absPidFilePath)
}
}
return &directoryLockGuard{f, absPidFilePath, readOnly}, nil
}
// Release deletes the pid file and releases our lock on the directory.
func (guard *directoryLockGuard) release() error {
var err error
if !guard.readOnly {
// It's important that we remove the pid file first.
err = os.Remove(guard.path)
}
if closeErr := guard.f.Close(); err == nil {
err = closeErr
}
guard.path = ""
guard.f = nil
return err
}
// openDir opens a directory for syncing.
func openDir(path string) (*os.File, error) { return os.Open(path) }
// When you create or delete a file, you have to ensure the directory entry for the file is synced
// in order to guarantee the file is visible (if the system crashes). (See the man page for fsync,
// or see https://github.com/coreos/etcd/issues/6368 for an example.)
func syncDir(dir string) error {
f, err := openDir(dir)
if err != nil {
return y.Wrapf(err, "While opening directory: %s.", dir)
}
err = f.Sync()
closeErr := f.Close()
if err != nil {
return y.Wrapf(err, "While syncing directory: %s.", dir)
}
return y.Wrapf(closeErr, "While closing directory: %s.", dir)
}
================================================
FILE: dir_plan9.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/dgraph-io/badger/v4/y"
)
// directoryLockGuard holds a lock on a directory and a pid file inside. The pid file isn't part
// of the locking mechanism, it's just advisory.
type directoryLockGuard struct {
// File handle on the directory, which we've locked.
f *os.File
// The absolute path to our pid file.
path string
}
// acquireDirectoryLock gets a lock on the directory.
// It will also write our pid to dirPath/pidFileName for convenience.
// readOnly is not supported on Plan 9.
func acquireDirectoryLock(dirPath string, pidFileName string, readOnly bool) (
*directoryLockGuard, error) {
if readOnly {
return nil, ErrPlan9NotSupported
}
// Convert to absolute path so that Release still works even if we do an unbalanced
// chdir in the meantime.
absPidFilePath, err := filepath.Abs(filepath.Join(dirPath, pidFileName))
if err != nil {
return nil, y.Wrap(err, "cannot get absolute path for pid lock file")
}
// If the file was unpacked or created by some other program, it might not
// have the ModeExclusive bit set. Set it before we call OpenFile, so that we
// can be confident that a successful OpenFile implies exclusive use.
//
// OpenFile fails if the file ModeExclusive bit set *and* the file is already open.
// So, if the file is closed when the DB crashed, we're fine. When the process
// that was managing the DB crashes, the OS will close the file for us.
//
// This bit of code is copied from Go's lockedfile internal package:
// https://github.com/golang/go/blob/go1.15rc1/src/cmd/go/internal/lockedfile/lockedfile_plan9.go#L58
if fi, err := os.Stat(absPidFilePath); err == nil {
if fi.Mode()&os.ModeExclusive == 0 {
if err := os.Chmod(absPidFilePath, fi.Mode()|os.ModeExclusive); err != nil {
return nil, y.Wrapf(err, "could not set exclusive mode bit")
}
}
} else if !os.IsNotExist(err) {
return nil, err
}
f, err := os.OpenFile(absPidFilePath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666|os.ModeExclusive)
if err != nil {
if isLocked(err) {
return nil, y.Wrapf(err,
"Cannot open pid lock file %q. Another process is using this Badger database",
absPidFilePath)
}
return nil, y.Wrapf(err, "Cannot open pid lock file %q", absPidFilePath)
}
if _, err = fmt.Fprintf(f, "%d\n", os.Getpid()); err != nil {
f.Close()
return nil, y.Wrapf(err, "could not write pid")
}
return &directoryLockGuard{f, absPidFilePath}, nil
}
// Release deletes the pid file and releases our lock on the directory.
func (guard *directoryLockGuard) release() error {
// It's important that we remove the pid file first.
err := os.Remove(guard.path)
if closeErr := guard.f.Close(); err == nil {
err = closeErr
}
guard.path = ""
guard.f = nil
return err
}
// openDir opens a directory for syncing.
func openDir(path string) (*os.File, error) { return os.Open(path) }
// When you create or delete a file, you have to ensure the directory entry for the file is synced
// in order to guarantee the file is visible (if the system crashes). (See the man page for fsync,
// or see https://github.com/coreos/etcd/issues/6368 for an example.)
func syncDir(dir string) error {
f, err := openDir(dir)
if err != nil {
return y.Wrapf(err, "While opening directory: %s.", dir)
}
err = f.Sync()
closeErr := f.Close()
if err != nil {
return y.Wrapf(err, "While syncing directory: %s.", dir)
}
return y.Wrapf(closeErr, "While closing directory: %s.", dir)
}
// Opening an exclusive-use file returns an error.
// The expected error strings are:
//
// - "open/create -- file is locked" (cwfs, kfs)
// - "exclusive lock" (fossil)
// - "exclusive use file already open" (ramfs)
//
// See https://github.com/golang/go/blob/go1.15rc1/src/cmd/go/internal/lockedfile/lockedfile_plan9.go#L16
var lockedErrStrings = [...]string{
"file is locked",
"exclusive lock",
"exclusive use file already open",
}
// Even though plan9 doesn't support the Lock/RLock/Unlock functions to
// manipulate already-open files, IsLocked is still meaningful: os.OpenFile
// itself may return errors that indicate that a file with the ModeExclusive bit
// set is already open.
func isLocked(err error) bool {
s := err.Error()
for _, frag := range lockedErrStrings {
if strings.Contains(s, frag) {
return true
}
}
return false
}
================================================
FILE: dir_unix.go
================================================
//go:build !windows && !plan9 && !js && !wasip1 && !aix
// +build !windows,!plan9,!js,!wasip1,!aix
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"fmt"
"os"
"path/filepath"
"golang.org/x/sys/unix"
"github.com/dgraph-io/badger/v4/y"
)
// directoryLockGuard holds a lock on a directory and a pid file inside. The pid file isn't part
// of the locking mechanism, it's just advisory.
type directoryLockGuard struct {
// File handle on the directory, which we've flocked.
f *os.File
// The absolute path to our pid file.
path string
// Was this a shared lock for a read-only database?
readOnly bool
}
// acquireDirectoryLock gets a lock on the directory (using flock). If
// this is not read-only, it will also write our pid to
// dirPath/pidFileName for convenience.
func acquireDirectoryLock(dirPath string, pidFileName string, readOnly bool) (
*directoryLockGuard, error) {
// Convert to absolute path so that Release still works even if we do an unbalanced
// chdir in the meantime.
absPidFilePath, err := filepath.Abs(filepath.Join(dirPath, pidFileName))
if err != nil {
return nil, y.Wrapf(err, "cannot get absolute path for pid lock file")
}
f, err := os.Open(dirPath)
if err != nil {
return nil, y.Wrapf(err, "cannot open directory %q", dirPath)
}
opts := unix.LOCK_EX | unix.LOCK_NB
if readOnly {
opts = unix.LOCK_SH | unix.LOCK_NB
}
err = unix.Flock(int(f.Fd()), opts)
if err != nil {
f.Close()
return nil, y.Wrapf(err,
"Cannot acquire directory lock on %q. Another process is using this Badger database.",
dirPath)
}
if !readOnly {
// Yes, we happily overwrite a pre-existing pid file. We're the
// only read-write badger process using this directory.
err = os.WriteFile(absPidFilePath, []byte(fmt.Sprintf("%d\n", os.Getpid())), 0666)
if err != nil {
f.Close()
return nil, y.Wrapf(err,
"Cannot write pid file %q", absPidFilePath)
}
}
return &directoryLockGuard{f, absPidFilePath, readOnly}, nil
}
// Release deletes the pid file and releases our lock on the directory.
func (guard *directoryLockGuard) release() error {
var err error
if !guard.readOnly {
// It's important that we remove the pid file first.
err = os.Remove(guard.path)
}
if closeErr := guard.f.Close(); err == nil {
err = closeErr
}
guard.path = ""
guard.f = nil
return err
}
// openDir opens a directory for syncing.
func openDir(path string) (*os.File, error) { return os.Open(path) }
// When you create or delete a file, you have to ensure the directory entry for the file is synced
// in order to guarantee the file is visible (if the system crashes). (See the man page for fsync,
// or see https://github.com/coreos/etcd/issues/6368 for an example.)
func syncDir(dir string) error {
f, err := openDir(dir)
if err != nil {
return y.Wrapf(err, "While opening directory: %s.", dir)
}
err = f.Sync()
closeErr := f.Close()
if err != nil {
return y.Wrapf(err, "While syncing directory: %s.", dir)
}
return y.Wrapf(closeErr, "While closing directory: %s.", dir)
}
================================================
FILE: dir_windows.go
================================================
//go:build windows
// +build windows
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
// OpenDir opens a directory in windows with write access for syncing.
import (
"os"
"path/filepath"
"syscall"
"github.com/dgraph-io/badger/v4/y"
)
// FILE_ATTRIBUTE_TEMPORARY - A file that is being used for temporary storage.
// FILE_FLAG_DELETE_ON_CLOSE - The file is to be deleted immediately after all of its handles are
// closed, which includes the specified handle and any other open or duplicated handles.
// See: https://docs.microsoft.com/en-us/windows/desktop/FileIO/file-attribute-constants
// NOTE: Added here to avoid importing golang.org/x/sys/windows
const (
FILE_ATTRIBUTE_TEMPORARY = 0x00000100
FILE_FLAG_DELETE_ON_CLOSE = 0x04000000
)
func openDir(path string) (*os.File, error) {
fd, err := openDirWin(path)
if err != nil {
return nil, err
}
return os.NewFile(uintptr(fd), path), nil
}
func openDirWin(path string) (fd syscall.Handle, err error) {
if len(path) == 0 {
return syscall.InvalidHandle, syscall.ERROR_FILE_NOT_FOUND
}
pathp, err := syscall.UTF16PtrFromString(path)
if err != nil {
return syscall.InvalidHandle, err
}
access := uint32(syscall.GENERIC_READ | syscall.GENERIC_WRITE)
sharemode := uint32(syscall.FILE_SHARE_READ | syscall.FILE_SHARE_WRITE)
createmode := uint32(syscall.OPEN_EXISTING)
fl := uint32(syscall.FILE_FLAG_BACKUP_SEMANTICS)
return syscall.CreateFile(pathp, access, sharemode, nil, createmode, fl, 0)
}
// DirectoryLockGuard holds a lock on the directory.
type directoryLockGuard struct {
h syscall.Handle
path string
}
// AcquireDirectoryLock acquires exclusive access to a directory.
func acquireDirectoryLock(dirPath string, pidFileName string, readOnly bool) (*directoryLockGuard, error) {
if readOnly {
return nil, ErrWindowsNotSupported
}
// Convert to absolute path so that Release still works even if we do an unbalanced
// chdir in the meantime.
absLockFilePath, err := filepath.Abs(filepath.Join(dirPath, pidFileName))
if err != nil {
return nil, y.Wrap(err, "Cannot get absolute path for pid lock file")
}
// This call creates a file handler in memory that only one process can use at a time. When
// that process ends, the file is deleted by the system.
// FILE_ATTRIBUTE_TEMPORARY is used to tell Windows to try to create the handle in memory.
// FILE_FLAG_DELETE_ON_CLOSE is not specified in syscall_windows.go but tells Windows to delete
// the file when all processes holding the handler are closed.
// XXX: this works but it's a bit clunky. i'd prefer to use LockFileEx but it needs unsafe pkg.
h, err := syscall.CreateFile(
syscall.StringToUTF16Ptr(absLockFilePath), 0, 0, nil,
syscall.OPEN_ALWAYS,
uint32(FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE),
0)
if err != nil {
return nil, y.Wrapf(err,
"Cannot create lock file %q. Another process is using this Badger database",
absLockFilePath)
}
return &directoryLockGuard{h: h, path: absLockFilePath}, nil
}
// Release removes the directory lock.
func (g *directoryLockGuard) release() error {
g.path = ""
return syscall.CloseHandle(g.h)
}
// Windows doesn't support syncing directories to the file system. See
// https://github.com/dgraph-io/badger/issues/699#issuecomment-504133587 for more details.
func syncDir(dir string) error { return nil }
================================================
FILE: discard.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"encoding/binary"
"os"
"path/filepath"
"sort"
"sync"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2/z"
)
// discardStats keeps track of the amount of data that could be discarded for
// a given logfile.
type discardStats struct {
sync.Mutex
*z.MmapFile
opt Options
nextEmptySlot int
}
const discardFname string = "DISCARD"
func InitDiscardStats(opt Options) (*discardStats, error) {
fname := filepath.Join(opt.ValueDir, discardFname)
// 1MB file can store 65.536 discard entries. Each entry is 16 bytes.
mf, err := z.OpenMmapFile(fname, os.O_CREATE|os.O_RDWR, 1<<20)
lf := &discardStats{
MmapFile: mf,
opt: opt,
}
if err == z.NewFile {
// We don't need to zero out the entire 1MB.
lf.zeroOut()
} else if err != nil {
return nil, y.Wrapf(err, "while opening file: %s\n", discardFname)
}
for slot := 0; slot < lf.maxSlot(); slot++ {
if lf.get(16*slot) == 0 {
lf.nextEmptySlot = slot
break
}
}
sort.Sort(lf)
opt.Infof("Discard stats nextEmptySlot: %d\n", lf.nextEmptySlot)
return lf, nil
}
func (lf *discardStats) Len() int {
return lf.nextEmptySlot
}
func (lf *discardStats) Less(i, j int) bool {
return lf.get(16*i) < lf.get(16*j)
}
func (lf *discardStats) Swap(i, j int) {
left := lf.Data[16*i : 16*i+16]
right := lf.Data[16*j : 16*j+16]
var tmp [16]byte
copy(tmp[:], left)
copy(left, right)
copy(right, tmp[:])
}
// offset is not slot.
func (lf *discardStats) get(offset int) uint64 {
return binary.BigEndian.Uint64(lf.Data[offset : offset+8])
}
func (lf *discardStats) set(offset int, val uint64) {
binary.BigEndian.PutUint64(lf.Data[offset:offset+8], val)
}
// zeroOut would zero out the next slot.
func (lf *discardStats) zeroOut() {
lf.set(lf.nextEmptySlot*16, 0)
lf.set(lf.nextEmptySlot*16+8, 0)
}
func (lf *discardStats) maxSlot() int {
return len(lf.Data) / 16
}
// Update would update the discard stats for the given file id. If discard is
// 0, it would return the current value of discard for the file. If discard is
// < 0, it would set the current value of discard to zero for the file.
func (lf *discardStats) Update(fidu uint32, discard int64) int64 {
fid := uint64(fidu)
lf.Lock()
defer lf.Unlock()
idx := sort.Search(lf.nextEmptySlot, func(slot int) bool {
return lf.get(slot*16) >= fid
})
if idx < lf.nextEmptySlot && lf.get(idx*16) == fid {
off := idx*16 + 8
curDisc := lf.get(off)
if discard == 0 {
return int64(curDisc)
}
if discard < 0 {
lf.set(off, 0)
return 0
}
lf.set(off, curDisc+uint64(discard))
return int64(curDisc + uint64(discard))
}
if discard <= 0 {
// No need to add a new entry.
return 0
}
// Could not find the fid. Add the entry.
idx = lf.nextEmptySlot
lf.set(idx*16, fid)
lf.set(idx*16+8, uint64(discard))
// Move to next slot.
lf.nextEmptySlot++
for lf.nextEmptySlot >= lf.maxSlot() {
y.Check(lf.Truncate(2 * int64(len(lf.Data))))
}
lf.zeroOut()
sort.Sort(lf)
return discard
}
func (lf *discardStats) Iterate(f func(fid, stats uint64)) {
for slot := 0; slot < lf.nextEmptySlot; slot++ {
idx := 16 * slot
f(lf.get(idx), lf.get(idx+8))
}
}
// MaxDiscard returns the file id with maximum discard bytes.
func (lf *discardStats) MaxDiscard() (uint32, int64) {
lf.Lock()
defer lf.Unlock()
var maxFid, maxVal uint64
lf.Iterate(func(fid, val uint64) {
if maxVal < val {
maxVal = val
maxFid = fid
}
})
return uint32(maxFid), int64(maxVal)
}
================================================
FILE: discard_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"os"
"testing"
"github.com/stretchr/testify/require"
)
func TestDiscardStats(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := DefaultOptions(dir)
ds, err := InitDiscardStats(opt)
require.NoError(t, err)
require.Zero(t, ds.nextEmptySlot)
fid, _ := ds.MaxDiscard()
require.Zero(t, fid)
for i := uint32(0); i < 20; i++ {
require.Equal(t, int64(i*100), ds.Update(i, int64(i*100)))
}
ds.Iterate(func(id, val uint64) {
require.Equal(t, id*100, val)
})
for i := uint32(0); i < 10; i++ {
require.Equal(t, 0, int(ds.Update(i, -1)))
}
ds.Iterate(func(id, val uint64) {
if id < 10 {
require.Zero(t, val)
return
}
require.Equal(t, int(id*100), int(val))
})
}
func TestReloadDiscardStats(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := DefaultOptions(dir)
db, err := Open(opt)
require.NoError(t, err)
ds := db.vlog.discardStats
ds.Update(uint32(1), 1)
ds.Update(uint32(2), 1)
ds.Update(uint32(1), -1)
require.NoError(t, db.Close())
// Reopen the DB, discard stats should be same.
db2, err := Open(opt)
require.NoError(t, err)
ds2 := db2.vlog.discardStats
require.Zero(t, ds2.Update(uint32(1), 0))
require.Equal(t, 1, int(ds2.Update(uint32(2), 0)))
}
================================================
FILE: doc.go
================================================
/*
Package badger implements an embeddable, simple and fast key-value database,
written in pure Go. It is designed to be highly performant for both reads and
writes simultaneously. Badger uses Multi-Version Concurrency Control (MVCC), and
supports transactions. It runs transactions concurrently, with serializable
snapshot isolation guarantees.
Badger uses an LSM tree along with a value log to separate keys from values,
hence reducing both write amplification and the size of the LSM tree. This
allows LSM tree to be served entirely from RAM, while the values are served
from SSD.
# Usage
Badger has the following main types: DB, Txn, Item and Iterator. DB contains
keys that are associated with values. It must be opened with the appropriate
options before it can be accessed.
All operations happen inside a Txn. Txn represents a transaction, which can
be read-only or read-write. Read-only transactions can read values for a
given key (which are returned inside an Item), or iterate over a set of
key-value pairs using an Iterator (which are returned as Item type values as
well). Read-write transactions can also update and delete keys from the DB.
See the examples for more usage details.
*/
package badger
================================================
FILE: docs/design.md
================================================
# Design
We wrote Badger with these design goals in mind:
- Write a key-value database in pure Go
- Use latest research to build the fastest KV database for data sets spanning terabytes
- Optimize for modern storage devices
Badger’s design is based on a paper titled
[WiscKey: Separating Keys from Values in SSD-conscious Storage](https://www.usenix.org/system/files/conference/fast16/fast16-papers-lu.pdf).
## References
The following blog posts are a great starting point for learning more about Badger and the
underlying design principles:
- [Introducing Badger: A fast key-value store written natively in Go](https://hypermode.com/blog/badger/)
- [Make Badger crash resilient with ALICE](https://hypermode.com/blog/alice/)
- [Badger vs LMDB vs BoltDB: Benchmarking key-value databases in Go](https://hypermode.com/blog/badger-lmdb-boltdb/)
- [Concurrent ACID Transactions in Badger](https://hypermode.com/blog/badger-txn/)
## Comparisons
| Feature | Badger | RocksDB | BoltDB |
| ----------------------------- | -------------------------------------- | ---------------------------- | ------- |
| Design | LSM tree with value log | LSM tree only | B+ tree |
| High Read throughput | Yes | No | Yes |
| High Write throughput | Yes | Yes | No |
| Designed for SSDs | Yes (with latest research1) | Not specifically2 | No |
| Embeddable | Yes | Yes | Yes |
| Sorted KV access | Yes | Yes | Yes |
| Pure Go (no Cgo) | Yes | No | Yes |
| Transactions | Yes | Yes | Yes |
| ACID-compliant | Yes, concurrent with SSI3 | No | Yes |
| Snapshots | Yes | Yes | Yes |
| TTL support | Yes | Yes | No |
| 3D access (key-value-version) | Yes4 | No | No |
1 The WiscKey paper (on which Badger is based) saw big wins with separating values from
keys, significantly reducing the write amplification compared to a typical LSM tree.
2 RocksDB is an SSD-optimized version of LevelDB, which was designed specifically for
rotating disks. As such RocksDB's design isn't aimed at SSDs.
3 SSI: Serializable Snapshot Isolation. For more details, see the blog post
[Concurrent ACID Transactions in Badger](https://hypermode.com/blog/badger-txn/)
4 Badger provides direct access to value versions via its Iterator API. Users can also
specify how many versions to keep per key via Options.
## Benchmarks
We've run comprehensive benchmarks against RocksDB, BoltDB, and LMDB. The benchmarking code with
detailed logs are in the [badger-bench](https://github.com/dgraph-io/badger-bench) repo.
================================================
FILE: docs/encryption-at-rest.md
================================================
# Encryption at Rest in Dgraph and Badger
Badger provides encryption at rest using AES encryption, enabling compliance with security standards
such as HIPAA and PCI DSS. This feature was introduced in Badger v2 and is available to all systems
built on Badger, including Dgraph.
## Overview
Badger implements encryption at the storage layer, allowing systems like Dgraph to inherit
encryption capabilities without additional implementation. This separation of concerns means:
- Badger manages data security and encryption at the disk level
- Higher-level systems like Dgraph focus on distributed operations and graph semantics
- All Badger-based systems benefit from encryption improvements
## Encryption Algorithm
Badger uses the
[Advanced Encryption Standard (AES)](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard),
standardized by NIST and widely adopted across databases including MongoDB, SQLite, and RocksDB. AES
is a symmetric encryption algorithm: the same key encrypts and decrypts data.
AES key sizes: 128, 192, or 256 bits. All provide strong security; 128-bit keys are computationally
infeasible to brute force.
## Key Management
Badger uses a two-tier key system:
### Master Key
The user-provided AES encryption key that encrypts data keys. Master key length determines AES
variant:
- 16 bytes: AES-128
- 24 bytes: AES-192
- 32 bytes: AES-256
**Important:** Use a cryptographically secure random key. Never use predictable strings. Generate
keys using a password manager or secure random generator.
### Data Keys
Auto-generated keys that encrypt actual data on disk. Each encrypted data key is stored alongside
the encrypted data. Master keys encrypt data keys, not data directly.
**Benefits:**
- Master key rotation only requires re-encrypting data keys (small, fast operation)
- Data keys rotate automatically without re-encrypting all data
- Minimal performance impact during key rotation
## Key Rotation
### Data Key Rotation
Badger automatically rotates data keys every 10 days by default. Configure the rotation interval
using `Options.WithEncryptionKeyRotationDuration`.
All historical data keys are retained to decrypt older data. Each data key is 32 bytes; 1000 keys
consume 32KB. At 10-day intervals, this represents approximately 27 years of keys.
### Master Key Rotation
Users must manually rotate master keys. Use the `rotate` command:
```shell
badger rotate --dir=badger_dir --old-key-path=old/path --new-key-path=new/path
```
**Requirements:**
- Database must be offline during master key rotation
- Only data keys are re-encrypted (fast operation)
- Future versions may support online rotation
## Initialization Vectors
To prevent identical plaintext from producing identical ciphertext, Badger uses Initialization
Vectors (IVs).
### SSTable Encryption
Each 4KB block in SSTables uses a unique 16-byte IV stored in plaintext at the end of the encrypted
block. Storage overhead: 0.4% (16 bytes per 4KB block).
**Security:** IVs can be stored in plaintext. Decryption requires the data key, which requires the
master key. Knowledge of the IV alone is insufficient.
### Value Log Encryption
Value log entries are encrypted individually to match access patterns. To minimize storage overhead,
Badger uses a 12-byte file-level IV combined with a 4-byte value offset to form the 16-byte IV.
**Benefits:**
- Saves 16 bytes per value entry
- 12-byte overhead per vlog file (vs 16 bytes per value)
- For 10,000 entries: 12 bytes total vs 160,000 bytes with per-value IVs
## Enabling Encryption
### New Database
Enable encryption when creating a new database:
```go
opts := badger.DefaultOptions("/tmp/badger").
WithEncryptionKey(masterKey).
WithEncryptionKeyRotationDuration(dataKeyRotationDuration) // defaults to 10 days
```
### Existing Database
Enable encryption on an unencrypted database:
```shell
badger rotate --dir=badger_dir --new-key-path=new/path
```
**Note:** This enables encryption for new files only. Existing data is encrypted during compaction
as new files are generated. Badger operates in hybrid mode, tracking encryption status per file.
### Immediate Full Encryption
To encrypt all existing data immediately:
1. Export the database: `badger backup --dir=badger_dir -f backup.bak`
2. Create a new encrypted database instance
3. Restore the data: `badger restore --dir=new_badger_dir -f backup.bak`
Alternatively, use the Stream Framework and StreamWriter interface for in-place encryption with high
throughput.
## Security Considerations
### Key Security
- Store master keys securely (key management service, secure vault)
- Rotate master keys regularly
- Use strong, randomly generated keys
- Protect physical access to systems performing encryption
### Key Leakage
Key security is more critical than key size. Threats include:
- Side-channel attacks (electromagnetic radiation analysis)
- Key reuse patterns enabling cryptanalysis
- Physical access to encryption systems
Regular key rotation mitigates these risks.
## Terminology
In this context, "key" refers to:
- **Database key**: The key in a key-value pair stored in Badger
- **Encryption key**: The cryptographic key used for encryption/decryption (master key or data key)
When ambiguous, this document uses "encryption key" for cryptographic keys.
================================================
FILE: docs/index.md
================================================
# Badger
## What is Badger?
BadgerDB is an embeddable, persistent, and fast key-value (KV) database written in pure Go. It is
the underlying database for [Dgraph](https://github.com/dgraph-io/dgraph), a fast, distributed graph
database. It is meant to be an efficient alternative to non-Go-based key-value stores like RocksDB.
## Changelog
We keep the [repo Changelog](https://github.com/dgraph-io/badger/blob/main/CHANGELOG.md) up to date
with each release.
[Quickstart](quickstart.md)
[Design](design.md)
[Encryption at rest](encryption-at-rest.md)
[Troubleshooting](troubleshooting.md)
================================================
FILE: docs/quickstart.md
================================================
# Quickstart
## Prerequisites
- [Go](https://go.dev/doc/install) - v1.23 or higher
- Text editor - we recommend [VS Code](https://code.visualstudio.com/)
- Terminal - access Badger through a command-line interface (CLI)
## Installing
To start using Badger, run the following command to retrieve the library.
```sh
go get github.com/dgraph-io/badger/v4
```
Then, install the Badger command line utility into your `$GOBIN` path.
```sh
go install github.com/dgraph-io/badger/v4/badger@latest
```
## Opening a database
The top-level object in Badger is a `DB`. It represents multiple files on disk in specific
directories, which contain the data for a single database.
To open your database, use the `badger.Open()` function, with the appropriate options. The `Dir` and
`ValueDir` options are mandatory and you must specify them in your client. To simplify, you can set
both options to the same value.
Badger obtains a lock on the directories. Multiple processes can't open the
same database at the same time.
```go
package main
import (
"log"
badger "github.com/dgraph-io/badger/v4"
)
func main() {
// Open the Badger database located in the /tmp/badger directory.
// It is created if it doesn't exist.
db, err := badger.Open(badger.DefaultOptions("/tmp/badger"))
if err != nil {
log.Fatal(err)
}
defer db.Close()
// your code here
}
```
### In-memory/diskless mode
By default, Badger ensures all data persists to disk. It also supports a pure in-memory mode. When
Badger is running in this mode, all data remains in memory only. Reads and writes are much faster,
but Badger loses all stored data in the case of a crash or close. To open Badger in in-memory mode,
set the `InMemory` option.
```go
opt := badger.DefaultOptions("").WithInMemory(true)
```
### Encryption mode
If you enable encryption in Badger, you also need to set the index cache size.
The cache improves the performance. Otherwise, reads can be very slow with
encryption enabled.
For example, to set a `100 Mb` cache:
```go
opts.IndexCache = 100 << 20 // 100 mb or some other size based on the amount of data
```
## Transactions
### Read-only transactions
To start a read-only transaction, you can use the `DB.View()` method:
```go
err := db.View(func(txn *badger.Txn) error {
// your code here
return nil
})
```
You can't perform any writes or deletes within this transaction. Badger ensures that you get a
consistent view of the database within this closure. Any writes that happen elsewhere after the
transaction has started aren't seen by calls made within the closure.
### Read-write transactions
To start a read-write transaction, you can use the `DB.Update()` method:
```go
err := db.Update(func(txn *badger.Txn) error {
// Your code here…
return nil
})
```
Badger allows all database operations inside a read-write transaction.
Always check the returned error value. If you return an error within your closure it's passed
through.
An `ErrConflict` error is reported in case of a conflict. Depending on the state of your app, you
have the option to retry the operation if you receive this error.
An `ErrTxnTooBig` is reported in case the number of pending writes/deletes in the transaction
exceeds a certain limit. In that case, it's best to commit the transaction and start a new
transaction immediately. Here is an example (we aren't checking for errors in some places for
simplicity):
```go
updates := make(map[string]string)
txn := db.NewTransaction(true)
for k,v := range updates {
if err := txn.Set([]byte(k),[]byte(v)); err == badger.ErrTxnTooBig {
_ = txn.Commit()
txn = db.NewTransaction(true)
_ = txn.Set([]byte(k),[]byte(v))
}
}
_ = txn.Commit()
```
### Managing transactions manually
The `DB.View()` and `DB.Update()` methods are wrappers around the `DB.NewTransaction()` and
`Txn.Commit()` methods (or `Txn.Discard()` in case of read-only transactions). These helper methods
start the transaction, execute a function, and then safely discard your transaction if an error is
returned. This is the recommended way to use Badger transactions.
However, sometimes you may want to manually create and commit your transactions. You can use the
`DB.NewTransaction()` function directly, which takes in a boolean argument to specify whether a
read-write transaction is required. For read-write transactions, it's necessary to call
`Txn.Commit()` to ensure the transaction is committed. For read-only transactions, calling
`Txn.Discard()` is sufficient. `Txn.Commit()` also calls `Txn.Discard()` internally to cleanup the
transaction, so just calling `Txn.Commit()` is sufficient for read-write transaction. However, if
your code doesn’t call `Txn.Commit()` for some reason (for e.g it returns prematurely with an
error), then please make sure you call `Txn.Discard()` in a `defer` block. Refer to the code below.
```go
// Start a writable transaction.
txn := db.NewTransaction(true)
defer txn.Discard()
// Use the transaction...
err := txn.Set([]byte("answer"), []byte("42"))
if err != nil {
return err
}
// Commit the transaction and check for error.
if err := txn.Commit(); err != nil {
return err
}
```
The first argument to `DB.NewTransaction()` is a boolean stating if the transaction should be
writable.
Badger allows an optional callback to the `Txn.Commit()` method. Normally, the callback can be set
to `nil`, and the method returns after all the writes have succeeded. However, if this callback is
provided, the `Txn.Commit()` method returns as soon as it has checked for any conflicts. The actual
writing to the disk happens asynchronously, and the callback is invoked once the writing has
finished, or an error has occurred. This can improve the throughput of the app in some cases. But it
also means that a transaction isn't durable until the callback has been invoked with a `nil` error
value.
## Using key/value pairs
To save a key/value pair, use the `Txn.Set()` method:
```go
err := db.Update(func(txn *badger.Txn) error {
err := txn.Set([]byte("answer"), []byte("42"))
return err
})
```
Key/Value pair can also be saved by first creating `Entry`, then setting this `Entry` using
`Txn.SetEntry()`. `Entry` also exposes methods to set properties on it.
```go
err := db.Update(func(txn *badger.Txn) error {
e := badger.NewEntry([]byte("answer"), []byte("42"))
err := txn.SetEntry(e)
return err
})
```
This sets the value of the `"answer"` key to `"42"`. To retrieve this value, we can use the
`Txn.Get()` method:
```go
err := db.View(func(txn *badger.Txn) error {
item, err := txn.Get([]byte("answer"))
handle(err)
var valNot, valCopy []byte
err := item.Value(func(val []byte) error {
// This func with val would only be called if item.Value encounters no error.
// Accessing val here is valid.
fmt.Printf("The answer is: %s\n", val)
// Copying or parsing val is valid.
valCopy = append([]byte{}, val...)
// Assigning val slice to another variable is NOT OK.
valNot = val // Do not do this.
return nil
})
handle(err)
// DO NOT access val here. It is the most common cause of bugs.
fmt.Printf("NEVER do this. %s\n", valNot)
// You must copy it to use it outside item.Value(...).
fmt.Printf("The answer is: %s\n", valCopy)
// Alternatively, you could also use item.ValueCopy().
valCopy, err = item.ValueCopy(nil)
handle(err)
fmt.Printf("The answer is: %s\n", valCopy)
return nil
})
```
`Txn.Get()` returns `ErrKeyNotFound` if the value isn't found.
Please note that values returned from `Get()` are only valid while the transaction is open. If you
need to use a value outside of the transaction then you must use `copy()` to copy it to another byte
slice.
Use the `Txn.Delete()` method to delete a key.
## Monotonically increasing integers
To get unique monotonically increasing integers with strong durability, you can use the
`DB.GetSequence` method. This method returns a `Sequence` object, which is thread-safe and can be
used concurrently via various goroutines.
Badger would lease a range of integers to hand out from memory, with the bandwidth provided to
`DB.GetSequence`. The frequency at which disk writes are done is determined by this lease bandwidth
and the frequency of `Next` invocations. Setting a bandwidth too low would do more disk writes,
setting it too high would result in wasted integers if Badger is closed or crashes. To avoid wasted
integers, call `Release` before closing Badger.
```go
seq, err := db.GetSequence(key, 1000)
defer seq.Release()
for {
num, err := seq.Next()
}
```
## Merge operations
Badger provides support for ordered merge operations. You can define a func of type `MergeFunc`
which takes in an existing value, and a value to be _merged_ with it. It returns a new value which
is the result of the merge operation. All values are specified in byte arrays. For example, this is
a merge function (`add`) which appends a `[]byte` value to an existing `[]byte` value.
```go
// Merge function to append one byte slice to another
func add(originalValue, newValue []byte) []byte {
return append(originalValue, newValue...)
}
```
This function can then be passed to the `DB.GetMergeOperator()` method, along with a key, and a
duration value. The duration specifies how often the merge function is run on values that have been
added using the `MergeOperator.Add()` method.
`MergeOperator.Get()` method can be used to retrieve the cumulative value of the key associated with
the merge operation.
```go
key := []byte("merge")
m := db.GetMergeOperator(key, add, 200*time.Millisecond)
defer m.Stop()
m.Add([]byte("A"))
m.Add([]byte("B"))
m.Add([]byte("C"))
res, _ := m.Get() // res should have value ABC encoded
```
Example: merge operator which increments a counter
```go
func uint64ToBytes(i uint64) []byte {
var buf [8]byte
binary.BigEndian.PutUint64(buf[:], i)
return buf[:]
}
func bytesToUint64(b []byte) uint64 {
return binary.BigEndian.Uint64(b)
}
// Merge function to add two uint64 numbers
func add(existing, new []byte) []byte {
return uint64ToBytes(bytesToUint64(existing) + bytesToUint64(new))
}
```
It can be used as
```go
key := []byte("merge")
m := db.GetMergeOperator(key, add, 200*time.Millisecond)
defer m.Stop()
m.Add(uint64ToBytes(1))
m.Add(uint64ToBytes(2))
m.Add(uint64ToBytes(3))
res, _ := m.Get() // res should have value 6 encoded
```
## Setting time to live and user metadata on keys
Badger allows setting an optional Time to Live (TTL) value on keys. Once the TTL has elapsed, the
key is no longer retrievable and is eligible for garbage collection. A TTL can be set as a
`time.Duration` value using the `Entry.WithTTL()` and `Txn.SetEntry()` API methods.
```go
err := db.Update(func(txn *badger.Txn) error {
e := badger.NewEntry([]byte("answer"), []byte("42")).WithTTL(time.Hour)
err := txn.SetEntry(e)
return err
})
```
An optional user metadata value can be set on each key. A user metadata value is represented by a
single byte. It can be used to set certain bits along with the key to aid in interpreting or
decoding the key-value pair. User metadata can be set using `Entry.WithMeta()` and `Txn.SetEntry()`
API methods.
```go
err := db.Update(func(txn *badger.Txn) error {
e := badger.NewEntry([]byte("answer"), []byte("42")).WithMeta(byte(1))
err := txn.SetEntry(e)
return err
})
```
`Entry` APIs can be used to add the user metadata and TTL for same key. This `Entry` then can be set
using `Txn.SetEntry()`.
```go
err := db.Update(func(txn *badger.Txn) error {
e := badger.NewEntry([]byte("answer"), []byte("42")).WithMeta(byte(1)).WithTTL(time.Hour)
err := txn.SetEntry(e)
return err
})
```
## Iterating over keys
To iterate over keys, we can use an `Iterator`, which can be obtained using the `Txn.NewIterator()`
method. Iteration happens in byte-wise lexicographical sorting order.
```go
err := db.View(func(txn *badger.Txn) error {
opts := badger.DefaultIteratorOptions
opts.PrefetchSize = 10
it := txn.NewIterator(opts)
defer it.Close()
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
k := item.Key()
err := item.Value(func(v []byte) error {
fmt.Printf("key=%s, value=%s\n", k, v)
return nil
})
if err != nil {
return err
}
}
return nil
})
```
The iterator allows you to move to a specific point in the list of keys and move forward or backward
through the keys one at a time.
By default, Badger prefetches the values of the next 100 items. You can adjust that with the
`IteratorOptions.PrefetchSize` field. However, setting it to a value higher than `GOMAXPROCS` (which
we recommend to be 128 or higher) shouldn’t give any additional benefits. You can also turn off the
fetching of values altogether. See section below on key-only iteration.
### Prefix scans
To iterate over a key prefix, you can combine `Seek()` and `ValidForPrefix()`:
```go
db.View(func(txn *badger.Txn) error {
it := txn.NewIterator(badger.DefaultIteratorOptions)
defer it.Close()
prefix := []byte("1234")
for it.Seek(prefix); it.ValidForPrefix(prefix); it.Next() {
item := it.Item()
k := item.Key()
err := item.Value(func(v []byte) error {
fmt.Printf("key=%s, value=%s\n", k, v)
return nil
})
if err != nil {
return err
}
}
return nil
})
```
### Possible pagination implementation using Prefix scans
Considering that iteration happens in **byte-wise lexicographical sorting** order, it's possible to
create a sorting-sensitive key. For example, a simple blog post key might look
like:`feed:userUuid:timestamp:postUuid`. Here, the `timestamp` part of the key is treated as an
attribute, and items are stored in the corresponding order:
| Order Ascending | Key |
| :-------------: | :------------------------------------------------------------ |
| 1 | feed:tQpnEDVRoCxTFQDvyQEzdo:1733127889:tQpnEDVRoCxTFQDvyQEzdo |
| 2 | feed:tQpnEDVRoCxTFQDvyQEzdo:1733127533:1Mryrou1xoekEaxzrFiHwL |
| 3 | feed:tQpnEDVRoCxTFQDvyQEzdo:1733127486:pprRrNL2WP4yfVXsSNBSx6 |
It is important to properly configure keys for lexicographical sorting to avoid incorrect ordering.
A **prefix scan** through the preceding keys can be achieved using the prefix
`feed:tQpnEDVRoCxTFQDvyQEzdo`. All matching keys are returned, sorted by `timestamp`.
Sorting can be done in ascending or descending order based on `timestamp` or `reversed timestamp` as
needed:
```go
reversedTimestamp := math.MaxInt64-time.Now().Unix()
```
This makes it possible to implement simple pagination by using a limit for the number of keys and a
cursor (the last key from the previous iteration) to identify where to resume.
```go
// startCursor may look like 'feed:tQpnEDVRoCxTFQDvyQEzdo:1733127486'.
// A prefix scan with this cursor locates the specific key where
// the previous iteration stopped.
err = db.badger.View(func(txn *badger.Txn) error {
it := txn.NewIterator(opts)
defer it.Close()
// Prefix example 'feed:tQpnEDVRoCxTFQDvyQEzdo'
// if no cursor provided prefix scan starts from the beginning
p := prefix
if startCursor != nil {
p = startCursor
}
iterNum := 0 // Tracks the number of iterations to enforce the limit.
for it.Seek(p); it.ValidForPrefix(p); it.Next() {
// The method it.ValidForPrefix ensures that iteration continues
// as long as keys match the prefix.
// For example, if p = 'feed:tQpnEDVRoCxTFQDvyQEzdo:1733127486',
// it matches keys like
// 'feed:tQpnEDVRoCxTFQDvyQEzdo:1733127889:pprRrNL2WP4yfVXsSNBSx6'.
// Once the starting point for iteration is found, revert the prefix
// back to 'feed:tQpnEDVRoCxTFQDvyQEzdo' to continue iterating sequentially.
// Otherwise, iteration would stop after a single prefix-key match.
p = prefix
item := it.Item()
key := string(item.Key())
if iterNum > limit { // Limit reached.
nextCursor = key // Save the next cursor for future iterations.
return nil
}
iterNum++ // Increment iteration count.
err := item.Value(func(v []byte) error {
fmt.Printf("key=%s, value=%s\n", k, v)
return nil
})
if err != nil {
return err
}
}
// If the number of iterations is less than the limit,
// it means there are no more items for the prefix.
if iterNum < limit {
nextCursor = ""
}
return nil
})
return nextCursor, err
```
### Key-only iteration
Badger supports a unique mode of iteration called _key-only_ iteration. It is several order of
magnitudes faster than regular iteration, because it involves access to the Log-structured merge
(LSM)-tree only, which is usually resident entirely in RAM. To enable key-only iteration, you need
to set the `IteratorOptions.PrefetchValues` field to `false`. This can also be used to do sparse
reads for selected keys during an iteration, by calling `item.Value()` only when required.
```go
err := db.View(func(txn *badger.Txn) error {
opts := badger.DefaultIteratorOptions
opts.PrefetchValues = false
it := txn.NewIterator(opts)
defer it.Close()
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
k := item.Key()
fmt.Printf("key=%s\n", k)
}
return nil
})
```
## Stream
Badger provides a Stream framework, which concurrently iterates over all or a portion of the DB,
converting data into custom key-values, and streams it out serially to be sent over network, written
to disk, or even written back to Badger. This is a lot faster way to iterate over Badger than using
a single Iterator. Stream supports Badger in both managed and normal mode.
Stream uses the natural boundaries created by SSTables within the Log-structure merge (LSM)-tree, to
quickly generate key ranges. Each goroutine then picks a range and runs an iterator to iterate over
it. Each iterator iterates over all versions of values and is created from the same transaction,
thus working over a snapshot of the DB. Every time a new key is encountered, it calls
`ChooseKey(item)`, followed by `KeyToList(key, itr)`. This allows a user to select or reject that
key, and if selected, convert the value versions into custom key-values. The goroutine batches up 4
MB worth of key-values, before sending it over to a channel. Another goroutine further batches up
data from this channel using _smart batching_ algorithm and calls `Send` serially.
This framework is designed for high throughput key-value iteration, spreading the work of iteration
across many goroutines. `DB.Backup` uses this framework to provide full and incremental backups
quickly. Dgraph is a heavy user of this framework. In fact, this framework was developed and used
within Dgraph, before getting ported over to Badger.
```go
stream := db.NewStream()
// db.NewStreamAt(readTs) for managed mode.
// -- Optional settings
stream.NumGo = 16 // Set number of goroutines to use for iteration.
stream.Prefix = []byte("some-prefix") // Leave nil for iteration over the whole DB.
stream.LogPrefix = "Badger.Streaming" // For identifying stream logs. Outputs to Logger.
// ChooseKey is called concurrently for every key. If left nil, assumes true by default.
stream.ChooseKey = func(item *badger.Item) bool {
return bytes.HasSuffix(item.Key(), []byte("er"))
}
// KeyToList is called concurrently for chosen keys. This can be used to convert
// Badger data into custom key-values. If nil, uses stream.ToList, a default
// implementation, which picks all valid key-values.
stream.KeyToList = nil
// -- End of optional settings.
// Send is called serially, while Stream.Orchestrate is running.
stream.Send = func(list *pb.KVList) error {
return proto.MarshalText(w, list) // Write to w.
}
// Run the stream
if err := stream.Orchestrate(context.Background()); err != nil {
return err
}
// Done.
```
## Garbage collection
Badger values need to be garbage collected, because of two reasons:
- Badger keeps values separately from the Log-structure merge (LSM)-tree. This means that the
compaction operations that clean up the LSM tree do not touch the values at all. Values need to be
cleaned up separately.
- Concurrent read/write transactions could leave behind multiple values for a single key, because
they're stored with different versions. These could accumulate, and take up unneeded space beyond
the time these older versions are needed.
Badger relies on the client to perform garbage collection at a time of their choosing. It provides
the following method, which can be invoked at an appropriate time:
- `DB.RunValueLogGC()`: This method is designed to do garbage collection while Badger is online.
Along with randomly picking a file, it uses statistics generated by the LSM tree compactions to
pick files that are likely to lead to maximum space reclamation. It is recommended to be called
during periods of low activity in your system, or periodically. One call would only result in
removal of at max one log file. As an optimization, you could also immediately re-run it whenever
it returns nil error (indicating a successful value log GC), as shown below.
```go
ticker := time.NewTicker(5 * time.Minute)
defer ticker.Stop()
for range ticker.C {
again:
err := db.RunValueLogGC(0.7)
if err == nil {
goto again
}
}
```
- `DB.PurgeOlderVersions()`: This method is **DEPRECATED** since v1.5.0. Now, Badger's LSM tree
automatically discards older/invalid versions of keys.
The `RunValueLogGC` method would not garbage collect the latest value log.
## Database backup
There are two public API methods `DB.Backup()` and `DB.Load()` which can be used to do online
backups and restores. Badger v0.9 provides a CLI tool `badger`, which can do offline backup/restore.
Make sure you have `$GOPATH/bin` in your PATH to use this tool.
The command below creates a version-agnostic backup of the database, to a file `badger.bak` in the
current working directory
```sh
badger backup --dir
```
To restore `badger.bak` in the current working directory to a new database:
```sh
badger restore --dir
```
See `badger --help` for more details.
If you have a Badger database that was created using v0.8 (or below), you can use the
`badger_backup` tool provided in v0.8.1, and then restore it using the preceding command to upgrade
your database to work with the latest version.
```sh
badger_backup --dir --backup-file badger.bak
```
We recommend all users to use the `Backup` and `Restore` APIs and tools. However, Badger is also
rsync-friendly because all files are immutable, barring the latest value log which is append-only.
So, rsync can be used as rudimentary way to perform a backup. In the following script, we repeat
rsync to ensure that the LSM tree remains consistent with the MANIFEST file while doing a full
backup.
```sh
#!/bin/bash
set -o history
set -o histexpand
# Makes a complete copy of a Badger database directory.
# Repeat rsync if the MANIFEST and SSTables are updated.
rsync -avz --delete db/ dst
while !! | grep -q "(MANIFEST\|\.sst)$"; do :; done
```
## Memory usage
Badger's memory usage can be managed by tweaking several options available in the `Options` struct
that's passed in when opening the database using `DB.Open`.
- Number of memtables (`Options.NumMemtables`)
- If you modify `Options.NumMemtables`, also adjust `Options.NumLevelZeroTables` and
`Options.NumLevelZeroTablesStall` accordingly.
- Number of concurrent compactions (`Options.NumCompactors`)
- Size of table (`Options.BaseTableSize`)
- Size of value log file (`Options.ValueLogFileSize`)
If you want to decrease the memory usage of Badger instance, tweak these options (ideally one at a
time) until you achieve the desired memory usage.
================================================
FILE: docs/troubleshooting.md
================================================
# Troubleshooting
## Writes are getting stuck
**Update: with the new `Value(func(v []byte))` API, this deadlock can no longer happen.**
The following is true for users on Badger v1.x.
This can happen if a long running iteration with `Prefetch` is set to false, but an `Item::Value`
call is made internally in the loop. That causes Badger to acquire read locks over the value log
files to avoid value log GC removing the file from underneath. As a side effect, this also blocks a
new value log GC file from being created, when the value log file boundary is hit.
Please see GitHub issues [#293](https://github.com/dgraph-io/badger/issues/293) and
[#315](https://github.com/dgraph-io/badger/issues/315).
There are multiple workarounds during iteration:
1. Use `Item::ValueCopy` instead of `Item::Value` when retrieving value.
1. Set `Prefetch` to true. Badger would then copy over the value and release the file lock
immediately.
1. When `Prefetch` is false, don't call `Item::Value` and do a pure key-only iteration. This might
be useful if you just want to delete a lot of keys.
1. Do the writes in a separate transaction after the reads.
## Writes are really slow
Are you creating a new transaction for every single key update, and waiting for it to `Commit` fully
before creating a new one? This leads to very low throughput.
We've created `WriteBatch` API which provides a way to batch up many updates into a single
transaction and `Commit` that transaction using callbacks to avoid blocking. This amortizes the cost
of a transaction really well, and provides the most efficient way to do bulk writes.
```go
wb := db.NewWriteBatch()
defer wb.Cancel()
for i := 0; i < N; i++ {
err := wb.Set(key(i), value(i), 0) // Will create txns as needed.
handle(err)
}
handle(wb.Flush()) // Wait for all txns to finish.
```
Note that `WriteBatch` API doesn't allow any reads. For read-modify-write workloads, you should be
using the `Transaction` API.
## I don't see any disk writes
If you're using Badger with `SyncWrites=false`, then your writes might not be written to value log
and won't get synced to disk immediately. Writes to LSM tree are done in-memory first, before they
get compacted to disk. The compaction would only happen once `BaseTableSize` has been reached. So,
if you're doing a few writes and then checking, you might not see anything on disk. Once you `Close`
the database, you'll see these writes on disk.
## Reverse iteration doesn't produce the right results
Just like forward iteration goes to the first key which is equal or greater than the SEEK key,
reverse iteration goes to the first key which is equal or lesser than the SEEK key. Therefore, SEEK
key would not be part of the results. You can typically add a `0xff` byte as a suffix to the SEEK
key to include it in the results. See the following issues:
[#436](https://github.com/dgraph-io/badger/issues/436) and
[#347](https://github.com/dgraph-io/badger/issues/347).
## Which instances should I use for Badger?
We recommend using instances which provide local SSD storage, without any limit on the maximum IOPS.
In AWS, these are storage optimized instances like i3. They provide local SSDs which clock 100K IOPS
over 4KB blocks easily.
## I'm getting a closed channel error
```sh
panic: close of closed channel
panic: send on closed channel
```
If you're seeing panics like this, it is because you're operating on a closed DB. This can happen,
if you call `Close()` before sending a write, or multiple times. You should ensure that you only
call `Close()` once, and all your read/write operations finish before closing.
## Are there any Go specific settings that I should use?
We _highly_ recommend setting a high number for `GOMAXPROCS`, which allows Go to observe the full
IOPS throughput provided by modern SSDs. In Dgraph, we have set it to 128. For more details,
[see this thread](https://groups.google.com/d/topic/golang-nuts/jPb_h3TvlKE/discussion).
## Are there any Linux specific settings that I should use?
We recommend setting `max file descriptors` to a high number depending upon the expected size of
your data. On Linux and Mac, you can check the file descriptor limit with `ulimit -n -H` for the
hard limit and `ulimit -n -S` for the soft limit. A soft limit of `65535` is a good lower bound. You
can adjust the limit as needed.
## I see "manifest has unsupported version: X (we support Y)" error
This error means you have a badger directory which was created by an older version of badger and
you're trying to open in a newer version of badger. The underlying data format can change across
badger versions and users have to migrate their data directory. Badger data can be migrated from
version X of badger to version Y of badger by following the steps listed below. Assume you were on
badger v1.6.0 and you wish to migrate to v2.0.0 version.
1. Install Badger version v1.6.0
- `cd $GOPATH/src/github.com/dgraph-io/badger`
- `git checkout v1.6.0`
- `cd badger && go install`
This should install the old Badger binary in your `$GOBIN`.
2. Create Backup
- `badger backup --dir path/to/badger/directory -f badger.backup`
3. Install Badger version v2.0.0
- `cd $GOPATH/src/github.com/dgraph-io/badger`
- `git checkout v2.0.0`
- `cd badger && go install`
This should install the new Badger binary in your `$GOBIN`.
4. Restore data from backup
- `badger restore --dir path/to/new/badger/directory -f badger.backup`
This creates a new directory on `path/to/new/badger/directory` and adds data in the new format
to it.
NOTE - The preceding steps shouldn't cause any data loss but please ensure the new data is valid
before deleting the old Badger directory.
## Why do I need gcc to build badger? Does badger need Cgo?
Badger doesn't directly use Cgo but it relies on https://github.com/DataDog/zstd library for zstd
compression and the library requires [`gcc/cgo`](https://pkg.go.dev/cmd/cgo). You can build Badger
without Cgo by running `CGO_ENABLED=0 go build`. This builds Badger without the support for ZSTD
compression algorithm.
As of Badger versions [v2.2007.4](https://github.com/dgraph-io/badger/releases/tag/v2.2007.4) and
[v3.2103.1](https://github.com/dgraph-io/badger/releases/tag/v3.2103.1) the DataDog ZSTD library was
replaced by pure Golang version and Cgo is no longer required. The new library is
[backwards compatible in nearly all cases](https://discuss.hypermode.com/t/use-pure-go-zstd-implementation/8670/10):
Yes they're compatible both ways. The only exception is 0 bytes of input which
gives 0 bytes output with the Go zstd. But you already have the
zstd.WithZeroFrames(true) which wraps 0 bytes in a header so it can be fed to
DD zstd. This is only relevant when downgrading.
================================================
FILE: errors.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
stderrors "errors"
"math"
)
const (
// ValueThresholdLimit is the maximum permissible value of opt.ValueThreshold.
ValueThresholdLimit = math.MaxUint16 - 16 + 1
)
var (
// ErrValueLogSize is returned when opt.ValueLogFileSize option is not within the valid
// range.
ErrValueLogSize = stderrors.New("Invalid ValueLogFileSize, must be in range [1MB, 2GB)")
// ErrKeyNotFound is returned when key isn't found on a txn.Get.
ErrKeyNotFound = stderrors.New("Key not found")
// ErrTxnTooBig is returned if too many writes are fit into a single transaction.
ErrTxnTooBig = stderrors.New("Txn is too big to fit into one request")
// ErrConflict is returned when a transaction conflicts with another transaction. This can
// happen if the read rows had been updated concurrently by another transaction.
ErrConflict = stderrors.New("Transaction Conflict. Please retry")
// ErrReadOnlyTxn is returned if an update function is called on a read-only transaction.
ErrReadOnlyTxn = stderrors.New("No sets or deletes are allowed in a read-only transaction")
// ErrDiscardedTxn is returned if a previously discarded transaction is reused.
ErrDiscardedTxn = stderrors.New("This transaction has been discarded. Create a new one")
// ErrEmptyKey is returned if an empty key is passed on an update function.
ErrEmptyKey = stderrors.New("Key cannot be empty")
// ErrInvalidKey is returned if the key has a special !badger! prefix,
// reserved for internal usage.
ErrInvalidKey = stderrors.New("Key is using a reserved !badger! prefix")
// ErrBannedKey is returned if the read/write key belongs to any banned namespace.
ErrBannedKey = stderrors.New("Key is using the banned prefix")
// ErrThresholdZero is returned if threshold is set to zero, and value log GC is called.
// In such a case, GC can't be run.
ErrThresholdZero = stderrors.New(
"Value log GC can't run because threshold is set to zero")
// ErrNoRewrite is returned if a call for value log GC doesn't result in a log file rewrite.
ErrNoRewrite = stderrors.New(
"Value log GC attempt didn't result in any cleanup")
// ErrRejected is returned if a value log GC is called either while another GC is running, or
// after DB::Close has been called.
ErrRejected = stderrors.New("Value log GC request rejected")
// ErrInvalidRequest is returned if the user request is invalid.
ErrInvalidRequest = stderrors.New("Invalid request")
// ErrManagedTxn is returned if the user tries to use an API which isn't
// allowed due to external management of transactions, when using ManagedDB.
ErrManagedTxn = stderrors.New(
"Invalid API request. Not allowed to perform this action using ManagedDB")
// ErrNamespaceMode is returned if the user tries to use an API which is allowed only when
// NamespaceOffset is non-negative.
ErrNamespaceMode = stderrors.New(
"Invalid API request. Not allowed to perform this action when NamespaceMode is not set.")
// ErrInvalidDump if a data dump made previously cannot be loaded into the database.
ErrInvalidDump = stderrors.New("Data dump cannot be read")
// ErrZeroBandwidth is returned if the user passes in zero bandwidth for sequence.
ErrZeroBandwidth = stderrors.New("Bandwidth must be greater than zero")
// ErrWindowsNotSupported is returned when opt.ReadOnly is used on Windows
ErrWindowsNotSupported = stderrors.New("Read-only mode is not supported on Windows")
// ErrPlan9NotSupported is returned when opt.ReadOnly is used on Plan 9
ErrPlan9NotSupported = stderrors.New("Read-only mode is not supported on Plan 9")
// ErrTruncateNeeded is returned when the value log gets corrupt, and requires truncation of
// corrupt data to allow Badger to run properly.
ErrTruncateNeeded = stderrors.New(
"Log truncate required to run DB. This might result in data loss")
// ErrBlockedWrites is returned if the user called DropAll. During the process of dropping all
// data from Badger, we stop accepting new writes, by returning this error.
ErrBlockedWrites = stderrors.New("Writes are blocked, possibly due to DropAll or Close")
// ErrNilCallback is returned when subscriber's callback is nil.
ErrNilCallback = stderrors.New("Callback cannot be nil")
// ErrEncryptionKeyMismatch is returned when the storage key is not
// matched with the key previously given.
ErrEncryptionKeyMismatch = stderrors.New("Encryption key mismatch")
// ErrInvalidDataKeyID is returned if the datakey id is invalid.
ErrInvalidDataKeyID = stderrors.New("Invalid datakey id")
// ErrInvalidEncryptionKey is returned if length of encryption keys is invalid.
ErrInvalidEncryptionKey = stderrors.New("Encryption key's length should be" +
"either 16, 24, or 32 bytes")
// ErrGCInMemoryMode is returned when db.RunValueLogGC is called in in-memory mode.
ErrGCInMemoryMode = stderrors.New("Cannot run value log GC when DB is opened in InMemory mode")
// ErrDBClosed is returned when a get operation is performed after closing the DB.
ErrDBClosed = stderrors.New("DB Closed")
)
================================================
FILE: fb/BlockOffset.go
================================================
// Code generated by the FlatBuffers compiler. DO NOT EDIT.
package fb
import (
flatbuffers "github.com/google/flatbuffers/go"
)
type BlockOffset struct {
_tab flatbuffers.Table
}
func GetRootAsBlockOffset(buf []byte, offset flatbuffers.UOffsetT) *BlockOffset {
n := flatbuffers.GetUOffsetT(buf[offset:])
x := &BlockOffset{}
x.Init(buf, n+offset)
return x
}
func (rcv *BlockOffset) Init(buf []byte, i flatbuffers.UOffsetT) {
rcv._tab.Bytes = buf
rcv._tab.Pos = i
}
func (rcv *BlockOffset) Table() flatbuffers.Table {
return rcv._tab
}
func (rcv *BlockOffset) Key(j int) byte {
o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
if o != 0 {
a := rcv._tab.Vector(o)
return rcv._tab.GetByte(a + flatbuffers.UOffsetT(j*1))
}
return 0
}
func (rcv *BlockOffset) KeyLength() int {
o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
if o != 0 {
return rcv._tab.VectorLen(o)
}
return 0
}
func (rcv *BlockOffset) KeyBytes() []byte {
o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
if o != 0 {
return rcv._tab.ByteVector(o + rcv._tab.Pos)
}
return nil
}
func (rcv *BlockOffset) MutateKey(j int, n byte) bool {
o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
if o != 0 {
a := rcv._tab.Vector(o)
return rcv._tab.MutateByte(a+flatbuffers.UOffsetT(j*1), n)
}
return false
}
func (rcv *BlockOffset) Offset() uint32 {
o := flatbuffers.UOffsetT(rcv._tab.Offset(6))
if o != 0 {
return rcv._tab.GetUint32(o + rcv._tab.Pos)
}
return 0
}
func (rcv *BlockOffset) MutateOffset(n uint32) bool {
return rcv._tab.MutateUint32Slot(6, n)
}
func (rcv *BlockOffset) Len() uint32 {
o := flatbuffers.UOffsetT(rcv._tab.Offset(8))
if o != 0 {
return rcv._tab.GetUint32(o + rcv._tab.Pos)
}
return 0
}
func (rcv *BlockOffset) MutateLen(n uint32) bool {
return rcv._tab.MutateUint32Slot(8, n)
}
func BlockOffsetStart(builder *flatbuffers.Builder) {
builder.StartObject(3)
}
func BlockOffsetAddKey(builder *flatbuffers.Builder, key flatbuffers.UOffsetT) {
builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(key), 0)
}
func BlockOffsetStartKeyVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT {
return builder.StartVector(1, numElems, 1)
}
func BlockOffsetAddOffset(builder *flatbuffers.Builder, offset uint32) {
builder.PrependUint32Slot(1, offset, 0)
}
func BlockOffsetAddLen(builder *flatbuffers.Builder, len uint32) {
builder.PrependUint32Slot(2, len, 0)
}
func BlockOffsetEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
return builder.EndObject()
}
================================================
FILE: fb/TableIndex.go
================================================
// Code generated by the FlatBuffers compiler. DO NOT EDIT.
package fb
import (
flatbuffers "github.com/google/flatbuffers/go"
)
type TableIndex struct {
_tab flatbuffers.Table
}
func GetRootAsTableIndex(buf []byte, offset flatbuffers.UOffsetT) *TableIndex {
n := flatbuffers.GetUOffsetT(buf[offset:])
x := &TableIndex{}
x.Init(buf, n+offset)
return x
}
func (rcv *TableIndex) Init(buf []byte, i flatbuffers.UOffsetT) {
rcv._tab.Bytes = buf
rcv._tab.Pos = i
}
func (rcv *TableIndex) Table() flatbuffers.Table {
return rcv._tab
}
func (rcv *TableIndex) Offsets(obj *BlockOffset, j int) bool {
o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
if o != 0 {
x := rcv._tab.Vector(o)
x += flatbuffers.UOffsetT(j) * 4
x = rcv._tab.Indirect(x)
obj.Init(rcv._tab.Bytes, x)
return true
}
return false
}
func (rcv *TableIndex) OffsetsLength() int {
o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
if o != 0 {
return rcv._tab.VectorLen(o)
}
return 0
}
func (rcv *TableIndex) BloomFilter(j int) byte {
o := flatbuffers.UOffsetT(rcv._tab.Offset(6))
if o != 0 {
a := rcv._tab.Vector(o)
return rcv._tab.GetByte(a + flatbuffers.UOffsetT(j*1))
}
return 0
}
func (rcv *TableIndex) BloomFilterLength() int {
o := flatbuffers.UOffsetT(rcv._tab.Offset(6))
if o != 0 {
return rcv._tab.VectorLen(o)
}
return 0
}
func (rcv *TableIndex) BloomFilterBytes() []byte {
o := flatbuffers.UOffsetT(rcv._tab.Offset(6))
if o != 0 {
return rcv._tab.ByteVector(o + rcv._tab.Pos)
}
return nil
}
func (rcv *TableIndex) MutateBloomFilter(j int, n byte) bool {
o := flatbuffers.UOffsetT(rcv._tab.Offset(6))
if o != 0 {
a := rcv._tab.Vector(o)
return rcv._tab.MutateByte(a+flatbuffers.UOffsetT(j*1), n)
}
return false
}
func (rcv *TableIndex) MaxVersion() uint64 {
o := flatbuffers.UOffsetT(rcv._tab.Offset(8))
if o != 0 {
return rcv._tab.GetUint64(o + rcv._tab.Pos)
}
return 0
}
func (rcv *TableIndex) MutateMaxVersion(n uint64) bool {
return rcv._tab.MutateUint64Slot(8, n)
}
func (rcv *TableIndex) KeyCount() uint32 {
o := flatbuffers.UOffsetT(rcv._tab.Offset(10))
if o != 0 {
return rcv._tab.GetUint32(o + rcv._tab.Pos)
}
return 0
}
func (rcv *TableIndex) MutateKeyCount(n uint32) bool {
return rcv._tab.MutateUint32Slot(10, n)
}
func (rcv *TableIndex) UncompressedSize() uint32 {
o := flatbuffers.UOffsetT(rcv._tab.Offset(12))
if o != 0 {
return rcv._tab.GetUint32(o + rcv._tab.Pos)
}
return 0
}
func (rcv *TableIndex) MutateUncompressedSize(n uint32) bool {
return rcv._tab.MutateUint32Slot(12, n)
}
func (rcv *TableIndex) OnDiskSize() uint32 {
o := flatbuffers.UOffsetT(rcv._tab.Offset(14))
if o != 0 {
return rcv._tab.GetUint32(o + rcv._tab.Pos)
}
return 0
}
func (rcv *TableIndex) MutateOnDiskSize(n uint32) bool {
return rcv._tab.MutateUint32Slot(14, n)
}
func (rcv *TableIndex) StaleDataSize() uint32 {
o := flatbuffers.UOffsetT(rcv._tab.Offset(16))
if o != 0 {
return rcv._tab.GetUint32(o + rcv._tab.Pos)
}
return 0
}
func (rcv *TableIndex) MutateStaleDataSize(n uint32) bool {
return rcv._tab.MutateUint32Slot(16, n)
}
func TableIndexStart(builder *flatbuffers.Builder) {
builder.StartObject(7)
}
func TableIndexAddOffsets(builder *flatbuffers.Builder, offsets flatbuffers.UOffsetT) {
builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(offsets), 0)
}
func TableIndexStartOffsetsVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT {
return builder.StartVector(4, numElems, 4)
}
func TableIndexAddBloomFilter(builder *flatbuffers.Builder, bloomFilter flatbuffers.UOffsetT) {
builder.PrependUOffsetTSlot(1, flatbuffers.UOffsetT(bloomFilter), 0)
}
func TableIndexStartBloomFilterVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT {
return builder.StartVector(1, numElems, 1)
}
func TableIndexAddMaxVersion(builder *flatbuffers.Builder, maxVersion uint64) {
builder.PrependUint64Slot(2, maxVersion, 0)
}
func TableIndexAddKeyCount(builder *flatbuffers.Builder, keyCount uint32) {
builder.PrependUint32Slot(3, keyCount, 0)
}
func TableIndexAddUncompressedSize(builder *flatbuffers.Builder, uncompressedSize uint32) {
builder.PrependUint32Slot(4, uncompressedSize, 0)
}
func TableIndexAddOnDiskSize(builder *flatbuffers.Builder, onDiskSize uint32) {
builder.PrependUint32Slot(5, onDiskSize, 0)
}
func TableIndexAddStaleDataSize(builder *flatbuffers.Builder, staleDataSize uint32) {
builder.PrependUint32Slot(6, staleDataSize, 0)
}
func TableIndexEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
return builder.EndObject()
}
================================================
FILE: fb/flatbuffer.fbs
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
namespace fb;
table TableIndex {
offsets:[BlockOffset];
bloom_filter:[ubyte];
max_version:uint64;
key_count:uint32;
uncompressed_size:uint32;
on_disk_size:uint32;
stale_data_size:uint32;
}
table BlockOffset {
key:[ubyte];
offset:uint;
len:uint;
}
root_type TableIndex;
root_type BlockOffset;
================================================
FILE: fb/gen.sh
================================================
#!/usr/bin/env bash
set -e
## Install flatc if not present
## ref. https://google.github.io/flatbuffers/flatbuffers_guide_building.html
command -v flatc >/dev/null || { ./install_flatbuffers.sh; }
flatc --go flatbuffer.fbs
# Move files to the correct directory.
mv fb/* ./
rmdir fb
================================================
FILE: fb/install_flatbuffers.sh
================================================
#!/usr/bin/env bash
set -e
install_mac() {
command -v brew >/dev/null ||
{
echo "[ERROR]: 'brew' command not not found. Exiting" 1>&2
exit 1
}
brew install flatbuffers
}
install_linux() {
for CMD in curl cmake g++ make; do
command -v "${CMD}" >/dev/null ||
{
echo "[ERROR]: '${CMD}' command not not found. Exiting" 1>&2
exit 1
}
done
## Create Temp Build Directory
BUILD_DIR=$(mktemp -d)
pushd "${BUILD_DIR}"
## Fetch Latest Tarball
LATEST_VERSION=$(curl -s https://api.github.com/repos/google/flatbuffers/releases/latest | grep -oP '(?<=tag_name": ")[^"]+')
curl -sLO https://github.com/google/flatbuffers/archive/"${LATEST_VERSION}".tar.gz
tar xf "${LATEST_VERSION}".tar.gz
## Build Binaries
cd flatbuffers-"${LATEST_VERSION#v}"
cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release
make
./flattests
cp flatc /usr/local/bin/flatc
## Cleanup Temp Build Directory
popd
rm -rf "${BUILD_DIR}"
}
SYSTEM=$(uname -s)
case ${SYSTEM,,} in
linux)
sudo bash -c "$(declare -f install_linux); install_linux"
;;
darwin)
install_mac
;;
esac
================================================
FILE: go.mod
================================================
module github.com/dgraph-io/badger/v4
go 1.23.0
toolchain go1.25.0
require (
github.com/cespare/xxhash/v2 v2.3.0
github.com/dgraph-io/ristretto/v2 v2.2.0
github.com/dustin/go-humanize v1.0.1
github.com/google/flatbuffers v25.2.10+incompatible
github.com/klauspost/compress v1.18.0
github.com/spf13/cobra v1.9.1
github.com/stretchr/testify v1.10.0
go.opentelemetry.io/contrib/zpages v0.62.0
go.opentelemetry.io/otel v1.37.0
golang.org/x/sys v0.35.0
google.golang.org/protobuf v1.36.7
)
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/spf13/pflag v1.0.6 // indirect
go.opentelemetry.io/auto/sdk v1.1.0 // indirect
go.opentelemetry.io/otel/metric v1.37.0 // indirect
go.opentelemetry.io/otel/sdk v1.37.0 // indirect
go.opentelemetry.io/otel/trace v1.37.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
retract v4.0.0 // see #1888 and #1889
retract v4.3.0 // see #2113 and #2121
================================================
FILE: go.sum
================================================
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgraph-io/ristretto/v2 v2.2.0 h1:bkY3XzJcXoMuELV8F+vS8kzNgicwQFAaGINAEJdWGOM=
github.com/dgraph-io/ristretto/v2 v2.2.0/go.mod h1:RZrm63UmcBAaYWC1DotLYBmTvgkrs0+XhBd7Npn7/zI=
github.com/dgryski/go-farm v0.0.0-20240924180020-3414d57e47da h1:aIftn67I1fkbMa512G+w+Pxci9hJPB8oMnkcP3iZF38=
github.com/dgryski/go-farm v0.0.0-20240924180020-3414d57e47da/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/google/flatbuffers v25.2.10+incompatible h1:F3vclr7C3HpB1k9mxCGRMXq6FdUalZ6H/pNX4FP1v0Q=
github.com/google/flatbuffers v25.2.10+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo=
github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0=
github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
go.opentelemetry.io/contrib/zpages v0.62.0 h1:9fUYTLmrK0x/lweM2uM+BOx069jLx8PxVqWhegGJ9Bo=
go.opentelemetry.io/contrib/zpages v0.62.0/go.mod h1:C8kXoiC1Ytvereztus2R+kqdSa6W/MZ8FfS8Zwj+LiM=
go.opentelemetry.io/otel v1.37.0 h1:9zhNfelUvx0KBfu/gb+ZgeAfAgtWrfHJZcAqFC228wQ=
go.opentelemetry.io/otel v1.37.0/go.mod h1:ehE/umFRLnuLa/vSccNq9oS1ErUlkkK71gMcN34UG8I=
go.opentelemetry.io/otel/metric v1.37.0 h1:mvwbQS5m0tbmqML4NqK+e3aDiO02vsf/WgbsdpcPoZE=
go.opentelemetry.io/otel/metric v1.37.0/go.mod h1:04wGrZurHYKOc+RKeye86GwKiTb9FKm1WHtO+4EVr2E=
go.opentelemetry.io/otel/sdk v1.37.0 h1:ItB0QUqnjesGRvNcmAcU0LyvkVyGJ2xftD29bWdDvKI=
go.opentelemetry.io/otel/sdk v1.37.0/go.mod h1:VredYzxUvuo2q3WRcDnKDjbdvmO0sCzOvVAiY+yUkAg=
go.opentelemetry.io/otel/trace v1.37.0 h1:HLdcFNbRQBE2imdSEgm/kwqmQj1Or1l/7bW6mxVK7z4=
go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
google.golang.org/protobuf v1.36.7 h1:IgrO7UwFQGJdRNXH/sQux4R1Dj1WAKcLElzeeRaXV2A=
google.golang.org/protobuf v1.36.7/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
================================================
FILE: histogram.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"fmt"
"math"
)
// PrintHistogram builds and displays the key-value size histogram.
// When keyPrefix is set, only the keys that have prefix "keyPrefix" are
// considered for creating the histogram
func (db *DB) PrintHistogram(keyPrefix []byte) {
if db == nil {
fmt.Println("\nCannot build histogram: DB is nil.")
return
}
histogram := db.buildHistogram(keyPrefix)
fmt.Printf("Histogram of key sizes (in bytes)\n")
histogram.keySizeHistogram.printHistogram()
fmt.Printf("Histogram of value sizes (in bytes)\n")
histogram.valueSizeHistogram.printHistogram()
}
// histogramData stores information about a histogram
type histogramData struct {
bins []int64
countPerBin []int64
totalCount int64
min int64
max int64
sum int64
}
// sizeHistogram contains keySize histogram and valueSize histogram
type sizeHistogram struct {
keySizeHistogram, valueSizeHistogram histogramData
}
// newSizeHistogram returns a new instance of keyValueSizeHistogram with
// properly initialized fields.
func newSizeHistogram() *sizeHistogram {
// TODO(ibrahim): find appropriate bin size.
keyBins := createHistogramBins(1, 16)
valueBins := createHistogramBins(1, 30)
return &sizeHistogram{
keySizeHistogram: histogramData{
bins: keyBins,
countPerBin: make([]int64, len(keyBins)+1),
max: math.MinInt64,
min: math.MaxInt64,
sum: 0,
},
valueSizeHistogram: histogramData{
bins: valueBins,
countPerBin: make([]int64, len(valueBins)+1),
max: math.MinInt64,
min: math.MaxInt64,
sum: 0,
},
}
}
// createHistogramBins creates bins for an histogram. The bin sizes are powers
// of two of the form [2^min_exponent, ..., 2^max_exponent].
func createHistogramBins(minExponent, maxExponent uint32) []int64 {
var bins []int64
for i := minExponent; i <= maxExponent; i++ {
bins = append(bins, int64(1)< histogram.max {
histogram.max = value
}
if value < histogram.min {
histogram.min = value
}
histogram.sum += value
histogram.totalCount++
for index := 0; index <= len(histogram.bins); index++ {
// Allocate value in the last buckets if we reached the end of the Bounds array.
if index == len(histogram.bins) {
histogram.countPerBin[index]++
break
}
// Check if the value should be added to the "index" bin
if value < histogram.bins[index] {
histogram.countPerBin[index]++
break
}
}
}
// buildHistogram builds the key-value size histogram.
// When keyPrefix is set, only the keys that have prefix "keyPrefix" are
// considered for creating the histogram
func (db *DB) buildHistogram(keyPrefix []byte) *sizeHistogram {
txn := db.NewTransaction(false)
defer txn.Discard()
itr := txn.NewIterator(DefaultIteratorOptions)
defer itr.Close()
badgerHistogram := newSizeHistogram()
// Collect key and value sizes.
for itr.Seek(keyPrefix); itr.ValidForPrefix(keyPrefix); itr.Next() {
item := itr.Item()
badgerHistogram.keySizeHistogram.Update(item.KeySize())
badgerHistogram.valueSizeHistogram.Update(item.ValueSize())
}
return badgerHistogram
}
// printHistogram prints the histogram data in a human-readable format.
func (histogram histogramData) printHistogram() {
fmt.Printf("Total count: %d\n", histogram.totalCount)
fmt.Printf("Min value: %d\n", histogram.min)
fmt.Printf("Max value: %d\n", histogram.max)
fmt.Printf("Mean: %.2f\n", float64(histogram.sum)/float64(histogram.totalCount))
fmt.Printf("%24s %9s\n", "Range", "Count")
numBins := len(histogram.bins)
for index, count := range histogram.countPerBin {
if count == 0 {
continue
}
// The last bin represents the bin that contains the range from
// the last bin up to infinity so it's processed differently than the
// other bins.
if index == len(histogram.countPerBin)-1 {
lowerBound := int(histogram.bins[numBins-1])
fmt.Printf("[%10d, %10s) %9d\n", lowerBound, "infinity", count)
continue
}
upperBound := int(histogram.bins[index])
lowerBound := 0
if index > 0 {
lowerBound = int(histogram.bins[index-1])
}
fmt.Printf("[%10d, %10d) %9d\n", lowerBound, upperBound, count)
}
fmt.Println()
}
================================================
FILE: histogram_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestBuildKeyValueSizeHistogram(t *testing.T) {
t.Run("All same size key-values", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
entries := int64(40)
err := db.Update(func(txn *Txn) error {
for i := rune(0); i < rune(entries); i++ {
err := txn.SetEntry(NewEntry([]byte(string(i)), []byte("B")))
if err != nil {
return err
}
}
return nil
})
require.NoError(t, err)
histogram := db.buildHistogram(nil)
keyHistogram := histogram.keySizeHistogram
valueHistogram := histogram.valueSizeHistogram
require.Equal(t, entries, keyHistogram.totalCount)
require.Equal(t, entries, valueHistogram.totalCount)
// Each entry is of size one. So the sum of sizes should be the same
// as number of entries
require.Equal(t, entries, valueHistogram.sum)
require.Equal(t, entries, keyHistogram.sum)
// All value sizes are same. The first bin should have all the values.
require.Equal(t, entries, valueHistogram.countPerBin[0])
require.Equal(t, entries, keyHistogram.countPerBin[0])
require.Equal(t, int64(1), keyHistogram.max)
require.Equal(t, int64(1), keyHistogram.min)
require.Equal(t, int64(1), valueHistogram.max)
require.Equal(t, int64(1), valueHistogram.min)
})
})
t.Run("different size key-values", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
entries := int64(3)
err := db.Update(func(txn *Txn) error {
if err := txn.SetEntry(NewEntry([]byte("A"), []byte("B"))); err != nil {
return err
}
if err := txn.SetEntry(NewEntry([]byte("AA"), []byte("BB"))); err != nil {
return err
}
return txn.SetEntry(NewEntry([]byte("AAA"), []byte("BBB")))
})
require.NoError(t, err)
histogram := db.buildHistogram(nil)
keyHistogram := histogram.keySizeHistogram
valueHistogram := histogram.valueSizeHistogram
require.Equal(t, entries, keyHistogram.totalCount)
require.Equal(t, entries, valueHistogram.totalCount)
// Each entry is of size one. So the sum of sizes should be the same
// as number of entries
require.Equal(t, int64(6), valueHistogram.sum)
require.Equal(t, int64(6), keyHistogram.sum)
// Length 1 key is in first bucket, length 2 and 3 are in the second
// bucket
require.Equal(t, int64(1), valueHistogram.countPerBin[0])
require.Equal(t, int64(2), valueHistogram.countPerBin[1])
require.Equal(t, int64(1), keyHistogram.countPerBin[0])
require.Equal(t, int64(2), keyHistogram.countPerBin[1])
require.Equal(t, int64(3), keyHistogram.max)
require.Equal(t, int64(1), keyHistogram.min)
require.Equal(t, int64(3), valueHistogram.max)
require.Equal(t, int64(1), valueHistogram.min)
})
})
}
================================================
FILE: integration/testgc/.gitignore
================================================
/testgc
================================================
FILE: integration/testgc/main.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package main
import (
"encoding/binary"
"fmt"
"log"
"math/rand"
"net/http"
_ "net/http/pprof" //nolint:gosec
"os"
"sync"
"sync/atomic"
"time"
"github.com/dgraph-io/badger/v4"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2/z"
)
var maxValue int64 = 10000000
var suffix = make([]byte, 128)
type testSuite struct {
sync.Mutex
vals map[uint64]uint64
count atomic.Uint64 // Not under mutex lock.
}
func encoded(i uint64) []byte {
out := make([]byte, 8)
binary.BigEndian.PutUint64(out, i)
return out
}
func (s *testSuite) write(db *badger.DB) error {
return db.Update(func(txn *badger.Txn) error {
for i := 0; i < 10; i++ {
// These keys would be overwritten.
keyi := uint64(rand.Int63n(maxValue))
key := encoded(keyi)
vali := s.count.Add(1)
val := encoded(vali)
val = append(val, suffix...)
if err := txn.SetEntry(badger.NewEntry(key, val)); err != nil {
return err
}
}
for i := 0; i < 20; i++ {
// These keys would be new and never overwritten.
keyi := s.count.Add(1)
if keyi%1000000 == 0 {
log.Printf("Count: %d\n", keyi)
}
key := encoded(keyi)
val := append(key, suffix...)
if err := txn.SetEntry(badger.NewEntry(key, val)); err != nil {
return err
}
}
return nil
})
}
func (s *testSuite) read(db *badger.DB) error {
max := int64(s.count.Load())
keyi := uint64(rand.Int63n(max))
key := encoded(keyi)
err := db.View(func(txn *badger.Txn) error {
item, err := txn.Get(key)
if err != nil {
return err
}
val, err := item.ValueCopy(nil)
if err != nil {
return err
}
y.AssertTruef(len(val) == len(suffix)+8, "Found val of len: %d\n", len(val))
vali := binary.BigEndian.Uint64(val[0:8])
s.Lock()
expected := s.vals[keyi]
if vali < expected {
log.Fatalf("Expected: %d. Found: %d. Key: %d\n", expected, vali, keyi)
} else if vali == expected {
// pass
} else {
s.vals[keyi] = vali
}
s.Unlock()
return nil
})
if err == badger.ErrKeyNotFound {
return nil
}
return err
}
func main() {
fmt.Println("Badger Integration test for value log GC.")
dir := "/mnt/drive/badgertest"
os.RemoveAll(dir)
db, err := badger.Open(badger.DefaultOptions(dir).
WithSyncWrites(false))
if err != nil {
log.Fatal(err)
}
defer db.Close()
go func() {
_ = http.ListenAndServe("localhost:8080", nil)
}()
closer := z.NewCloser(11)
go func() {
// Run value log GC.
defer closer.Done()
var count int
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
for range ticker.C {
again:
select {
case <-closer.HasBeenClosed():
log.Printf("Num times value log GC was successful: %d\n", count)
return
default:
}
log.Printf("Starting a value log GC")
err := db.RunValueLogGC(0.1)
log.Printf("Result of value log GC: %v\n", err)
if err == nil {
count++
goto again
}
}
}()
s := testSuite{vals: make(map[uint64]uint64)}
s.count.Store(uint64(maxValue))
var numLoops atomic.Uint64
ticker := time.NewTicker(5 * time.Second)
for i := 0; i < 10; i++ {
go func() {
defer closer.Done()
for {
if err := s.write(db); err != nil {
log.Fatal(err)
}
for j := 0; j < 10; j++ {
if err := s.read(db); err != nil {
log.Fatal(err)
}
}
nl := numLoops.Add(1)
select {
case <-closer.HasBeenClosed():
return
case <-ticker.C:
log.Printf("Num loops: %d\n", nl)
default:
}
}
}()
}
time.Sleep(5 * time.Minute)
log.Println("Signaling...")
closer.SignalAndWait()
log.Println("Wait done. Now iterating over everything.")
err = db.View(func(txn *badger.Txn) error {
iopts := badger.DefaultIteratorOptions
itr := txn.NewIterator(iopts)
defer itr.Close()
var total, tested int
for itr.Rewind(); itr.Valid(); itr.Next() {
item := itr.Item()
key := item.Key()
keyi := binary.BigEndian.Uint64(key)
total++
val, err := item.ValueCopy(nil)
if err != nil {
return err
}
if len(val) < 8 {
log.Printf("Unexpected value: %x\n", val)
continue
}
vali := binary.BigEndian.Uint64(val[0:8])
expected, ok := s.vals[keyi] // Not all keys must be in vals map.
if ok {
tested++
if vali < expected {
// vali must be equal or greater than what's in the map.
log.Fatalf("Expected: %d. Got: %d. Key: %d\n", expected, vali, keyi)
}
}
}
log.Printf("Total iterated: %d. Tested values: %d\n", total, tested)
return nil
})
if err != nil {
log.Fatalf("Error while iterating: %v", err)
}
log.Println("Iteration done. Test successful.")
time.Sleep(time.Minute) // Time to do some poking around.
}
================================================
FILE: iterator.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"bytes"
"fmt"
"hash/crc32"
"math"
"sort"
"sync"
"time"
"github.com/dgraph-io/badger/v4/table"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2/z"
)
type prefetchStatus uint8
const (
prefetched prefetchStatus = iota + 1
)
// Item is returned during iteration. Both the Key() and Value() output is only valid until
// iterator.Next() is called.
type Item struct {
key []byte
vptr []byte
val []byte
version uint64
expiresAt uint64
slice *y.Slice // Used only during prefetching.
next *Item
txn *Txn
err error
wg sync.WaitGroup
status prefetchStatus
meta byte // We need to store meta to know about bitValuePointer.
userMeta byte
}
// String returns a string representation of Item
func (item *Item) String() string {
return fmt.Sprintf("key=%q, version=%d, meta=%x", item.Key(), item.Version(), item.meta)
}
// Key returns the key.
//
// Key is only valid as long as item is valid, or transaction is valid. If you need to use it
// outside its validity, please use KeyCopy.
func (item *Item) Key() []byte {
return item.key
}
// KeyCopy returns a copy of the key of the item, writing it to dst slice.
// If nil is passed, or capacity of dst isn't sufficient, a new slice would be allocated and
// returned.
func (item *Item) KeyCopy(dst []byte) []byte {
return y.SafeCopy(dst, item.key)
}
// Version returns the commit timestamp of the item.
func (item *Item) Version() uint64 {
return item.version
}
// Value retrieves the value of the item from the value log.
//
// This method must be called within a transaction. Calling it outside a
// transaction is considered undefined behavior. If an iterator is being used,
// then Item.Value() is defined in the current iteration only, because items are
// reused.
//
// If you need to use a value outside a transaction, please use Item.ValueCopy
// instead, or copy it yourself. Value might change once discard or commit is called.
// Use ValueCopy if you want to do a Set after Get.
func (item *Item) Value(fn func(val []byte) error) error {
item.wg.Wait()
if item.status == prefetched {
if item.err == nil && fn != nil {
if err := fn(item.val); err != nil {
return err
}
}
return item.err
}
buf, cb, err := item.yieldItemValue()
defer runCallback(cb)
if err != nil {
return err
}
if fn != nil {
return fn(buf)
}
return nil
}
// ValueCopy returns a copy of the value of the item from the value log, writing it to dst slice.
// If nil is passed, or capacity of dst isn't sufficient, a new slice would be allocated and
// returned. Tip: It might make sense to reuse the returned slice as dst argument for the next call.
//
// This function is useful in long running iterate/update transactions to avoid a write deadlock.
// See Github issue: https://github.com/dgraph-io/badger/issues/315
func (item *Item) ValueCopy(dst []byte) ([]byte, error) {
item.wg.Wait()
if item.status == prefetched {
return y.SafeCopy(dst, item.val), item.err
}
buf, cb, err := item.yieldItemValue()
defer runCallback(cb)
return y.SafeCopy(dst, buf), err
}
func (item *Item) hasValue() bool {
if item.meta == 0 && item.vptr == nil {
// key not found
return false
}
return true
}
// IsDeletedOrExpired returns true if item contains deleted or expired value.
func (item *Item) IsDeletedOrExpired() bool {
return isDeletedOrExpired(item.meta, item.expiresAt)
}
// DiscardEarlierVersions returns whether the item was created with the
// option to discard earlier versions of a key when multiple are available.
func (item *Item) DiscardEarlierVersions() bool {
return item.meta&bitDiscardEarlierVersions > 0
}
func (item *Item) yieldItemValue() ([]byte, func(), error) {
key := item.Key() // No need to copy.
if !item.hasValue() {
return nil, nil, nil
}
if item.slice == nil {
item.slice = new(y.Slice)
}
if (item.meta & bitValuePointer) == 0 {
val := item.slice.Resize(len(item.vptr))
copy(val, item.vptr)
return val, nil, nil
}
var vp valuePointer
vp.Decode(item.vptr)
db := item.txn.db
result, cb, err := db.vlog.Read(vp, item.slice)
if err != nil {
db.opt.Errorf("Unable to read: Key: %v, Version : %v, meta: %v, userMeta: %v"+
" Error: %v", key, item.version, item.meta, item.userMeta, err)
var txn *Txn
if db.opt.managedTxns {
txn = db.NewTransactionAt(math.MaxUint64, false)
} else {
txn = db.NewTransaction(false)
}
defer txn.Discard()
iopt := DefaultIteratorOptions
iopt.AllVersions = true
iopt.InternalAccess = true
iopt.PrefetchValues = false
it := txn.NewKeyIterator(item.Key(), iopt)
defer it.Close()
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
var vp valuePointer
if item.meta&bitValuePointer > 0 {
vp.Decode(item.vptr)
}
db.opt.Errorf("Key: %v, Version : %v, meta: %v, userMeta: %v valuePointer: %+v",
item.Key(), item.version, item.meta, item.userMeta, vp)
}
}
// Don't return error if we cannot read the value. Just log the error.
return result, cb, nil
}
func runCallback(cb func()) {
if cb != nil {
cb()
}
}
func (item *Item) prefetchValue() {
val, cb, err := item.yieldItemValue()
defer runCallback(cb)
item.err = err
item.status = prefetched
if val == nil {
return
}
buf := item.slice.Resize(len(val))
copy(buf, val)
item.val = buf
}
// EstimatedSize returns the approximate size of the key-value pair.
//
// This can be called while iterating through a store to quickly estimate the
// size of a range of key-value pairs (without fetching the corresponding
// values).
func (item *Item) EstimatedSize() int64 {
if !item.hasValue() {
return 0
}
if (item.meta & bitValuePointer) == 0 {
return int64(len(item.key) + len(item.vptr))
}
var vp valuePointer
vp.Decode(item.vptr)
return int64(vp.Len) // includes key length.
}
// KeySize returns the size of the key.
// Exact size of the key is key + 8 bytes of timestamp
func (item *Item) KeySize() int64 {
return int64(len(item.key))
}
// ValueSize returns the approximate size of the value.
//
// This can be called to quickly estimate the size of a value without fetching
// it.
func (item *Item) ValueSize() int64 {
if !item.hasValue() {
return 0
}
if (item.meta & bitValuePointer) == 0 {
return int64(len(item.vptr))
}
var vp valuePointer
vp.Decode(item.vptr)
klen := int64(len(item.key) + 8) // 8 bytes for timestamp.
// 6 bytes are for the approximate length of the header. Since header is encoded in varint, we
// cannot find the exact length of header without fetching it.
return int64(vp.Len) - klen - 6 - crc32.Size
}
// UserMeta returns the userMeta set by the user. Typically, this byte, optionally set by the user
// is used to interpret the value.
func (item *Item) UserMeta() byte {
return item.userMeta
}
// ExpiresAt returns a Unix time value indicating when the item will be
// considered expired. 0 indicates that the item will never expire.
func (item *Item) ExpiresAt() uint64 {
return item.expiresAt
}
// TODO: Switch this to use linked list container in Go.
type list struct {
head *Item
tail *Item
}
func (l *list) push(i *Item) {
i.next = nil
if l.tail == nil {
l.head = i
l.tail = i
return
}
l.tail.next = i
l.tail = i
}
func (l *list) pop() *Item {
if l.head == nil {
return nil
}
i := l.head
if l.head == l.tail {
l.tail = nil
l.head = nil
} else {
l.head = i.next
}
i.next = nil
return i
}
// IteratorOptions is used to set options when iterating over Badger key-value
// stores.
//
// This package provides DefaultIteratorOptions which contains options that
// should work for most applications. Consider using that as a starting point
// before customizing it for your own needs.
type IteratorOptions struct {
// PrefetchSize is the number of KV pairs to prefetch while iterating.
// Valid only if PrefetchValues is true.
PrefetchSize int
// PrefetchValues Indicates whether we should prefetch values during
// iteration and store them.
PrefetchValues bool
Reverse bool // Direction of iteration. False is forward, true is backward.
AllVersions bool // Fetch all valid versions of the same key.
InternalAccess bool // Used to allow internal access to badger keys.
// The following option is used to narrow down the SSTables that iterator
// picks up. If Prefix is specified, only tables which could have this
// prefix are picked based on their range of keys.
prefixIsKey bool // If set, use the prefix for bloom filter lookup.
Prefix []byte // Only iterate over this given prefix.
SinceTs uint64 // Only read data that has version > SinceTs.
}
func (opt *IteratorOptions) compareToPrefix(key []byte) int {
// We should compare key without timestamp. For example key - a[TS] might be > "aa" prefix.
key = y.ParseKey(key)
if len(key) > len(opt.Prefix) {
key = key[:len(opt.Prefix)]
}
return bytes.Compare(key, opt.Prefix)
}
func (opt *IteratorOptions) pickTable(t table.TableInterface) bool {
// Ignore this table if its max version is less than the sinceTs.
if t.MaxVersion() < opt.SinceTs {
return false
}
if len(opt.Prefix) == 0 {
return true
}
if opt.compareToPrefix(t.Smallest()) > 0 {
return false
}
if opt.compareToPrefix(t.Biggest()) < 0 {
return false
}
// Bloom filter lookup would only work if opt.Prefix does NOT have the read
// timestamp as part of the key.
if opt.prefixIsKey && t.DoesNotHave(y.Hash(opt.Prefix)) {
return false
}
return true
}
// pickTables picks the necessary table for the iterator. This function also assumes
// that the tables are sorted in the right order.
func (opt *IteratorOptions) pickTables(all []*table.Table) []*table.Table {
filterTables := func(tables []*table.Table) []*table.Table {
if opt.SinceTs > 0 {
tmp := tables[:0]
for _, t := range tables {
if t.MaxVersion() < opt.SinceTs {
continue
}
tmp = append(tmp, t)
}
tables = tmp
}
return tables
}
if len(opt.Prefix) == 0 {
out := make([]*table.Table, len(all))
copy(out, all)
return filterTables(out)
}
sIdx := sort.Search(len(all), func(i int) bool {
// table.Biggest >= opt.prefix
// if opt.Prefix < table.Biggest, then surely it is not in any of the preceding tables.
return opt.compareToPrefix(all[i].Biggest()) >= 0
})
if sIdx == len(all) {
// Not found.
return []*table.Table{}
}
filtered := all[sIdx:]
if !opt.prefixIsKey {
eIdx := sort.Search(len(filtered), func(i int) bool {
return opt.compareToPrefix(filtered[i].Smallest()) > 0
})
out := make([]*table.Table, len(filtered[:eIdx]))
copy(out, filtered[:eIdx])
return filterTables(out)
}
// opt.prefixIsKey == true. This code is optimizing for opt.prefixIsKey part.
var out []*table.Table
hash := y.Hash(opt.Prefix)
for _, t := range filtered {
// When we encounter the first table whose smallest key is higher than opt.Prefix, we can
// stop. This is an IMPORTANT optimization, just considering how often we call
// NewKeyIterator.
if opt.compareToPrefix(t.Smallest()) > 0 {
// if table.Smallest > opt.Prefix, then this and all tables after this can be ignored.
break
}
// opt.Prefix is actually the key. So, we can run bloom filter checks
// as well.
if t.DoesNotHave(hash) {
continue
}
out = append(out, t)
}
return filterTables(out)
}
// DefaultIteratorOptions contains default options when iterating over Badger key-value stores.
var DefaultIteratorOptions = IteratorOptions{
PrefetchValues: true,
PrefetchSize: 100,
Reverse: false,
AllVersions: false,
}
// Iterator helps iterating over the KV pairs in a lexicographically sorted order.
type Iterator struct {
iitr y.Iterator
txn *Txn
readTs uint64
opt IteratorOptions
item *Item
data list
waste list
lastKey []byte // Used to skip over multiple versions of the same key.
closed bool
scanned int // Used to estimate the size of data scanned by iterator.
// ThreadId is an optional value that can be set to identify which goroutine created
// the iterator. It can be used, for example, to uniquely identify each of the
// iterators created by the stream interface
ThreadId int
Alloc *z.Allocator
}
// NewIterator returns a new iterator. Depending upon the options, either only keys, or both
// key-value pairs would be fetched. The keys are returned in lexicographically sorted order.
// Using prefetch is recommended if you're doing a long running iteration, for performance.
//
// Multiple Iterators:
// For a read-only txn, multiple iterators can be running simultaneously. However, for a read-write
// txn, iterators have the nuance of being a snapshot of the writes for the transaction at the time
// iterator was created. If writes are performed after an iterator is created, then that iterator
// will not be able to see those writes. Only writes performed before an iterator was created can be
// viewed.
func (txn *Txn) NewIterator(opt IteratorOptions) *Iterator {
if txn.discarded {
panic(ErrDiscardedTxn)
}
if txn.db.IsClosed() {
panic(ErrDBClosed)
}
y.NumIteratorsCreatedAdd(txn.db.opt.MetricsEnabled, 1)
// Keep track of the number of active iterators.
txn.numIterators.Add(1)
// TODO: If Prefix is set, only pick those memtables which have keys with the prefix.
tables, decr := txn.db.getMemTables()
defer decr()
txn.db.vlog.incrIteratorCount()
var iters []y.Iterator
if itr := txn.newPendingWritesIterator(opt.Reverse); itr != nil {
iters = append(iters, itr)
}
for i := 0; i < len(tables); i++ {
iters = append(iters, tables[i].sl.NewUniIterator(opt.Reverse))
}
iters = txn.db.lc.appendIterators(iters, &opt) // This will increment references.
res := &Iterator{
txn: txn,
iitr: table.NewMergeIterator(iters, opt.Reverse),
opt: opt,
readTs: txn.readTs,
}
return res
}
// NewKeyIterator is just like NewIterator, but allows the user to iterate over all versions of a
// single key. Internally, it sets the Prefix option in provided opt, and uses that prefix to
// additionally run bloom filter lookups before picking tables from the LSM tree.
func (txn *Txn) NewKeyIterator(key []byte, opt IteratorOptions) *Iterator {
if len(opt.Prefix) > 0 {
panic("opt.Prefix should be nil for NewKeyIterator.")
}
opt.Prefix = key // This key must be without the timestamp.
opt.prefixIsKey = true
opt.AllVersions = true
return txn.NewIterator(opt)
}
func (it *Iterator) newItem() *Item {
item := it.waste.pop()
if item == nil {
item = &Item{slice: new(y.Slice), txn: it.txn}
}
return item
}
// Item returns pointer to the current key-value pair.
// This item is only valid until it.Next() gets called.
func (it *Iterator) Item() *Item {
tx := it.txn
tx.addReadKey(it.item.Key())
return it.item
}
// Valid returns false when iteration is done.
func (it *Iterator) Valid() bool {
if it.item == nil {
return false
}
if it.opt.prefixIsKey {
return bytes.Equal(it.item.key, it.opt.Prefix)
}
return bytes.HasPrefix(it.item.key, it.opt.Prefix)
}
// ValidForPrefix returns false when iteration is done
// or when the current key is not prefixed by the specified prefix.
func (it *Iterator) ValidForPrefix(prefix []byte) bool {
return it.Valid() && bytes.HasPrefix(it.item.key, prefix)
}
// Close would close the iterator. It is important to call this when you're done with iteration.
func (it *Iterator) Close() {
if it.closed {
return
}
it.closed = true
if it.iitr == nil {
it.txn.numIterators.Add(-1)
return
}
it.iitr.Close()
// It is important to wait for the fill goroutines to finish. Otherwise, we might leave zombie
// goroutines behind, which are waiting to acquire file read locks after DB has been closed.
waitFor := func(l list) {
item := l.pop()
for item != nil {
item.wg.Wait()
item = l.pop()
}
}
waitFor(it.waste)
waitFor(it.data)
// TODO: We could handle this error.
_ = it.txn.db.vlog.decrIteratorCount()
it.txn.numIterators.Add(-1)
}
// Next would advance the iterator by one. Always check it.Valid() after a Next()
// to ensure you have access to a valid it.Item().
func (it *Iterator) Next() {
if it.iitr == nil {
return
}
// Reuse current item
it.item.wg.Wait() // Just cleaner to wait before pushing to avoid doing ref counting.
it.scanned += len(it.item.key) + len(it.item.val) + len(it.item.vptr) + 2
it.waste.push(it.item)
// Set next item to current
it.item = it.data.pop()
for it.iitr.Valid() && hasPrefix(it) {
if it.parseItem() {
// parseItem calls one extra next.
// This is used to deal with the complexity of reverse iteration.
break
}
}
}
func isDeletedOrExpired(meta byte, expiresAt uint64) bool {
if meta&bitDelete > 0 {
return true
}
if expiresAt == 0 {
return false
}
return expiresAt <= uint64(time.Now().Unix())
}
// parseItem is a complex function because it needs to handle both forward and reverse iteration
// implementation. We store keys such that their versions are sorted in descending order. This makes
// forward iteration efficient, but revese iteration complicated. This tradeoff is better because
// forward iteration is more common than reverse. It returns true, if either the iterator is invalid
// or it has pushed an item into it.data list, else it returns false.
//
// This function advances the iterator.
func (it *Iterator) parseItem() bool {
mi := it.iitr
key := mi.Key()
setItem := func(item *Item) {
if it.item == nil {
it.item = item
} else {
it.data.push(item)
}
}
isInternalKey := bytes.HasPrefix(key, badgerPrefix)
// Skip badger keys.
if !it.opt.InternalAccess && isInternalKey {
mi.Next()
return false
}
// Skip any versions which are beyond the readTs.
version := y.ParseTs(key)
// Ignore everything that is above the readTs and below or at the sinceTs.
if version > it.readTs || (it.opt.SinceTs > 0 && version <= it.opt.SinceTs) {
mi.Next()
return false
}
// Skip banned keys only if it does not have badger internal prefix.
if !isInternalKey && it.txn.db.isBanned(key) != nil {
mi.Next()
return false
}
if it.opt.AllVersions {
// Return deleted or expired values also, otherwise user can't figure out
// whether the key was deleted.
item := it.newItem()
it.fill(item)
setItem(item)
mi.Next()
return true
}
// If iterating in forward direction, then just checking the last key against current key would
// be sufficient.
if !it.opt.Reverse {
if y.SameKey(it.lastKey, key) {
mi.Next()
return false
}
// Only track in forward direction.
// We should update lastKey as soon as we find a different key in our snapshot.
// Consider keys: a 5, b 7 (del), b 5. When iterating, lastKey = a.
// Then we see b 7, which is deleted. If we don't store lastKey = b, we'll then return b 5,
// which is wrong. Therefore, update lastKey here.
it.lastKey = y.SafeCopy(it.lastKey, mi.Key())
}
FILL:
// If deleted, advance and return.
vs := mi.Value()
if isDeletedOrExpired(vs.Meta, vs.ExpiresAt) {
mi.Next()
return false
}
item := it.newItem()
it.fill(item)
// fill item based on current cursor position. All Next calls have returned, so reaching here
// means no Next was called.
mi.Next() // Advance but no fill item yet.
if !it.opt.Reverse || !mi.Valid() { // Forward direction, or invalid.
setItem(item)
return true
}
// Reverse direction.
nextTs := y.ParseTs(mi.Key())
mik := y.ParseKey(mi.Key())
if nextTs <= it.readTs && bytes.Equal(mik, item.key) {
// This is a valid potential candidate.
goto FILL
}
// Ignore the next candidate. Return the current one.
setItem(item)
return true
}
func (it *Iterator) fill(item *Item) {
vs := it.iitr.Value()
item.meta = vs.Meta
item.userMeta = vs.UserMeta
item.expiresAt = vs.ExpiresAt
item.version = y.ParseTs(it.iitr.Key())
item.key = y.SafeCopy(item.key, y.ParseKey(it.iitr.Key()))
item.vptr = y.SafeCopy(item.vptr, vs.Value)
item.val = nil
if it.opt.PrefetchValues {
item.wg.Add(1)
go func() {
// FIXME we are not handling errors here.
item.prefetchValue()
item.wg.Done()
}()
}
}
func hasPrefix(it *Iterator) bool {
// We shouldn't check prefix in case the iterator is going in reverse. Since in reverse we expect
// people to append items to the end of prefix.
if !it.opt.Reverse && len(it.opt.Prefix) > 0 {
return bytes.HasPrefix(y.ParseKey(it.iitr.Key()), it.opt.Prefix)
}
return true
}
func (it *Iterator) prefetch() {
prefetchSize := 2
if it.opt.PrefetchValues && it.opt.PrefetchSize > 1 {
prefetchSize = it.opt.PrefetchSize
}
i := it.iitr
var count int
it.item = nil
for i.Valid() && hasPrefix(it) {
if !it.parseItem() {
continue
}
count++
if count == prefetchSize {
break
}
}
}
// Seek would seek to the provided key if present. If absent, it would seek to the next
// smallest key greater than the provided key if iterating in the forward direction.
// Behavior would be reversed if iterating backwards.
func (it *Iterator) Seek(key []byte) {
if it.iitr == nil {
return
}
if len(key) > 0 {
it.txn.addReadKey(key)
}
for i := it.data.pop(); i != nil; i = it.data.pop() {
i.wg.Wait()
it.waste.push(i)
}
it.lastKey = it.lastKey[:0]
if len(key) == 0 {
key = it.opt.Prefix
}
if len(key) == 0 {
it.iitr.Rewind()
it.prefetch()
return
}
if !it.opt.Reverse {
key = y.KeyWithTs(key, it.txn.readTs)
} else {
key = y.KeyWithTs(key, 0)
}
it.iitr.Seek(key)
it.prefetch()
}
// Rewind would rewind the iterator cursor all the way to zero-th position, which would be the
// smallest key if iterating forward, and largest if iterating backward. It does not keep track of
// whether the cursor started with a Seek().
func (it *Iterator) Rewind() {
it.Seek(nil)
}
================================================
FILE: iterator_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"bytes"
"fmt"
"math"
"math/rand"
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/require"
"github.com/dgraph-io/badger/v4/options"
"github.com/dgraph-io/badger/v4/table"
"github.com/dgraph-io/badger/v4/y"
)
type tableMock struct {
left, right []byte
}
func (tm *tableMock) Smallest() []byte { return tm.left }
func (tm *tableMock) Biggest() []byte { return tm.right }
func (tm *tableMock) DoesNotHave(hash uint32) bool { return false }
func (tm *tableMock) MaxVersion() uint64 { return math.MaxUint64 }
func TestPickTables(t *testing.T) {
opt := DefaultIteratorOptions
within := func(prefix, left, right []byte) {
opt.Prefix = prefix
// PickTable expects smallest and biggest to contain timestamps.
tm := &tableMock{left: y.KeyWithTs(left, 1), right: y.KeyWithTs(right, 1)}
require.True(t, opt.pickTable(tm), "within failed for %b %b %b\n", prefix, left, right)
}
outside := func(prefix, left, right string) {
opt.Prefix = []byte(prefix)
// PickTable expects smallest and biggest to contain timestamps.
tm := &tableMock{left: y.KeyWithTs([]byte(left), 1), right: y.KeyWithTs([]byte(right), 1)}
require.False(t, opt.pickTable(tm), "outside failed for %b %b %b", prefix, left, right)
}
within([]byte("abc"), []byte("ab"), []byte("ad"))
within([]byte("abc"), []byte("abc"), []byte("ad"))
within([]byte("abc"), []byte("abb123"), []byte("ad"))
within([]byte("abc"), []byte("abc123"), []byte("abd234"))
within([]byte("abc"), []byte("abc123"), []byte("abc456"))
// Regression test for https://github.com/dgraph-io/badger/issues/992
within([]byte{0, 0, 1}, []byte{0}, []byte{0, 0, 1})
outside("abd", "abe", "ad")
outside("abd", "ac", "ad")
outside("abd", "b", "e")
outside("abd", "a", "ab")
outside("abd", "ab", "abc")
outside("abd", "ab", "abc123")
}
func TestPickSortTables(t *testing.T) {
type MockKeys struct {
small string
large string
}
genTables := func(mks ...MockKeys) []*table.Table {
out := make([]*table.Table, 0)
for _, mk := range mks {
opts := table.Options{ChkMode: options.OnTableAndBlockRead}
tbl := buildTable(t, [][]string{{mk.small, "some value"},
{mk.large, "some value"}}, opts)
defer func() { require.NoError(t, tbl.DecrRef()) }()
out = append(out, tbl)
}
return out
}
tables := genTables(MockKeys{small: "a", large: "abc"},
MockKeys{small: "abcd", large: "cde"},
MockKeys{small: "cge", large: "chf"},
MockKeys{small: "glr", large: "gyup"})
opt := DefaultIteratorOptions
opt.prefixIsKey = false
opt.Prefix = []byte("c")
filtered := opt.pickTables(tables)
require.Equal(t, 2, len(filtered))
// build table adds time stamp so removing tailing bytes.
require.Equal(t, filtered[0].Smallest()[:4], []byte("abcd"))
require.Equal(t, filtered[1].Smallest()[:3], []byte("cge"))
tables = genTables(MockKeys{small: "a", large: "abc"},
MockKeys{small: "abcd", large: "ade"},
MockKeys{small: "cge", large: "chf"},
MockKeys{small: "glr", large: "gyup"})
filtered = opt.pickTables(tables)
require.Equal(t, 1, len(filtered))
require.Equal(t, filtered[0].Smallest()[:3], []byte("cge"))
tables = genTables(MockKeys{small: "a", large: "abc"},
MockKeys{small: "abcd", large: "ade"},
MockKeys{small: "cge", large: "chf"},
MockKeys{small: "ckr", large: "cyup"},
MockKeys{small: "csfr", large: "gyup"})
filtered = opt.pickTables(tables)
require.Equal(t, 3, len(filtered))
require.Equal(t, filtered[0].Smallest()[:3], []byte("cge"))
require.Equal(t, filtered[1].Smallest()[:3], []byte("ckr"))
require.Equal(t, filtered[2].Smallest()[:4], []byte("csfr"))
opt.Prefix = []byte("aa")
filtered = opt.pickTables(tables)
require.Equal(t, y.ParseKey(filtered[0].Smallest()), []byte("a"))
require.Equal(t, y.ParseKey(filtered[0].Biggest()), []byte("abc"))
}
func TestIterateSinceTs(t *testing.T) {
bkey := func(i int) []byte {
return []byte(fmt.Sprintf("%04d", i))
}
val := []byte("OK")
n := 100000
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
batch := db.NewWriteBatch()
for i := 0; i < n; i++ {
if (i % 10000) == 0 {
t.Logf("Put i=%d\n", i)
}
require.NoError(t, batch.Set(bkey(i), val))
}
require.NoError(t, batch.Flush())
maxVs := db.MaxVersion()
sinceTs := maxVs - maxVs/10
iopt := DefaultIteratorOptions
iopt.SinceTs = sinceTs
require.NoError(t, db.View(func(txn *Txn) error {
it := txn.NewIterator(iopt)
defer it.Close()
for it.Rewind(); it.Valid(); it.Next() {
i := it.Item()
require.GreaterOrEqual(t, i.Version(), sinceTs)
}
return nil
}))
})
}
func TestIterateSinceTsWithPendingWrites(t *testing.T) {
// The pending entries still have version=0. Even IteratorOptions.SinceTs is 0, the entries
// should be visible.
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
txn := db.NewTransaction(true)
defer txn.Discard()
require.NoError(t, txn.Set([]byte("key1"), []byte("value1")))
require.NoError(t, txn.Set([]byte("key2"), []byte("value2")))
itr := txn.NewIterator(DefaultIteratorOptions)
defer itr.Close()
count := 0
for itr.Rewind(); itr.Valid(); itr.Next() {
count++
}
require.Equal(t, 2, count)
})
}
func TestIteratePrefix(t *testing.T) {
if !*manual {
t.Skip("Skipping test meant to be run manually.")
return
}
testIteratorPrefix := func(t *testing.T, db *DB) {
bkey := func(i int) []byte {
return []byte(fmt.Sprintf("%04d", i))
}
val := []byte("OK")
n := 10000
batch := db.NewWriteBatch()
for i := 0; i < n; i++ {
if (i % 1000) == 0 {
t.Logf("Put i=%d\n", i)
}
require.NoError(t, batch.Set(bkey(i), val))
}
require.NoError(t, batch.Flush())
countKeys := func(prefix string) int {
t.Logf("Testing with prefix: %s", prefix)
var count int
opt := DefaultIteratorOptions
opt.Prefix = []byte(prefix)
err := db.View(func(txn *Txn) error {
itr := txn.NewIterator(opt)
defer itr.Close()
for itr.Rewind(); itr.Valid(); itr.Next() {
item := itr.Item()
err := item.Value(func(v []byte) error {
require.Equal(t, val, v)
return nil
})
require.NoError(t, err)
require.True(t, bytes.HasPrefix(item.Key(), opt.Prefix))
count++
}
return nil
})
require.NoError(t, err)
return count
}
countOneKey := func(key []byte) int {
var count int
err := db.View(func(txn *Txn) error {
itr := txn.NewKeyIterator(key, DefaultIteratorOptions)
defer itr.Close()
for itr.Rewind(); itr.Valid(); itr.Next() {
item := itr.Item()
err := item.Value(func(v []byte) error {
require.Equal(t, val, v)
return nil
})
require.NoError(t, err)
require.Equal(t, key, item.Key())
count++
}
return nil
})
require.NoError(t, err)
return count
}
for i := 0; i <= 9; i++ {
require.Equal(t, 1, countKeys(fmt.Sprintf("%d%d%d%d", i, i, i, i)))
require.Equal(t, 10, countKeys(fmt.Sprintf("%d%d%d", i, i, i)))
require.Equal(t, 100, countKeys(fmt.Sprintf("%d%d", i, i)))
require.Equal(t, 1000, countKeys(fmt.Sprintf("%d", i)))
}
require.Equal(t, 10000, countKeys(""))
t.Logf("Testing each key with key iterator")
for i := 0; i < n; i++ {
require.Equal(t, 1, countOneKey(bkey(i)))
}
}
t.Run("With Default options", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
testIteratorPrefix(t, db)
})
})
t.Run("With Block Offsets in Cache", func(t *testing.T) {
opts := getTestOptions("")
opts.IndexCacheSize = 100 << 20
runBadgerTest(t, &opts, func(t *testing.T, db *DB) {
testIteratorPrefix(t, db)
})
})
t.Run("With Block Offsets and Blocks in Cache", func(t *testing.T) {
opts := getTestOptions("")
opts.BlockCacheSize = 100 << 20
opts.IndexCacheSize = 100 << 20
runBadgerTest(t, &opts, func(t *testing.T, db *DB) {
testIteratorPrefix(t, db)
})
})
t.Run("With Blocks in Cache", func(t *testing.T) {
opts := getTestOptions("")
opts.BlockCacheSize = 100 << 20
runBadgerTest(t, &opts, func(t *testing.T, db *DB) {
testIteratorPrefix(t, db)
})
})
}
// Sanity test to verify the iterator does not crash the db in readonly mode if data does not exist.
func TestIteratorReadOnlyWithNoData(t *testing.T) {
dir, err := os.MkdirTemp(".", "badger-test")
y.Check(err)
defer removeDir(dir)
opts := getTestOptions(dir)
db, err := Open(opts)
require.NoError(t, err)
require.NoError(t, db.Close())
opts.ReadOnly = true
db, err = Open(opts)
require.NoError(t, err)
defer func() {
require.NoError(t, db.Close())
}()
require.NoError(t, db.View(func(txn *Txn) error {
iopts := DefaultIteratorOptions
iopts.Prefix = []byte("xxx")
itr := txn.NewIterator(iopts)
defer itr.Close()
return nil
}))
}
// go test -v -run=XXX -bench=BenchmarkIterate -benchtime=3s
// Benchmark with opt.Prefix set ===
// goos: linux
// goarch: amd64
// pkg: github.com/dgraph-io/badger
// BenchmarkIteratePrefixSingleKey/Key_lookups-4 10000 365539 ns/op
// --- BENCH: BenchmarkIteratePrefixSingleKey/Key_lookups-4
//
// iterator_test.go:147: Inner b.N: 1
// iterator_test.go:147: Inner b.N: 100
// iterator_test.go:147: Inner b.N: 10000
//
// --- BENCH: BenchmarkIteratePrefixSingleKey
//
// iterator_test.go:143: LSM files: 79
// iterator_test.go:145: Outer b.N: 1
//
// PASS
// ok github.com/dgraph-io/badger 41.586s
//
// Benchmark with NO opt.Prefix set ===
// goos: linux
// goarch: amd64
// pkg: github.com/dgraph-io/badger
// BenchmarkIteratePrefixSingleKey/Key_lookups-4 10000 460924 ns/op
// --- BENCH: BenchmarkIteratePrefixSingleKey/Key_lookups-4
//
// iterator_test.go:147: Inner b.N: 1
// iterator_test.go:147: Inner b.N: 100
// iterator_test.go:147: Inner b.N: 10000
//
// --- BENCH: BenchmarkIteratePrefixSingleKey
//
// iterator_test.go:143: LSM files: 83
// iterator_test.go:145: Outer b.N: 1
//
// PASS
// ok github.com/dgraph-io/badger 41.836s
//
// Only my laptop there's a 20% improvement in latency with ~80 files.
func BenchmarkIteratePrefixSingleKey(b *testing.B) {
dir, err := os.MkdirTemp(".", "badger-test")
y.Check(err)
defer removeDir(dir)
opts := getTestOptions(dir)
db, err := Open(opts)
y.Check(err)
defer db.Close()
N := 100000 // Should generate around 80 SSTables.
val := []byte("OK")
bkey := func(i int) []byte {
return []byte(fmt.Sprintf("%06d", i))
}
batch := db.NewWriteBatch()
for i := 0; i < N; i++ {
y.Check(batch.Set(bkey(i), val))
}
y.Check(batch.Flush())
var lsmFiles int
err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if strings.HasSuffix(path, ".sst") {
lsmFiles++
}
if err != nil {
return err
}
return nil
})
y.Check(err)
b.Logf("LSM files: %d", lsmFiles)
b.Logf("Key splits: %v", db.Ranges(nil, 10000))
b.Logf("Key splits with prefix: %v", db.Ranges([]byte("09"), 10000))
b.Logf("Outer b.N: %d", b.N)
b.Run("Key lookups", func(b *testing.B) {
b.Logf("Inner b.N: %d", b.N)
for i := 0; i < b.N; i++ {
key := bkey(rand.Intn(N))
err := db.View(func(txn *Txn) error {
opt := DefaultIteratorOptions
// NOTE: Comment opt.Prefix out here to compare the performance
// difference between providing Prefix as an option, v/s not. I
// see a 20% improvement when there are ~80 SSTables.
opt.Prefix = key
opt.AllVersions = true
itr := txn.NewIterator(opt)
defer itr.Close()
var count int
for itr.Seek(key); itr.ValidForPrefix(key); itr.Next() {
count++
}
if count != 1 {
b.Fatalf("Count must be one key: %s. Found: %d", key, count)
}
return nil
})
if err != nil {
b.Fatalf("Error while View: %v", err)
}
}
})
}
================================================
FILE: key_registry.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"bytes"
"crypto/aes"
"crypto/rand"
"encoding/binary"
"hash/crc32"
"io"
"os"
"path/filepath"
"sync"
"time"
"github.com/dgraph-io/badger/v4/pb"
"github.com/dgraph-io/badger/v4/y"
"google.golang.org/protobuf/proto"
)
const (
// KeyRegistryFileName is the file name for the key registry file.
KeyRegistryFileName = "KEYREGISTRY"
// KeyRegistryRewriteFileName is the file name for the rewrite key registry file.
KeyRegistryRewriteFileName = "REWRITE-KEYREGISTRY"
)
// SanityText is used to check whether the given user provided storage key is valid or not
var sanityText = []byte("Hello Badger")
// KeyRegistry used to maintain all the data keys.
type KeyRegistry struct {
sync.RWMutex
dataKeys map[uint64]*pb.DataKey
lastCreated int64 //lastCreated is the timestamp(seconds) of the last data key generated.
nextKeyID uint64
fp *os.File
opt KeyRegistryOptions
}
type KeyRegistryOptions struct {
Dir string
ReadOnly bool
EncryptionKey []byte
EncryptionKeyRotationDuration time.Duration
InMemory bool
}
// newKeyRegistry returns KeyRegistry.
func newKeyRegistry(opt KeyRegistryOptions) *KeyRegistry {
return &KeyRegistry{
dataKeys: make(map[uint64]*pb.DataKey),
nextKeyID: 0,
opt: opt,
}
}
// OpenKeyRegistry opens key registry if it exists, otherwise it'll create key registry
// and returns key registry.
func OpenKeyRegistry(opt KeyRegistryOptions) (*KeyRegistry, error) {
// sanity check the encryption key length.
if len(opt.EncryptionKey) > 0 {
switch len(opt.EncryptionKey) {
default:
return nil, y.Wrapf(ErrInvalidEncryptionKey, "During OpenKeyRegistry")
case 16, 24, 32:
break
}
}
// If db is opened in InMemory mode, we don't need to write key registry to the disk.
if opt.InMemory {
return newKeyRegistry(opt), nil
}
path := filepath.Join(opt.Dir, KeyRegistryFileName)
var flags y.Flags
if opt.ReadOnly {
flags |= y.ReadOnly
} else {
flags |= y.Sync
}
fp, err := y.OpenExistingFile(path, flags)
// OpenExistingFile just open file.
// So checking whether the file exist or not. If not
// We'll create new keyregistry.
if os.IsNotExist(err) {
// Creating new registry file if not exist.
kr := newKeyRegistry(opt)
if opt.ReadOnly {
return kr, nil
}
// Writing the key registry to the file.
if err := WriteKeyRegistry(kr, opt); err != nil {
return nil, y.Wrapf(err, "Error while writing key registry.")
}
fp, err = y.OpenExistingFile(path, flags)
if err != nil {
return nil, y.Wrapf(err, "Error while opening newly created key registry.")
}
} else if err != nil {
return nil, y.Wrapf(err, "Error while opening key registry.")
}
kr, err := readKeyRegistry(fp, opt)
if err != nil {
// This case happens only if the file is opened properly and
// not able to read.
fp.Close()
return nil, err
}
if opt.ReadOnly {
// We'll close the file in readonly mode.
return kr, fp.Close()
}
kr.fp = fp
return kr, nil
}
// keyRegistryIterator reads all the datakey from the key registry
type keyRegistryIterator struct {
encryptionKey []byte
fp *os.File
// lenCrcBuf contains crc buf and data length to move forward.
lenCrcBuf [8]byte
}
// newKeyRegistryIterator returns iterator which will allow you to iterate
// over the data key of the key registry.
func newKeyRegistryIterator(fp *os.File, encryptionKey []byte) (*keyRegistryIterator, error) {
return &keyRegistryIterator{
encryptionKey: encryptionKey,
fp: fp,
lenCrcBuf: [8]byte{},
}, validRegistry(fp, encryptionKey)
}
// validRegistry checks that given encryption key is valid or not.
func validRegistry(fp *os.File, encryptionKey []byte) error {
iv := make([]byte, aes.BlockSize)
var err error
if _, err = fp.Read(iv); err != nil {
return y.Wrapf(err, "Error while reading IV for key registry.")
}
eSanityText := make([]byte, len(sanityText))
if _, err = fp.Read(eSanityText); err != nil {
return y.Wrapf(err, "Error while reading sanity text.")
}
if len(encryptionKey) > 0 {
// Decrypting sanity text.
if eSanityText, err = y.XORBlockAllocate(eSanityText, encryptionKey, iv); err != nil {
return y.Wrapf(err, "During validRegistry")
}
}
// Check the given key is valid or not.
if !bytes.Equal(eSanityText, sanityText) {
return ErrEncryptionKeyMismatch
}
return nil
}
func (kri *keyRegistryIterator) next() (*pb.DataKey, error) {
var err error
// Read crc buf and data length.
if _, err = kri.fp.Read(kri.lenCrcBuf[:]); err != nil {
// EOF means end of the iteration.
if err != io.EOF {
return nil, y.Wrapf(err, "While reading crc in keyRegistryIterator.next")
}
return nil, err
}
l := int64(binary.BigEndian.Uint32(kri.lenCrcBuf[0:4]))
// Read protobuf data.
data := make([]byte, l)
if _, err = kri.fp.Read(data); err != nil {
// EOF means end of the iteration.
if err != io.EOF {
return nil, y.Wrapf(err, "While reading protobuf in keyRegistryIterator.next")
}
return nil, err
}
// Check checksum.
if crc32.Checksum(data, y.CastagnoliCrcTable) != binary.BigEndian.Uint32(kri.lenCrcBuf[4:]) {
return nil, y.Wrapf(y.ErrChecksumMismatch, "Error while checking checksum for data key.")
}
dataKey := &pb.DataKey{}
if err = proto.Unmarshal(data, dataKey); err != nil {
return nil, y.Wrapf(err, "While unmarshal of datakey in keyRegistryIterator.next")
}
if len(kri.encryptionKey) > 0 {
// Decrypt the key if the storage key exists.
if dataKey.Data, err = y.XORBlockAllocate(dataKey.Data, kri.encryptionKey, dataKey.Iv); err != nil {
return nil, y.Wrapf(err, "While decrypting datakey in keyRegistryIterator.next")
}
}
return dataKey, nil
}
// readKeyRegistry will read the key registry file and build the key registry struct.
func readKeyRegistry(fp *os.File, opt KeyRegistryOptions) (*KeyRegistry, error) {
itr, err := newKeyRegistryIterator(fp, opt.EncryptionKey)
if err != nil {
return nil, err
}
kr := newKeyRegistry(opt)
var dk *pb.DataKey
dk, err = itr.next()
for err == nil && dk != nil {
if dk.KeyId > kr.nextKeyID {
// Set the maximum key ID for next key ID generation.
kr.nextKeyID = dk.KeyId
}
if dk.CreatedAt > kr.lastCreated {
// Set the last generated key timestamp.
kr.lastCreated = dk.CreatedAt
}
// No need to lock since we are building the initial state.
kr.dataKeys[dk.KeyId] = dk
// Forward the iterator.
dk, err = itr.next()
}
// We read all the key. So, Ignoring this error.
if err == io.EOF {
err = nil
}
return kr, err
}
/*
Structure of Key Registry.
+-------------------+---------------------+--------------------+--------------+------------------+
| IV | Sanity Text | DataKey1 | DataKey2 | ... |
+-------------------+---------------------+--------------------+--------------+------------------+
*/
// WriteKeyRegistry will rewrite the existing key registry file with new one.
// It is okay to give closed key registry. Since, it's using only the datakey.
func WriteKeyRegistry(reg *KeyRegistry, opt KeyRegistryOptions) error {
buf := &bytes.Buffer{}
iv, err := y.GenerateIV()
y.Check(err)
// Encrypt sanity text if the encryption key is presents.
eSanity := sanityText
if len(opt.EncryptionKey) > 0 {
var err error
eSanity, err = y.XORBlockAllocate(eSanity, opt.EncryptionKey, iv)
if err != nil {
return y.Wrapf(err, "Error while encrypting sanity text in WriteKeyRegistry")
}
}
y.Check2(buf.Write(iv))
y.Check2(buf.Write(eSanity))
// Write all the datakeys to the buf.
for _, k := range reg.dataKeys {
// Writing the datakey to the given buffer.
if err := storeDataKey(buf, opt.EncryptionKey, k); err != nil {
return y.Wrapf(err, "Error while storing datakey in WriteKeyRegistry")
}
}
tmpPath := filepath.Join(opt.Dir, KeyRegistryRewriteFileName)
// Open temporary file to write the data and do atomic rename.
fp, err := y.OpenTruncFile(tmpPath, true)
if err != nil {
return y.Wrapf(err, "Error while opening tmp file in WriteKeyRegistry")
}
// Write buf to the disk.
if _, err = fp.Write(buf.Bytes()); err != nil {
// close the fd before returning error. We're not using defer
// because, for windows we need to close the fd explicitly before
// renaming.
fp.Close()
return y.Wrapf(err, "Error while writing buf in WriteKeyRegistry")
}
// In Windows the files should be closed before doing a Rename.
if err = fp.Close(); err != nil {
return y.Wrapf(err, "Error while closing tmp file in WriteKeyRegistry")
}
// Rename to the original file.
if err = os.Rename(tmpPath, filepath.Join(opt.Dir, KeyRegistryFileName)); err != nil {
return y.Wrapf(err, "Error while renaming file in WriteKeyRegistry")
}
// Sync Dir.
return syncDir(opt.Dir)
}
// DataKey returns datakey of the given key id.
func (kr *KeyRegistry) DataKey(id uint64) (*pb.DataKey, error) {
kr.RLock()
defer kr.RUnlock()
if id == 0 {
// nil represent plain text.
return nil, nil
}
dk, ok := kr.dataKeys[id]
if !ok {
return nil, y.Wrapf(ErrInvalidDataKeyID, "Error for the KEY ID %d", id)
}
return dk, nil
}
// LatestDataKey will give you the latest generated datakey based on the rotation
// period. If the last generated datakey lifetime exceeds the rotation period.
// It'll create new datakey.
func (kr *KeyRegistry) LatestDataKey() (*pb.DataKey, error) {
if len(kr.opt.EncryptionKey) == 0 {
// nil is for no encryption.
return nil, nil
}
// validKey return datakey if the last generated key duration less than
// rotation duration.
validKey := func() (*pb.DataKey, bool) {
// Time difference from the last generated time.
diff := time.Since(time.Unix(kr.lastCreated, 0))
if diff < kr.opt.EncryptionKeyRotationDuration {
return kr.dataKeys[kr.nextKeyID], true
}
return nil, false
}
kr.RLock()
key, valid := validKey()
kr.RUnlock()
if valid {
// If less than EncryptionKeyRotationDuration, returns the last generated key.
return key, nil
}
kr.Lock()
defer kr.Unlock()
// Key might have generated by another go routine. So,
// checking once again.
key, valid = validKey()
if valid {
return key, nil
}
k := make([]byte, len(kr.opt.EncryptionKey))
iv, err := y.GenerateIV()
if err != nil {
return nil, err
}
_, err = rand.Read(k)
if err != nil {
return nil, err
}
// Otherwise Increment the KeyID and generate new datakey.
kr.nextKeyID++
dk := &pb.DataKey{
KeyId: kr.nextKeyID,
Data: k,
CreatedAt: time.Now().Unix(),
Iv: iv,
}
// Don't store the datakey on file if badger is running in InMemory mode.
if !kr.opt.InMemory {
// Store the datekey.
buf := &bytes.Buffer{}
if err = storeDataKey(buf, kr.opt.EncryptionKey, dk); err != nil {
return nil, err
}
// Persist the datakey to the disk
if _, err = kr.fp.Write(buf.Bytes()); err != nil {
return nil, err
}
}
// storeDatakey encrypts the datakey So, placing un-encrypted key in the memory.
dk.Data = k
kr.lastCreated = dk.CreatedAt
kr.dataKeys[kr.nextKeyID] = dk
return dk, nil
}
// Close closes the key registry.
func (kr *KeyRegistry) Close() error {
if !(kr.opt.ReadOnly || kr.opt.InMemory) {
return kr.fp.Close()
}
return nil
}
// storeDataKey stores datakey in an encrypted format in the given buffer. If storage key preset.
func storeDataKey(buf *bytes.Buffer, storageKey []byte, k *pb.DataKey) error {
// xor will encrypt the IV and xor with the given data.
// It'll used for both encryption and decryption.
xor := func() error {
if len(storageKey) == 0 {
return nil
}
var err error
k.Data, err = y.XORBlockAllocate(k.Data, storageKey, k.Iv)
return err
}
// In memory datakey will be plain text so encrypting before storing to the disk.
var err error
if err = xor(); err != nil {
return y.Wrapf(err, "Error while encrypting datakey in storeDataKey")
}
var data []byte
if data, err = proto.Marshal(k); err != nil {
err = y.Wrapf(err, "Error while marshaling datakey in storeDataKey")
var err2 error
// decrypting the datakey back.
if err2 = xor(); err2 != nil {
return y.Wrapf(err,
y.Wrapf(err2, "Error while decrypting datakey in storeDataKey").Error())
}
return err
}
var lenCrcBuf [8]byte
binary.BigEndian.PutUint32(lenCrcBuf[0:4], uint32(len(data)))
binary.BigEndian.PutUint32(lenCrcBuf[4:8], crc32.Checksum(data, y.CastagnoliCrcTable))
y.Check2(buf.Write(lenCrcBuf[:]))
y.Check2(buf.Write(data))
// Decrypting the datakey back since we're using the pointer.
return xor()
}
================================================
FILE: key_registry_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"math/rand"
"os"
"testing"
"github.com/stretchr/testify/require"
)
func getRegistryTestOptions(dir string, key []byte) KeyRegistryOptions {
return KeyRegistryOptions{
Dir: dir,
EncryptionKey: key,
ReadOnly: false,
}
}
func TestBuildRegistry(t *testing.T) {
encryptionKey := make([]byte, 32)
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
_, err = rand.Read(encryptionKey)
require.NoError(t, err)
opt := getRegistryTestOptions(dir, encryptionKey)
kr, err := OpenKeyRegistry(opt)
require.NoError(t, err)
dk, err := kr.LatestDataKey()
require.NoError(t, err)
// We're resetting the last created timestamp. So, it creates
// new datakey.
kr.lastCreated = 0
dk1, err := kr.LatestDataKey()
// We generated two key. So, checking the length.
require.Equal(t, 2, len(kr.dataKeys))
require.NoError(t, err)
require.NoError(t, kr.Close())
kr2, err := OpenKeyRegistry(opt)
require.NoError(t, err)
require.Equal(t, 2, len(kr2.dataKeys))
// Asserting the correctness of the datakey after opening the registry.
require.Equal(t, dk.Data, kr.dataKeys[dk.KeyId].Data)
require.Equal(t, dk1.Data, kr.dataKeys[dk1.KeyId].Data)
require.NoError(t, kr2.Close())
}
func TestRewriteRegistry(t *testing.T) {
encryptionKey := make([]byte, 32)
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
_, err = rand.Read(encryptionKey)
require.NoError(t, err)
opt := getRegistryTestOptions(dir, encryptionKey)
kr, err := OpenKeyRegistry(opt)
require.NoError(t, err)
_, err = kr.LatestDataKey()
require.NoError(t, err)
// We're resetting the last created timestamp. So, it creates
// new datakey.
kr.lastCreated = 0
_, err = kr.LatestDataKey()
require.NoError(t, err)
require.NoError(t, kr.Close())
delete(kr.dataKeys, 1)
require.NoError(t, WriteKeyRegistry(kr, opt))
kr2, err := OpenKeyRegistry(opt)
require.NoError(t, err)
require.Equal(t, 1, len(kr2.dataKeys))
require.NoError(t, kr2.Close())
}
func TestMismatch(t *testing.T) {
encryptionKey := make([]byte, 32)
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
_, err = rand.Read(encryptionKey)
require.NoError(t, err)
opt := getRegistryTestOptions(dir, encryptionKey)
kr, err := OpenKeyRegistry(opt)
require.NoError(t, err)
require.NoError(t, kr.Close())
// Opening with the same key and asserting.
kr, err = OpenKeyRegistry(opt)
require.NoError(t, err)
require.NoError(t, kr.Close())
// Opening with the invalid key and asserting.
encryptionKey = make([]byte, 32)
_, err = rand.Read(encryptionKey)
require.NoError(t, err)
opt.EncryptionKey = encryptionKey
_, err = OpenKeyRegistry(opt)
require.Error(t, err)
require.EqualError(t, err, ErrEncryptionKeyMismatch.Error())
}
func TestEncryptionAndDecryption(t *testing.T) {
encryptionKey := make([]byte, 32)
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
_, err = rand.Read(encryptionKey)
require.NoError(t, err)
opt := getRegistryTestOptions(dir, encryptionKey)
kr, err := OpenKeyRegistry(opt)
require.NoError(t, err)
dk, err := kr.LatestDataKey()
require.NoError(t, err)
require.NoError(t, kr.Close())
// Checking the correctness of the datakey after closing and
// opening the key registry.
kr, err = OpenKeyRegistry(opt)
require.NoError(t, err)
dk1, err := kr.DataKey(dk.GetKeyId())
require.NoError(t, err)
require.Equal(t, dk.Data, dk1.Data)
require.NoError(t, kr.Close())
}
func TestKeyRegistryInMemory(t *testing.T) {
encryptionKey := make([]byte, 32)
_, err := rand.Read(encryptionKey)
require.NoError(t, err)
opt := getRegistryTestOptions("", encryptionKey)
opt.InMemory = true
kr, err := OpenKeyRegistry(opt)
require.NoError(t, err)
_, err = kr.LatestDataKey()
require.NoError(t, err)
// We're resetting the last created timestamp. So, it creates
// new datakey.
kr.lastCreated = 0
_, err = kr.LatestDataKey()
// We generated two key. So, checking the length.
require.Equal(t, 2, len(kr.dataKeys))
require.NoError(t, err)
require.NoError(t, kr.Close())
}
================================================
FILE: level_handler.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"fmt"
"sort"
"sync"
"github.com/dgraph-io/badger/v4/table"
"github.com/dgraph-io/badger/v4/y"
)
type levelHandler struct {
// Guards tables, totalSize.
sync.RWMutex
// For level >= 1, tables are sorted by key ranges, which do not overlap.
// For level 0, tables are sorted by time.
// For level 0, newest table are at the back. Compact the oldest one first, which is at the front.
tables []*table.Table
totalSize int64
totalStaleSize int64
// The following are initialized once and const.
level int
strLevel string
db *DB
}
func (s *levelHandler) isLastLevel() bool {
return s.level == s.db.opt.MaxLevels-1
}
func (s *levelHandler) getTotalStaleSize() int64 {
s.RLock()
defer s.RUnlock()
return s.totalStaleSize
}
func (s *levelHandler) getTotalSize() int64 {
s.RLock()
defer s.RUnlock()
return s.totalSize
}
// initTables replaces s.tables with given tables. This is done during loading.
func (s *levelHandler) initTables(tables []*table.Table) {
s.Lock()
defer s.Unlock()
s.tables = tables
s.totalSize = 0
s.totalStaleSize = 0
for _, t := range tables {
s.addSize(t)
}
if s.level == 0 {
// Key range will overlap. Just sort by fileID in ascending order
// because newer tables are at the end of level 0.
sort.Slice(s.tables, func(i, j int) bool {
return s.tables[i].ID() < s.tables[j].ID()
})
} else {
// Sort tables by keys.
sort.Slice(s.tables, func(i, j int) bool {
return y.CompareKeys(s.tables[i].Smallest(), s.tables[j].Smallest()) < 0
})
}
}
// deleteTables remove tables idx0, ..., idx1-1.
func (s *levelHandler) deleteTables(toDel []*table.Table) error {
s.Lock() // s.Unlock() below
toDelMap := make(map[uint64]struct{})
for _, t := range toDel {
toDelMap[t.ID()] = struct{}{}
}
// Make a copy as iterators might be keeping a slice of tables.
var newTables []*table.Table
for _, t := range s.tables {
_, found := toDelMap[t.ID()]
if !found {
newTables = append(newTables, t)
continue
}
s.subtractSize(t)
}
s.tables = newTables
s.Unlock() // Unlock s _before_ we DecrRef our tables, which can be slow.
return decrRefs(toDel)
}
// replaceTables will replace tables[left:right] with newTables. Note this EXCLUDES tables[right].
// You must call decr() to delete the old tables _after_ writing the update to the manifest.
func (s *levelHandler) replaceTables(toDel, toAdd []*table.Table) error {
// Need to re-search the range of tables in this level to be replaced as other goroutines might
// be changing it as well. (They can't touch our tables, but if they add/remove other tables,
// the indices get shifted around.)
s.Lock() // We s.Unlock() below.
toDelMap := make(map[uint64]struct{})
for _, t := range toDel {
toDelMap[t.ID()] = struct{}{}
}
var newTables []*table.Table
for _, t := range s.tables {
_, found := toDelMap[t.ID()]
if !found {
newTables = append(newTables, t)
continue
}
s.subtractSize(t)
}
// Increase totalSize first.
for _, t := range toAdd {
s.addSize(t)
t.IncrRef()
newTables = append(newTables, t)
}
// Assign tables.
s.tables = newTables
sort.Slice(s.tables, func(i, j int) bool {
return y.CompareKeys(s.tables[i].Smallest(), s.tables[j].Smallest()) < 0
})
s.Unlock() // s.Unlock before we DecrRef tables -- that can be slow.
return decrRefs(toDel)
}
// addTable adds toAdd table to levelHandler. Normally when we add tables to levelHandler, we sort
// tables based on table.Smallest. This is required for correctness of the system. But in case of
// stream writer this can be avoided. We can just add tables to levelHandler's table list
// and after all addTable calls, we can sort table list(check sortTable method).
// NOTE: levelHandler.sortTables() should be called after call addTable calls are done.
func (s *levelHandler) addTable(t *table.Table) {
s.Lock()
defer s.Unlock()
s.addSize(t) // Increase totalSize first.
t.IncrRef()
s.tables = append(s.tables, t)
}
// sortTables sorts tables of levelHandler based on table.Smallest.
// Normally it should be called after all addTable calls.
func (s *levelHandler) sortTables() {
s.Lock()
defer s.Unlock()
sort.Slice(s.tables, func(i, j int) bool {
return y.CompareKeys(s.tables[i].Smallest(), s.tables[j].Smallest()) < 0
})
}
func decrRefs(tables []*table.Table) error {
for _, table := range tables {
if err := table.DecrRef(); err != nil {
return err
}
}
return nil
}
func newLevelHandler(db *DB, level int) *levelHandler {
return &levelHandler{
level: level,
strLevel: fmt.Sprintf("l%d", level),
db: db,
}
}
// tryAddLevel0Table returns true if ok and no stalling.
func (s *levelHandler) tryAddLevel0Table(t *table.Table) bool {
y.AssertTrue(s.level == 0)
// Need lock as we may be deleting the first table during a level 0 compaction.
s.Lock()
defer s.Unlock()
// Stall (by returning false) if we are above the specified stall setting for L0.
if len(s.tables) >= s.db.opt.NumLevelZeroTablesStall {
return false
}
s.tables = append(s.tables, t)
t.IncrRef()
s.addSize(t)
return true
}
// This should be called while holding the lock on the level.
func (s *levelHandler) addSize(t *table.Table) {
s.totalSize += t.Size()
s.totalStaleSize += int64(t.StaleDataSize())
}
// This should be called while holding the lock on the level.
func (s *levelHandler) subtractSize(t *table.Table) {
s.totalSize -= t.Size()
s.totalStaleSize -= int64(t.StaleDataSize())
}
func (s *levelHandler) numTables() int {
s.RLock()
defer s.RUnlock()
return len(s.tables)
}
func (s *levelHandler) close() error {
s.RLock()
defer s.RUnlock()
var err error
for _, t := range s.tables {
if closeErr := t.Close(-1); closeErr != nil && err == nil {
err = closeErr
}
}
return y.Wrap(err, "levelHandler.close")
}
// getTableForKey acquires a read-lock to access s.tables. It returns a list of tableHandlers.
func (s *levelHandler) getTableForKey(key []byte) ([]*table.Table, func() error) {
s.RLock()
defer s.RUnlock()
if s.level == 0 {
// For level 0, we need to check every table. Remember to make a copy as s.tables may change
// once we exit this function, and we don't want to lock s.tables while seeking in tables.
// CAUTION: Reverse the tables.
out := make([]*table.Table, 0, len(s.tables))
for i := len(s.tables) - 1; i >= 0; i-- {
out = append(out, s.tables[i])
s.tables[i].IncrRef()
}
return out, func() error {
for _, t := range out {
if err := t.DecrRef(); err != nil {
return err
}
}
return nil
}
}
// For level >= 1, we can do a binary search as key range does not overlap.
idx := sort.Search(len(s.tables), func(i int) bool {
return y.CompareKeys(s.tables[i].Biggest(), key) >= 0
})
if idx >= len(s.tables) {
// Given key is strictly > than every element we have.
return nil, func() error { return nil }
}
tbl := s.tables[idx]
tbl.IncrRef()
return []*table.Table{tbl}, tbl.DecrRef
}
// get returns value for a given key or the key after that. If not found, return nil.
func (s *levelHandler) get(key []byte) (y.ValueStruct, error) {
tables, decr := s.getTableForKey(key)
keyNoTs := y.ParseKey(key)
hash := y.Hash(keyNoTs)
var maxVs y.ValueStruct
for _, th := range tables {
if th.DoesNotHave(hash) {
y.NumLSMBloomHitsAdd(s.db.opt.MetricsEnabled, s.strLevel, 1)
continue
}
it := th.NewIterator(0)
defer it.Close()
y.NumLSMGetsAdd(s.db.opt.MetricsEnabled, s.strLevel, 1)
it.Seek(key)
if !it.Valid() {
continue
}
if y.SameKey(key, it.Key()) {
if version := y.ParseTs(it.Key()); maxVs.Version < version {
maxVs = it.ValueCopy()
maxVs.Version = version
}
}
}
return maxVs, decr()
}
// appendIterators appends iterators to an array of iterators, for merging.
// Note: This obtains references for the table handlers. Remember to close these iterators.
func (s *levelHandler) appendIterators(iters []y.Iterator, opt *IteratorOptions) []y.Iterator {
s.RLock()
defer s.RUnlock()
var topt int
if opt.Reverse {
topt = table.REVERSED
}
if s.level == 0 {
// Remember to add in reverse order!
// The newer table at the end of s.tables should be added first as it takes precedence.
// Level 0 tables are not in key sorted order, so we need to consider them one by one.
var out []*table.Table
for _, t := range s.tables {
if opt.pickTable(t) {
out = append(out, t)
}
}
return appendIteratorsReversed(iters, out, topt)
}
tables := opt.pickTables(s.tables)
if len(tables) == 0 {
return iters
}
return append(iters, table.NewConcatIterator(tables, topt))
}
type levelHandlerRLocked struct{}
// overlappingTables returns the tables that intersect with key range. Returns a half-interval.
// This function should already have acquired a read lock, and this is so important the caller must
// pass an empty parameter declaring such.
func (s *levelHandler) overlappingTables(_ levelHandlerRLocked, kr keyRange) (int, int) {
if len(kr.left) == 0 || len(kr.right) == 0 {
return 0, 0
}
left := sort.Search(len(s.tables), func(i int) bool {
return y.CompareKeys(kr.left, s.tables[i].Biggest()) <= 0
})
right := sort.Search(len(s.tables), func(i int) bool {
return y.CompareKeys(kr.right, s.tables[i].Smallest()) < 0
})
return left, right
}
================================================
FILE: levels.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"bytes"
"context"
"encoding/hex"
"errors"
"fmt"
"math"
"math/rand"
"os"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"github.com/dgraph-io/badger/v4/pb"
"github.com/dgraph-io/badger/v4/table"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2/z"
)
type levelsController struct {
nextFileID atomic.Uint64
l0stallsMs atomic.Int64
// The following are initialized once and const.
levels []*levelHandler
kv *DB
cstatus compactStatus
}
// revertToManifest checks that all necessary table files exist and removes all table files not
// referenced by the manifest. idMap is a set of table file id's that were read from the directory
// listing.
func revertToManifest(kv *DB, mf *Manifest, idMap map[uint64]struct{}) error {
// 1. Check all files in manifest exist.
for id := range mf.Tables {
if _, ok := idMap[id]; !ok {
return fmt.Errorf("file does not exist for table %d", id)
}
}
// 2. Delete files that shouldn't exist.
for id := range idMap {
if _, ok := mf.Tables[id]; !ok {
kv.opt.Debugf("Table file %d not referenced in MANIFEST\n", id)
filename := table.NewFilename(id, kv.opt.Dir)
if err := os.Remove(filename); err != nil {
return y.Wrapf(err, "While removing table %d", id)
}
}
}
return nil
}
func newLevelsController(db *DB, mf *Manifest) (*levelsController, error) {
y.AssertTrue(db.opt.NumLevelZeroTablesStall > db.opt.NumLevelZeroTables)
s := &levelsController{
kv: db,
levels: make([]*levelHandler, db.opt.MaxLevels),
}
s.cstatus.tables = make(map[uint64]struct{})
s.cstatus.levels = make([]*levelCompactStatus, db.opt.MaxLevels)
for i := 0; i < db.opt.MaxLevels; i++ {
s.levels[i] = newLevelHandler(db, i)
s.cstatus.levels[i] = new(levelCompactStatus)
}
if db.opt.InMemory {
return s, nil
}
// Compare manifest against directory, check for existent/non-existent files, and remove.
if err := revertToManifest(db, mf, getIDMap(db.opt.Dir)); err != nil {
return nil, err
}
var mu sync.Mutex
tables := make([][]*table.Table, db.opt.MaxLevels)
var maxFileID uint64
// We found that using 3 goroutines allows disk throughput to be utilized to its max.
// Disk utilization is the main thing we should focus on, while trying to read the data. That's
// the one factor that remains constant between HDD and SSD.
throttle := y.NewThrottle(3)
start := time.Now()
var numOpened atomic.Int32
tick := time.NewTicker(3 * time.Second)
defer tick.Stop()
for fileID, tf := range mf.Tables {
fname := table.NewFilename(fileID, db.opt.Dir)
select {
case <-tick.C:
db.opt.Infof("%d tables out of %d opened in %s\n", numOpened.Load(),
len(mf.Tables), time.Since(start).Round(time.Millisecond))
default:
}
if err := throttle.Do(); err != nil {
closeAllTables(tables)
return nil, err
}
if fileID > maxFileID {
maxFileID = fileID
}
go func(fname string, tf TableManifest) {
var rerr error
defer func() {
throttle.Done(rerr)
numOpened.Add(1)
}()
dk, err := db.registry.DataKey(tf.KeyID)
if err != nil {
rerr = y.Wrapf(err, "Error while reading datakey")
return
}
topt := buildTableOptions(db)
// Explicitly set Compression and DataKey based on how the table was generated.
topt.Compression = tf.Compression
topt.DataKey = dk
mf, err := z.OpenMmapFile(fname, db.opt.getFileFlags(), 0)
if err != nil {
rerr = y.Wrapf(err, "Opening file: %q", fname)
return
}
t, err := table.OpenTable(mf, topt)
if err != nil {
if strings.HasPrefix(err.Error(), "CHECKSUM_MISMATCH:") {
db.opt.Errorf(err.Error())
db.opt.Errorf("Ignoring table %s", mf.Fd.Name())
// Do not set rerr. We will continue without this table.
} else {
rerr = y.Wrapf(err, "Opening table: %q", fname)
}
return
}
mu.Lock()
tables[tf.Level] = append(tables[tf.Level], t)
mu.Unlock()
}(fname, tf)
}
if err := throttle.Finish(); err != nil {
closeAllTables(tables)
return nil, err
}
db.opt.Infof("All %d tables opened in %s\n", numOpened.Load(),
time.Since(start).Round(time.Millisecond))
s.nextFileID.Store(maxFileID + 1)
for i, tbls := range tables {
s.levels[i].initTables(tbls)
}
// Make sure key ranges do not overlap etc.
if err := s.validate(); err != nil {
_ = s.cleanupLevels()
return nil, y.Wrap(err, "Level validation")
}
// Sync directory (because we have at least removed some files, or previously created the
// manifest file).
if err := syncDir(db.opt.Dir); err != nil {
_ = s.close()
return nil, err
}
return s, nil
}
// Closes the tables, for cleanup in newLevelsController. (We Close() instead of using DecrRef()
// because that would delete the underlying files.) We ignore errors, which is OK because tables
// are read-only.
func closeAllTables(tables [][]*table.Table) {
for _, tableSlice := range tables {
for _, table := range tableSlice {
_ = table.Close(-1)
}
}
}
func (s *levelsController) cleanupLevels() error {
var firstErr error
for _, l := range s.levels {
if err := l.close(); err != nil && firstErr == nil {
firstErr = err
}
}
return firstErr
}
// dropTree picks all tables from all levels, creates a manifest changeset,
// applies it, and then decrements the refs of these tables, which would result
// in their deletion.
func (s *levelsController) dropTree() (int, error) {
// First pick all tables, so we can create a manifest changelog.
var all []*table.Table
for _, l := range s.levels {
l.RLock()
all = append(all, l.tables...)
l.RUnlock()
}
if len(all) == 0 {
return 0, nil
}
// Generate the manifest changes.
changes := []*pb.ManifestChange{}
for _, table := range all {
// Add a delete change only if the table is not in memory.
if !table.IsInmemory {
changes = append(changes, newDeleteChange(table.ID()))
}
}
changeSet := pb.ManifestChangeSet{Changes: changes}
if err := s.kv.manifest.addChanges(changeSet.Changes, s.kv.opt); err != nil {
return 0, err
}
// Now that manifest has been successfully written, we can delete the tables.
for _, l := range s.levels {
l.Lock()
l.totalSize = 0
l.tables = l.tables[:0]
l.Unlock()
}
for _, table := range all {
if err := table.DecrRef(); err != nil {
return 0, err
}
}
return len(all), nil
}
// dropPrefix runs a L0->L1 compaction, and then runs same level compaction on the rest of the
// levels. For L0->L1 compaction, it runs compactions normally, but skips over
// all the keys with the provided prefix.
// For Li->Li compactions, it picks up the tables which would have the prefix. The
// tables who only have keys with this prefix are quickly dropped. The ones which have other keys
// are run through MergeIterator and compacted to create new tables. All the mechanisms of
// compactions apply, i.e. level sizes and MANIFEST are updated as in the normal flow.
func (s *levelsController) dropPrefixes(prefixes [][]byte) error {
opt := s.kv.opt
// Iterate levels in the reverse order because if we were to iterate from
// lower level (say level 0) to a higher level (say level 3) we could have
// a state in which level 0 is compacted and an older version of a key exists in lower level.
// At this point, if someone creates an iterator, they would see an old
// value for a key from lower levels. Iterating in reverse order ensures we
// drop the oldest data first so that lookups never return stale data.
for i := len(s.levels) - 1; i >= 0; i-- {
l := s.levels[i]
l.RLock()
if l.level == 0 {
size := len(l.tables)
l.RUnlock()
if size > 0 {
cp := compactionPriority{
level: 0,
score: 1.74,
// A unique number greater than 1.0 does two things. Helps identify this
// function in logs, and forces a compaction.
dropPrefixes: prefixes,
}
if err := s.doCompact(174, cp); err != nil {
opt.Warningf("While compacting level 0: %v", err)
return nil
}
}
continue
}
// Build a list of compaction tableGroups affecting all the prefixes we
// need to drop. We need to build tableGroups that satisfy the invariant that
// bottom tables are consecutive.
// tableGroup contains groups of consecutive tables.
var tableGroups [][]*table.Table
var tableGroup []*table.Table
finishGroup := func() {
if len(tableGroup) > 0 {
tableGroups = append(tableGroups, tableGroup)
tableGroup = nil
}
}
for _, table := range l.tables {
if containsAnyPrefixes(table, prefixes) {
tableGroup = append(tableGroup, table)
} else {
finishGroup()
}
}
finishGroup()
l.RUnlock()
if len(tableGroups) == 0 {
continue
}
opt.Infof("Dropping prefix at level %d (%d tableGroups)", l.level, len(tableGroups))
for _, operation := range tableGroups {
cd := compactDef{
thisLevel: l,
nextLevel: l,
top: nil,
bot: operation,
dropPrefixes: prefixes,
t: s.levelTargets(),
}
_, span := otel.Tracer("").Start(context.TODO(), "Badger.Compaction")
span.SetAttributes(attribute.Int("Compaction level", l.level))
span.SetAttributes(attribute.String("Drop Prefixes", fmt.Sprintf("%v", prefixes)))
cd.t.baseLevel = l.level
if err := s.runCompactDef(-1, l.level, cd); err != nil {
opt.Warningf("While running compact def: %+v. Error: %v", cd, err)
span.End()
return err
}
span.SetAttributes(
attribute.Int("Top tables count", len(cd.top)),
attribute.Int("Bottom tables count", len(cd.bot)))
span.End()
}
}
return nil
}
func (s *levelsController) startCompact(lc *z.Closer) {
n := s.kv.opt.NumCompactors
lc.AddRunning(n - 1)
for i := 0; i < n; i++ {
go s.runCompactor(i, lc)
}
}
type targets struct {
baseLevel int
targetSz []int64
fileSz []int64
}
// levelTargets calculates the targets for levels in the LSM tree. The idea comes from Dynamic Level
// Sizes ( https://rocksdb.org/blog/2015/07/23/dynamic-level.html ) in RocksDB. The sizes of levels
// are calculated based on the size of the lowest level, typically L6. So, if L6 size is 1GB, then
// L5 target size is 100MB, L4 target size is 10MB and so on.
//
// L0 files don't automatically go to L1. Instead, they get compacted to Lbase, where Lbase is
// chosen based on the first level which is non-empty from top (check L1 through L6). For an empty
// DB, that would be L6. So, L0 compactions go to L6, then L5, L4 and so on.
//
// Lbase is advanced to the upper levels when its target size exceeds BaseLevelSize. For
// example, when L6 reaches 1.1GB, then L4 target sizes becomes 11MB, thus exceeding the
// BaseLevelSize of 10MB. L3 would then become the new Lbase, with a target size of 1MB <
// BaseLevelSize.
func (s *levelsController) levelTargets() targets {
adjust := func(sz int64) int64 {
if sz < s.kv.opt.BaseLevelSize {
return s.kv.opt.BaseLevelSize
}
return sz
}
t := targets{
targetSz: make([]int64, len(s.levels)),
fileSz: make([]int64, len(s.levels)),
}
// DB size is the size of the last level.
dbSize := s.lastLevel().getTotalSize()
for i := len(s.levels) - 1; i > 0; i-- {
ltarget := adjust(dbSize)
t.targetSz[i] = ltarget
if t.baseLevel == 0 && ltarget <= s.kv.opt.BaseLevelSize {
t.baseLevel = i
}
dbSize /= int64(s.kv.opt.LevelSizeMultiplier)
}
tsz := s.kv.opt.BaseTableSize
for i := 0; i < len(s.levels); i++ {
if i == 0 {
// Use MemTableSize for Level 0. Because at Level 0, we stop compactions based on the
// number of tables, not the size of the level. So, having a 1:1 size ratio between
// memtable size and the size of L0 files is better than churning out 32 files per
// memtable (assuming 64MB MemTableSize and 2MB BaseTableSize).
t.fileSz[i] = s.kv.opt.MemTableSize
} else if i <= t.baseLevel {
t.fileSz[i] = tsz
} else {
tsz *= int64(s.kv.opt.TableSizeMultiplier)
t.fileSz[i] = tsz
}
}
// Bring the base level down to the last empty level.
for i := t.baseLevel + 1; i < len(s.levels)-1; i++ {
if s.levels[i].getTotalSize() > 0 {
break
}
t.baseLevel = i
}
// If the base level is empty and the next level size is less than the
// target size, pick the next level as the base level.
b := t.baseLevel
lvl := s.levels
if b < len(lvl)-1 && lvl[b].getTotalSize() == 0 && lvl[b+1].getTotalSize() < t.targetSz[b+1] {
t.baseLevel++
}
return t
}
func (s *levelsController) runCompactor(id int, lc *z.Closer) {
defer lc.Done()
randomDelay := time.NewTimer(time.Duration(rand.Int31n(1000)) * time.Millisecond)
select {
case <-randomDelay.C:
case <-lc.HasBeenClosed():
randomDelay.Stop()
return
}
moveL0toFront := func(prios []compactionPriority) []compactionPriority {
idx := -1
for i, p := range prios {
if p.level == 0 {
idx = i
break
}
}
// If idx == -1, we didn't find L0.
// If idx == 0, then we don't need to do anything. L0 is already at the front.
if idx > 0 {
out := append([]compactionPriority{}, prios[idx])
out = append(out, prios[:idx]...)
out = append(out, prios[idx+1:]...)
return out
}
return prios
}
run := func(p compactionPriority) bool {
err := s.doCompact(id, p)
switch err {
case nil:
return true
case errFillTables:
// pass
default:
s.kv.opt.Warningf("While running doCompact: %v\n", err)
}
return false
}
var priosBuffer []compactionPriority
runOnce := func() bool {
prios := s.pickCompactLevels(priosBuffer)
defer func() {
priosBuffer = prios
}()
if id == 0 {
// Worker ID zero prefers to compact L0 always.
prios = moveL0toFront(prios)
}
for _, p := range prios {
if id == 0 && p.level == 0 {
// Allow worker zero to run level 0, irrespective of its adjusted score.
} else if p.adjusted < 1.0 {
break
}
if run(p) {
return true
}
}
return false
}
tryLmaxToLmaxCompaction := func() {
p := compactionPriority{
level: s.lastLevel().level,
t: s.levelTargets(),
}
run(p)
}
count := 0
ticker := time.NewTicker(50 * time.Millisecond)
defer ticker.Stop()
for {
select {
// Can add a done channel or other stuff.
case <-ticker.C:
count++
// Each ticker is 50ms so 50*200=10seconds.
if s.kv.opt.LmaxCompaction && id == 2 && count >= 200 {
tryLmaxToLmaxCompaction()
count = 0
} else {
runOnce()
}
case <-lc.HasBeenClosed():
return
}
}
}
type compactionPriority struct {
level int
score float64
adjusted float64
dropPrefixes [][]byte
t targets
}
func (s *levelsController) lastLevel() *levelHandler {
return s.levels[len(s.levels)-1]
}
// pickCompactLevel determines which level to compact.
// Based on: https://github.com/facebook/rocksdb/wiki/Leveled-Compaction
// It tries to reuse priosBuffer to reduce memory allocation,
// passing nil is acceptable, then new memory will be allocated.
func (s *levelsController) pickCompactLevels(priosBuffer []compactionPriority) (prios []compactionPriority) {
t := s.levelTargets()
addPriority := func(level int, score float64) {
pri := compactionPriority{
level: level,
score: score,
adjusted: score,
t: t,
}
prios = append(prios, pri)
}
// Grow buffer to fit all levels.
if cap(priosBuffer) < len(s.levels) {
priosBuffer = make([]compactionPriority, 0, len(s.levels))
}
prios = priosBuffer[:0]
// Add L0 priority based on the number of tables.
addPriority(0, float64(s.levels[0].numTables())/float64(s.kv.opt.NumLevelZeroTables))
// All other levels use size to calculate priority.
for i := 1; i < len(s.levels); i++ {
// Don't consider those tables that are already being compacted right now.
delSize := s.cstatus.delSize(i)
l := s.levels[i]
sz := l.getTotalSize() - delSize
addPriority(i, float64(sz)/float64(t.targetSz[i]))
}
y.AssertTrue(len(prios) == len(s.levels))
// The following code is borrowed from PebbleDB and results in healthier LSM tree structure.
// If Li-1 has score > 1.0, then we'll divide Li-1 score by Li. If Li score is >= 1.0, then Li-1
// score is reduced, which means we'll prioritize the compaction of lower levels (L5, L4 and so
// on) over the higher levels (L0, L1 and so on). On the other hand, if Li score is < 1.0, then
// we'll increase the priority of Li-1.
// Overall what this means is, if the bottom level is already overflowing, then de-prioritize
// compaction of the above level. If the bottom level is not full, then increase the priority of
// above level.
var prevLevel int
for level := t.baseLevel; level < len(s.levels); level++ {
if prios[prevLevel].adjusted >= 1 {
// Avoid absurdly large scores by placing a floor on the score that we'll
// adjust a level by. The value of 0.01 was chosen somewhat arbitrarily
const minScore = 0.01
if prios[level].score >= minScore {
prios[prevLevel].adjusted /= prios[level].adjusted
} else {
prios[prevLevel].adjusted /= minScore
}
}
prevLevel = level
}
// Pick all the levels whose original score is >= 1.0, irrespective of their adjusted score.
// We'll still sort them by their adjusted score below. Having both these scores allows us to
// make better decisions about compacting L0. If we see a score >= 1.0, we can do L0->L0
// compactions. If the adjusted score >= 1.0, then we can do L0->Lbase compactions.
out := prios[:0]
for _, p := range prios[:len(prios)-1] {
if p.score >= 1.0 {
out = append(out, p)
}
}
prios = out
// Sort by the adjusted score.
sort.Slice(prios, func(i, j int) bool {
return prios[i].adjusted > prios[j].adjusted
})
return prios
}
// checkOverlap checks if the given tables overlap with any level from the given "lev" onwards.
func (s *levelsController) checkOverlap(tables []*table.Table, lev int) bool {
kr := getKeyRange(tables...)
for i, lh := range s.levels {
if i < lev { // Skip upper levels.
continue
}
lh.RLock()
left, right := lh.overlappingTables(levelHandlerRLocked{}, kr)
lh.RUnlock()
if right-left > 0 {
return true
}
}
return false
}
// subcompact runs a single sub-compaction, iterating over the specified key-range only.
//
// We use splits to do a single compaction concurrently. If we have >= 3 tables
// involved in the bottom level during compaction, we choose key ranges to
// split the main compaction up into sub-compactions. Each sub-compaction runs
// concurrently, only iterating over the provided key range, generating tables.
// This speeds up the compaction significantly.
func (s *levelsController) subcompact(it y.Iterator, kr keyRange, cd compactDef,
inflightBuilders *y.Throttle, res chan<- *table.Table) {
// Check overlap of the top level with the levels which are not being
// compacted in this compaction.
hasOverlap := s.checkOverlap(cd.allTables(), cd.nextLevel.level+1)
// Pick a discard ts, so we can discard versions below this ts. We should
// never discard any versions starting from above this timestamp, because
// that would affect the snapshot view guarantee provided by transactions.
discardTs := s.kv.orc.discardAtOrBelow()
// Try to collect stats so that we can inform value log about GC. That would help us find which
// value log file should be GCed.
discardStats := make(map[uint32]int64)
updateStats := func(vs y.ValueStruct) {
// We don't need to store/update discard stats when badger is running in Disk-less mode.
if s.kv.opt.InMemory {
return
}
if vs.Meta&bitValuePointer > 0 {
var vp valuePointer
vp.Decode(vs.Value)
discardStats[vp.Fid] += int64(vp.Len)
}
}
// exceedsAllowedOverlap returns true if the given key range would overlap with more than 10
// tables from level below nextLevel (nextLevel+1). This helps avoid generating tables at Li
// with huge overlaps with Li+1.
exceedsAllowedOverlap := func(kr keyRange) bool {
n2n := cd.nextLevel.level + 1
if n2n <= 1 || n2n >= len(s.levels) {
return false
}
n2nl := s.levels[n2n]
n2nl.RLock()
defer n2nl.RUnlock()
l, r := n2nl.overlappingTables(levelHandlerRLocked{}, kr)
return r-l >= 10
}
var (
lastKey, skipKey []byte
numBuilds, numVersions int
// Denotes if the first key is a series of duplicate keys had
// "DiscardEarlierVersions" set
firstKeyHasDiscardSet bool
)
addKeys := func(builder *table.Builder) {
timeStart := time.Now()
var numKeys, numSkips uint64
var rangeCheck int
var tableKr keyRange
for ; it.Valid(); it.Next() {
// See if we need to skip the prefix.
if len(cd.dropPrefixes) > 0 && hasAnyPrefixes(it.Key(), cd.dropPrefixes) {
numSkips++
updateStats(it.Value())
continue
}
// See if we need to skip this key.
if len(skipKey) > 0 {
if y.SameKey(it.Key(), skipKey) {
numSkips++
updateStats(it.Value())
continue
} else {
skipKey = skipKey[:0]
}
}
if !y.SameKey(it.Key(), lastKey) {
firstKeyHasDiscardSet = false
if len(kr.right) > 0 && y.CompareKeys(it.Key(), kr.right) >= 0 {
break
}
if builder.ReachedCapacity() {
// Only break if we are on a different key, and have reached capacity. We want
// to ensure that all versions of the key are stored in the same sstable, and
// not divided across multiple tables at the same level.
break
}
lastKey = y.SafeCopy(lastKey, it.Key())
numVersions = 0
firstKeyHasDiscardSet = it.Value().Meta&bitDiscardEarlierVersions > 0
if len(tableKr.left) == 0 {
tableKr.left = y.SafeCopy(tableKr.left, it.Key())
}
tableKr.right = lastKey
rangeCheck++
if rangeCheck%5000 == 0 {
// This table's range exceeds the allowed range overlap with the level after
// next. So, we stop writing to this table. If we don't do this, then we end up
// doing very expensive compactions involving too many tables. To amortize the
// cost of this check, we do it only every N keys.
if exceedsAllowedOverlap(tableKr) {
// s.kv.opt.Debugf("L%d -> L%d Breaking due to exceedsAllowedOverlap with
// kr: %s\n", cd.thisLevel.level, cd.nextLevel.level, tableKr)
break
}
}
}
vs := it.Value()
version := y.ParseTs(it.Key())
isExpired := isDeletedOrExpired(vs.Meta, vs.ExpiresAt)
// Do not discard entries inserted by merge operator. These entries will be
// discarded once they're merged
if version <= discardTs && vs.Meta&bitMergeEntry == 0 {
// Keep track of the number of versions encountered for this key. Only consider the
// versions which are below the minReadTs, otherwise, we might end up discarding the
// only valid version for a running transaction.
numVersions++
// Keep the current version and discard all the next versions if
// - The `discardEarlierVersions` bit is set OR
// - We've already processed `NumVersionsToKeep` number of versions
// (including the current item being processed)
lastValidVersion := vs.Meta&bitDiscardEarlierVersions > 0 ||
numVersions == s.kv.opt.NumVersionsToKeep
if isExpired || lastValidVersion {
// If this version of the key is deleted or expired, skip all the rest of the
// versions. Ensure that we're only removing versions below readTs.
skipKey = y.SafeCopy(skipKey, it.Key())
switch {
// Add the key to the table only if it has not expired.
// We don't want to add the deleted/expired keys.
case !isExpired && lastValidVersion:
// Add this key. We have set skipKey, so the following key versions
// would be skipped.
case hasOverlap:
// If this key range has overlap with lower levels, then keep the deletion
// marker with the latest version, discarding the rest. We have set skipKey,
// so the following key versions would be skipped.
default:
// If no overlap, we can skip all the versions, by continuing here.
numSkips++
updateStats(vs)
continue // Skip adding this key.
}
}
}
numKeys++
var vp valuePointer
if vs.Meta&bitValuePointer > 0 {
vp.Decode(vs.Value)
}
switch {
case firstKeyHasDiscardSet:
// This key is same as the last key which had "DiscardEarlierVersions" set. The
// the next compactions will drop this key if its ts >
// discardTs (of the next compaction).
builder.AddStaleKey(it.Key(), vs, vp.Len)
case isExpired:
// If the key is expired, the next compaction will drop it if
// its ts > discardTs (of the next compaction).
builder.AddStaleKey(it.Key(), vs, vp.Len)
default:
builder.Add(it.Key(), vs, vp.Len)
}
}
s.kv.opt.Debugf("[%d] LOG Compact. Added %d keys. Skipped %d keys. Iteration took: %v",
cd.compactorId, numKeys, numSkips, time.Since(timeStart).Round(time.Millisecond))
} // End of function: addKeys
if len(kr.left) > 0 {
it.Seek(kr.left)
} else {
it.Rewind()
}
for it.Valid() {
if len(kr.right) > 0 && y.CompareKeys(it.Key(), kr.right) >= 0 {
break
}
bopts := buildTableOptions(s.kv)
// Set TableSize to the target file size for that level.
bopts.TableSize = uint64(cd.t.fileSz[cd.nextLevel.level])
builder := table.NewTableBuilder(bopts)
// This would do the iteration and add keys to builder.
addKeys(builder)
// It was true that it.Valid() at least once in the loop above, which means we
// called Add() at least once, and builder is not Empty().
if builder.Empty() {
// Cleanup builder resources:
builder.Finish()
builder.Close()
continue
}
numBuilds++
if err := inflightBuilders.Do(); err != nil {
// Can't return from here, until I decrRef all the tables that I built so far.
break
}
go func(builder *table.Builder, fileID uint64) {
var err error
defer inflightBuilders.Done(err)
defer builder.Close()
var tbl *table.Table
if s.kv.opt.InMemory {
tbl, err = table.OpenInMemoryTable(builder.Finish(), fileID, &bopts)
} else {
fname := table.NewFilename(fileID, s.kv.opt.Dir)
tbl, err = table.CreateTable(fname, builder)
}
// If we couldn't build the table, return fast.
if err != nil {
return
}
res <- tbl
}(builder, s.reserveFileID())
}
s.kv.vlog.updateDiscardStats(discardStats)
s.kv.opt.Debugf("Discard stats: %v", discardStats)
}
// compactBuildTables merges topTables and botTables to form a list of new tables.
func (s *levelsController) compactBuildTables(
lev int, cd compactDef) ([]*table.Table, func() error, error) {
topTables := cd.top
botTables := cd.bot
numTables := int64(len(topTables) + len(botTables))
y.NumCompactionTablesAdd(s.kv.opt.MetricsEnabled, numTables)
defer y.NumCompactionTablesAdd(s.kv.opt.MetricsEnabled, -numTables)
keepTable := func(t *table.Table) bool {
for _, prefix := range cd.dropPrefixes {
if bytes.HasPrefix(t.Smallest(), prefix) &&
bytes.HasPrefix(t.Biggest(), prefix) {
// All the keys in this table have the dropPrefix. So, this
// table does not need to be in the iterator and can be
// dropped immediately.
return false
}
}
return true
}
var valid []*table.Table
for _, table := range botTables {
if keepTable(table) {
valid = append(valid, table)
}
}
newIterator := func() []y.Iterator {
// Create iterators across all the tables involved first.
var iters []y.Iterator
switch {
case lev == 0:
iters = appendIteratorsReversed(iters, topTables, table.NOCACHE)
case len(topTables) > 0:
y.AssertTrue(len(topTables) == 1)
iters = []y.Iterator{topTables[0].NewIterator(table.NOCACHE)}
}
// Next level has level>=1 and we can use ConcatIterator as key ranges do not overlap.
return append(iters, table.NewConcatIterator(valid, table.NOCACHE))
}
res := make(chan *table.Table, 3)
inflightBuilders := y.NewThrottle(8 + len(cd.splits))
for _, kr := range cd.splits {
// Initiate Do here so we can register the goroutines for buildTables too.
if err := inflightBuilders.Do(); err != nil {
s.kv.opt.Errorf("cannot start subcompaction: %+v", err)
return nil, nil, err
}
go func(kr keyRange) {
defer inflightBuilders.Done(nil)
it := table.NewMergeIterator(newIterator(), false)
defer it.Close()
s.subcompact(it, kr, cd, inflightBuilders, res)
}(kr)
}
var newTables []*table.Table
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for t := range res {
newTables = append(newTables, t)
}
}()
// Wait for all table builders to finish and also for newTables accumulator to finish.
err := inflightBuilders.Finish()
close(res)
wg.Wait() // Wait for all tables to be picked up.
if err == nil {
// Ensure created files' directory entries are visible. We don't mind the extra latency
// from not doing this ASAP after all file creation has finished because this is a
// background operation.
err = s.kv.syncDir(s.kv.opt.Dir)
}
if err != nil {
// An error happened. Delete all the newly created table files (by calling DecrRef
// -- we're the only holders of a ref).
_ = decrRefs(newTables)
return nil, nil, y.Wrapf(err, "while running compactions for: %+v", cd)
}
sort.Slice(newTables, func(i, j int) bool {
return y.CompareKeys(newTables[i].Biggest(), newTables[j].Biggest()) < 0
})
return newTables, func() error { return decrRefs(newTables) }, nil
}
func buildChangeSet(cd *compactDef, newTables []*table.Table) pb.ManifestChangeSet {
changes := []*pb.ManifestChange{}
for _, table := range newTables {
changes = append(changes,
newCreateChange(table.ID(), cd.nextLevel.level, table.KeyID(), table.CompressionType()))
}
for _, table := range cd.top {
// Add a delete change only if the table is not in memory.
if !table.IsInmemory {
changes = append(changes, newDeleteChange(table.ID()))
}
}
for _, table := range cd.bot {
changes = append(changes, newDeleteChange(table.ID()))
}
return pb.ManifestChangeSet{Changes: changes}
}
func hasAnyPrefixes(s []byte, listOfPrefixes [][]byte) bool {
for _, prefix := range listOfPrefixes {
if bytes.HasPrefix(s, prefix) {
return true
}
}
return false
}
func containsPrefix(table *table.Table, prefix []byte) bool {
smallValue := table.Smallest()
largeValue := table.Biggest()
if bytes.HasPrefix(smallValue, prefix) {
return true
}
if bytes.HasPrefix(largeValue, prefix) {
return true
}
isPresent := func() bool {
ti := table.NewIterator(0)
defer ti.Close()
// In table iterator's Seek, we assume that key has version in last 8 bytes. We set
// version=0 (ts=math.MaxUint64), so that we don't skip the key prefixed with prefix.
ti.Seek(y.KeyWithTs(prefix, math.MaxUint64))
return bytes.HasPrefix(ti.Key(), prefix)
}
if bytes.Compare(prefix, smallValue) > 0 &&
bytes.Compare(prefix, largeValue) < 0 {
// There may be a case when table contains [0x0000,...., 0xffff]. If we are searching for
// k=0x0011, we should not directly infer that k is present. It may not be present.
return isPresent()
}
return false
}
func containsAnyPrefixes(table *table.Table, listOfPrefixes [][]byte) bool {
for _, prefix := range listOfPrefixes {
if containsPrefix(table, prefix) {
return true
}
}
return false
}
type compactDef struct {
compactorId int
t targets
p compactionPriority
thisLevel *levelHandler
nextLevel *levelHandler
top []*table.Table
bot []*table.Table
thisRange keyRange
nextRange keyRange
splits []keyRange
thisSize int64
dropPrefixes [][]byte
}
// addSplits can allow us to run multiple sub-compactions in parallel across the split key ranges.
func (s *levelsController) addSplits(cd *compactDef) {
cd.splits = cd.splits[:0]
// Let's say we have 10 tables in cd.bot and min width = 3. Then, we'll pick
// 0, 1, 2 (pick), 3, 4, 5 (pick), 6, 7, 8 (pick), 9 (pick, because last table).
// This gives us 4 picks for 10 tables.
// In an edge case, 142 tables in bottom led to 48 splits. That's too many splits, because it
// then uses up a lot of memory for table builder.
// We should keep it so we have at max 5 splits.
width := int(math.Ceil(float64(len(cd.bot)) / 5.0))
if width < 3 {
width = 3
}
skr := cd.thisRange
skr.extend(cd.nextRange)
addRange := func(right []byte) {
skr.right = y.Copy(right)
cd.splits = append(cd.splits, skr)
skr.left = skr.right
}
for i, t := range cd.bot {
// last entry in bottom table.
if i == len(cd.bot)-1 {
addRange([]byte{})
return
}
if i%width == width-1 {
// Right is assigned ts=0. The encoding ts bytes take MaxUint64-ts,
// so, those with smaller TS will be considered larger for the same key.
// Consider the following.
// Top table is [A1...C3(deleted)]
// bot table is [B1....C2]
// It will generate a split [A1 ... C0], including any records of Key C.
right := y.KeyWithTs(y.ParseKey(t.Biggest()), 0)
addRange(right)
}
}
}
func (cd *compactDef) lockLevels() {
cd.thisLevel.RLock()
cd.nextLevel.RLock()
}
func (cd *compactDef) unlockLevels() {
cd.nextLevel.RUnlock()
cd.thisLevel.RUnlock()
}
func (cd *compactDef) allTables() []*table.Table {
ret := make([]*table.Table, 0, len(cd.top)+len(cd.bot))
ret = append(ret, cd.top...)
ret = append(ret, cd.bot...)
return ret
}
func (s *levelsController) fillTablesL0ToL0(cd *compactDef) bool {
if cd.compactorId != 0 {
// Only compactor zero can work on this.
return false
}
cd.nextLevel = s.levels[0]
cd.nextRange = keyRange{}
cd.bot = nil
// Because this level and next level are both level 0, we should NOT acquire
// the read lock twice, because it can result in a deadlock. So, we don't
// call compactDef.lockLevels, instead locking the level only once and
// directly here.
//
// As per godocs on RWMutex:
// If a goroutine holds a RWMutex for reading and another goroutine might
// call Lock, no goroutine should expect to be able to acquire a read lock
// until the initial read lock is released. In particular, this prohibits
// recursive read locking. This is to ensure that the lock eventually
// becomes available; a blocked Lock call excludes new readers from
// acquiring the lock.
y.AssertTrue(cd.thisLevel.level == 0)
y.AssertTrue(cd.nextLevel.level == 0)
s.levels[0].RLock()
defer s.levels[0].RUnlock()
s.cstatus.Lock()
defer s.cstatus.Unlock()
top := cd.thisLevel.tables
var out []*table.Table
now := time.Now()
for _, t := range top {
if t.Size() >= 2*cd.t.fileSz[0] {
// This file is already big, don't include it.
continue
}
if now.Sub(t.CreatedAt) < 10*time.Second {
// Just created it 10s ago. Don't pick for compaction.
continue
}
if _, beingCompacted := s.cstatus.tables[t.ID()]; beingCompacted {
continue
}
out = append(out, t)
}
if len(out) < 4 {
// If we don't have enough tables to merge in L0, don't do it.
return false
}
cd.thisRange = infRange
cd.top = out
// Avoid any other L0 -> Lbase from happening, while this is going on.
thisLevel := s.cstatus.levels[cd.thisLevel.level]
thisLevel.ranges = append(thisLevel.ranges, infRange)
for _, t := range out {
s.cstatus.tables[t.ID()] = struct{}{}
}
// For L0->L0 compaction, we set the target file size to max, so the output is always one file.
// This significantly decreases the L0 table stalls and improves the performance.
cd.t.fileSz[0] = math.MaxUint32
return true
}
func (s *levelsController) fillTablesL0ToLbase(cd *compactDef) bool {
if cd.nextLevel.level == 0 {
panic("Base level can't be zero.")
}
// We keep cd.p.adjusted > 0.0 here to allow functions in db.go to artificially trigger
// L0->Lbase compactions. Those functions wouldn't be setting the adjusted score.
if cd.p.adjusted > 0.0 && cd.p.adjusted < 1.0 {
// Do not compact to Lbase if adjusted score is less than 1.0.
return false
}
cd.lockLevels()
defer cd.unlockLevels()
top := cd.thisLevel.tables
if len(top) == 0 {
return false
}
var out []*table.Table
if len(cd.dropPrefixes) > 0 {
// Use all tables if drop prefix is set. We don't want to compact only a
// sub-range. We want to compact all the tables.
out = top
} else {
var kr keyRange
// cd.top[0] is the oldest file. So we start from the oldest file first.
for _, t := range top {
dkr := getKeyRange(t)
if kr.overlapsWith(dkr) {
out = append(out, t)
kr.extend(dkr)
} else {
break
}
}
}
cd.thisRange = getKeyRange(out...)
cd.top = out
left, right := cd.nextLevel.overlappingTables(levelHandlerRLocked{}, cd.thisRange)
cd.bot = make([]*table.Table, right-left)
copy(cd.bot, cd.nextLevel.tables[left:right])
if len(cd.bot) == 0 {
cd.nextRange = cd.thisRange
} else {
cd.nextRange = getKeyRange(cd.bot...)
}
return s.cstatus.compareAndAdd(thisAndNextLevelRLocked{}, *cd)
}
// fillTablesL0 would try to fill tables from L0 to be compacted with Lbase. If
// it can not do that, it would try to compact tables from L0 -> L0.
//
// Say L0 has 10 tables.
// fillTablesL0ToLbase picks up 5 tables to compact from L0 -> L5.
// Next call to fillTablesL0 would run L0ToLbase again, which fails this time.
// So, instead, we run fillTablesL0ToL0, which picks up rest of the 5 tables to
// be compacted within L0. Additionally, it would set the compaction range in
// cstatus to inf, so no other L0 -> Lbase compactions can happen.
// Thus, L0 -> L0 must finish for the next L0 -> Lbase to begin.
func (s *levelsController) fillTablesL0(cd *compactDef) bool {
if ok := s.fillTablesL0ToLbase(cd); ok {
return true
}
return s.fillTablesL0ToL0(cd)
}
// sortByStaleData sorts tables based on the amount of stale data they have.
// This is useful in removing tombstones.
func (s *levelsController) sortByStaleDataSize(tables []*table.Table, cd *compactDef) {
if len(tables) == 0 || cd.nextLevel == nil {
return
}
sort.Slice(tables, func(i, j int) bool {
return tables[i].StaleDataSize() > tables[j].StaleDataSize()
})
}
// sortByHeuristic sorts tables in increasing order of MaxVersion, so we
// compact older tables first.
func (s *levelsController) sortByHeuristic(tables []*table.Table, cd *compactDef) {
if len(tables) == 0 || cd.nextLevel == nil {
return
}
// Sort tables by max version. This is what RocksDB does.
sort.Slice(tables, func(i, j int) bool {
return tables[i].MaxVersion() < tables[j].MaxVersion()
})
}
// This function should be called with lock on levels.
func (s *levelsController) fillMaxLevelTables(tables []*table.Table, cd *compactDef) bool {
sortedTables := make([]*table.Table, len(tables))
copy(sortedTables, tables)
s.sortByStaleDataSize(sortedTables, cd)
if len(sortedTables) > 0 && sortedTables[0].StaleDataSize() == 0 {
// This is a maxLevel to maxLevel compaction and we don't have any stale data.
return false
}
cd.bot = []*table.Table{}
collectBotTables := func(t *table.Table, needSz int64) {
totalSize := t.Size()
j := sort.Search(len(tables), func(i int) bool {
return y.CompareKeys(tables[i].Smallest(), t.Smallest()) >= 0
})
y.AssertTrue(tables[j].ID() == t.ID())
j++
// Collect tables until we reach the the required size.
for j < len(tables) {
newT := tables[j]
totalSize += newT.Size()
if totalSize >= needSz {
break
}
cd.bot = append(cd.bot, newT)
cd.nextRange.extend(getKeyRange(newT))
j++
}
}
now := time.Now()
for _, t := range sortedTables {
// If the maxVersion is above the discardTs, we won't clean anything in
// the compaction. So skip this table.
if t.MaxVersion() > s.kv.orc.discardAtOrBelow() {
continue
}
if now.Sub(t.CreatedAt) < time.Hour {
// Just created it an hour ago. Don't pick for compaction.
continue
}
// If the stale data size is less than 10 MB, it might not be worth
// rewriting the table. Skip it.
if t.StaleDataSize() < 10<<20 {
continue
}
cd.thisSize = t.Size()
cd.thisRange = getKeyRange(t)
// Set the next range as the same as the current range. If we don't do
// this, we won't be able to run more than one max level compactions.
cd.nextRange = cd.thisRange
// If we're already compacting this range, don't do anything.
if s.cstatus.overlapsWith(cd.thisLevel.level, cd.thisRange) {
continue
}
// Found a valid table!
cd.top = []*table.Table{t}
needFileSz := cd.t.fileSz[cd.thisLevel.level]
// The table size is what we want so no need to collect more tables.
if t.Size() >= needFileSz {
break
}
// TableSize is less than what we want. Collect more tables for compaction.
// If the level has multiple small tables, we collect all of them
// together to form a bigger table.
collectBotTables(t, needFileSz)
if !s.cstatus.compareAndAdd(thisAndNextLevelRLocked{}, *cd) {
cd.bot = cd.bot[:0]
cd.nextRange = keyRange{}
continue
}
return true
}
if len(cd.top) == 0 {
return false
}
return s.cstatus.compareAndAdd(thisAndNextLevelRLocked{}, *cd)
}
func (s *levelsController) fillTables(cd *compactDef) bool {
cd.lockLevels()
defer cd.unlockLevels()
tables := make([]*table.Table, len(cd.thisLevel.tables))
copy(tables, cd.thisLevel.tables)
if len(tables) == 0 {
return false
}
// We're doing a maxLevel to maxLevel compaction. Pick tables based on the stale data size.
if cd.thisLevel.isLastLevel() {
return s.fillMaxLevelTables(tables, cd)
}
// We pick tables, so we compact older tables first. This is similar to
// kOldestLargestSeqFirst in RocksDB.
s.sortByHeuristic(tables, cd)
for _, t := range tables {
cd.thisSize = t.Size()
cd.thisRange = getKeyRange(t)
// If we're already compacting this range, don't do anything.
if s.cstatus.overlapsWith(cd.thisLevel.level, cd.thisRange) {
continue
}
cd.top = []*table.Table{t}
left, right := cd.nextLevel.overlappingTables(levelHandlerRLocked{}, cd.thisRange)
cd.bot = make([]*table.Table, right-left)
copy(cd.bot, cd.nextLevel.tables[left:right])
if len(cd.bot) == 0 {
cd.bot = []*table.Table{}
cd.nextRange = cd.thisRange
if !s.cstatus.compareAndAdd(thisAndNextLevelRLocked{}, *cd) {
continue
}
return true
}
cd.nextRange = getKeyRange(cd.bot...)
if s.cstatus.overlapsWith(cd.nextLevel.level, cd.nextRange) {
continue
}
if !s.cstatus.compareAndAdd(thisAndNextLevelRLocked{}, *cd) {
continue
}
return true
}
return false
}
func (s *levelsController) runCompactDef(id, l int, cd compactDef) (err error) {
if len(cd.t.fileSz) == 0 {
return errors.New("Filesizes cannot be zero. Targets are not set")
}
timeStart := time.Now()
thisLevel := cd.thisLevel
nextLevel := cd.nextLevel
y.AssertTrue(len(cd.splits) == 0)
if thisLevel.level == nextLevel.level {
// don't do anything for L0 -> L0 and Lmax -> Lmax.
} else {
s.addSplits(&cd)
}
if len(cd.splits) == 0 {
cd.splits = append(cd.splits, keyRange{})
}
// Table should never be moved directly between levels,
// always be rewritten to allow discarding invalid versions.
newTables, decr, err := s.compactBuildTables(l, cd)
if err != nil {
return err
}
defer func() {
// Only assign to err, if it's not already nil.
if decErr := decr(); err == nil {
err = decErr
}
}()
changeSet := buildChangeSet(&cd, newTables)
// We write to the manifest _before_ we delete files (and after we created files)
if err := s.kv.manifest.addChanges(changeSet.Changes, s.kv.opt); err != nil {
return err
}
getSizes := func(tables []*table.Table) int64 {
size := int64(0)
for _, i := range tables {
size += i.Size()
}
return size
}
sizeNewTables := int64(0)
sizeOldTables := int64(0)
if s.kv.opt.MetricsEnabled {
sizeNewTables = getSizes(newTables)
sizeOldTables = getSizes(cd.bot) + getSizes(cd.top)
y.NumBytesCompactionWrittenAdd(s.kv.opt.MetricsEnabled, nextLevel.strLevel, sizeNewTables)
}
// See comment earlier in this function about the ordering of these ops, and the order in which
// we access levels when reading.
if err := nextLevel.replaceTables(cd.bot, newTables); err != nil {
return err
}
if err := thisLevel.deleteTables(cd.top); err != nil {
return err
}
// Note: For level 0, while doCompact is running, it is possible that new tables are added.
// However, the tables are added only to the end, so it is ok to just delete the first table.
from := append(tablesToString(cd.top), tablesToString(cd.bot)...)
to := tablesToString(newTables)
if dur := time.Since(timeStart); dur > 2*time.Second {
var expensive string
if dur > time.Second {
expensive = " [E]"
}
s.kv.opt.Infof("[%d]%s LOG Compact %d->%d (%d, %d -> %d tables with %d splits)."+
" [%s] -> [%s], took %v\n, deleted %d bytes",
id, expensive, thisLevel.level, nextLevel.level, len(cd.top), len(cd.bot),
len(newTables), len(cd.splits), strings.Join(from, " "), strings.Join(to, " "),
dur.Round(time.Millisecond), sizeOldTables-sizeNewTables)
}
if cd.thisLevel.level != 0 && len(newTables) > 2*s.kv.opt.LevelSizeMultiplier {
s.kv.opt.Infof("This Range (numTables: %d)\nLeft:\n%s\nRight:\n%s\n",
len(cd.top), hex.Dump(cd.thisRange.left), hex.Dump(cd.thisRange.right))
s.kv.opt.Infof("Next Range (numTables: %d)\nLeft:\n%s\nRight:\n%s\n",
len(cd.bot), hex.Dump(cd.nextRange.left), hex.Dump(cd.nextRange.right))
}
return nil
}
func tablesToString(tables []*table.Table) []string {
var res []string
for _, t := range tables {
res = append(res, fmt.Sprintf("%05d", t.ID()))
}
res = append(res, ".")
return res
}
var errFillTables = errors.New("Unable to fill tables")
// doCompact picks some table on level l and compacts it away to the next level.
func (s *levelsController) doCompact(id int, p compactionPriority) error {
l := p.level
y.AssertTrue(l < s.kv.opt.MaxLevels) // Sanity check.
if p.t.baseLevel == 0 {
p.t = s.levelTargets()
}
_, span := otel.Tracer("").Start(context.TODO(), "Badger.Compaction")
defer span.End()
cd := compactDef{
compactorId: id,
p: p,
t: p.t,
thisLevel: s.levels[l],
dropPrefixes: p.dropPrefixes,
}
// While picking tables to be compacted, both levels' tables are expected to
// remain unchanged.
if l == 0 {
cd.nextLevel = s.levels[p.t.baseLevel]
if !s.fillTablesL0(&cd) {
return errFillTables
}
} else {
cd.nextLevel = cd.thisLevel
// We're not compacting the last level so pick the next level.
if !cd.thisLevel.isLastLevel() {
cd.nextLevel = s.levels[l+1]
}
if !s.fillTables(&cd) {
return errFillTables
}
}
defer s.cstatus.delete(cd) // Remove the ranges from compaction status.
span.SetAttributes(attribute.String("Compaction", fmt.Sprintf("%+v", cd)))
if err := s.runCompactDef(id, l, cd); err != nil {
// This compaction couldn't be done successfully.
s.kv.opt.Warningf("[Compactor: %d] LOG Compact FAILED with error: %+v: %+v", id, err, cd)
return err
}
span.SetAttributes(
attribute.Int("Top tables count", len(cd.top)),
attribute.Int("Bottom tables count", len(cd.bot)))
s.kv.opt.Debugf("[Compactor: %d] Compaction for level: %d DONE", id, cd.thisLevel.level)
return nil
}
func (s *levelsController) addLevel0Table(t *table.Table) error {
// Add table to manifest file only if it is not opened in memory. We don't want to add a table
// to the manifest file if it exists only in memory.
if !t.IsInmemory {
// We update the manifest _before_ the table becomes part of a levelHandler, because at that
// point it could get used in some compaction. This ensures the manifest file gets updated in
// the proper order. (That means this update happens before that of some compaction which
// deletes the table.)
err := s.kv.manifest.addChanges([]*pb.ManifestChange{
newCreateChange(t.ID(), 0, t.KeyID(), t.CompressionType()),
}, s.kv.opt)
if err != nil {
return err
}
}
for !s.levels[0].tryAddLevel0Table(t) {
// Before we uninstall, we need to make sure that level 0 is healthy.
timeStart := time.Now()
for s.levels[0].numTables() >= s.kv.opt.NumLevelZeroTablesStall {
time.Sleep(10 * time.Millisecond)
}
dur := time.Since(timeStart)
if dur > time.Second {
s.kv.opt.Infof("L0 was stalled for %s\n", dur.Round(time.Millisecond))
}
s.l0stallsMs.Add(int64(dur.Round(time.Millisecond)))
}
return nil
}
func (s *levelsController) close() error {
err := s.cleanupLevels()
return y.Wrap(err, "levelsController.Close")
}
// get searches for a given key in all the levels of the LSM tree. It returns
// key version <= the expected version (version in key). If not found,
// it returns an empty y.ValueStruct.
func (s *levelsController) get(key []byte, maxVs y.ValueStruct, startLevel int) (
y.ValueStruct, error) {
if s.kv.IsClosed() {
return y.ValueStruct{}, ErrDBClosed
}
// It's important that we iterate the levels from 0 on upward. The reason is, if we iterated
// in opposite order, or in parallel (naively calling all the h.RLock() in some order) we could
// read level L's tables post-compaction and level L+1's tables pre-compaction. (If we do
// parallelize this, we will need to call the h.RLock() function by increasing order of level
// number.)
version := y.ParseTs(key)
for _, h := range s.levels {
// Ignore all levels below startLevel. This is useful for GC when L0 is kept in memory.
if h.level < startLevel {
continue
}
vs, err := h.get(key) // Calls h.RLock() and h.RUnlock().
if err != nil {
return y.ValueStruct{}, y.Wrapf(err, "get key: %q", key)
}
if vs.Value == nil && vs.Meta == 0 {
continue
}
y.NumBytesReadsLSMAdd(s.kv.opt.MetricsEnabled, int64(len(vs.Value)))
if vs.Version == version {
return vs, nil
}
if maxVs.Version < vs.Version {
maxVs = vs
}
}
if len(maxVs.Value) > 0 {
y.NumGetsWithResultsAdd(s.kv.opt.MetricsEnabled, 1)
}
return maxVs, nil
}
func appendIteratorsReversed(out []y.Iterator, th []*table.Table, opt int) []y.Iterator {
for i := len(th) - 1; i >= 0; i-- {
// This will increment the reference of the table handler.
out = append(out, th[i].NewIterator(opt))
}
return out
}
// appendIterators appends iterators to an array of iterators, for merging.
// Note: This obtains references for the table handlers. Remember to close these iterators.
func (s *levelsController) appendIterators(
iters []y.Iterator, opt *IteratorOptions) []y.Iterator {
// Just like with get, it's important we iterate the levels from 0 on upward, to avoid missing
// data when there's a compaction.
for _, level := range s.levels {
iters = level.appendIterators(iters, opt)
}
return iters
}
// TableInfo represents the information about a table.
type TableInfo struct {
ID uint64
Level int
Left []byte
Right []byte
KeyCount uint32 // Number of keys in the table
OnDiskSize uint32
StaleDataSize uint32
UncompressedSize uint32
MaxVersion uint64
IndexSz int
BloomFilterSize int
}
func (s *levelsController) getTableInfo() (result []TableInfo) {
for _, l := range s.levels {
l.RLock()
for _, t := range l.tables {
info := TableInfo{
ID: t.ID(),
Level: l.level,
Left: t.Smallest(),
Right: t.Biggest(),
KeyCount: t.KeyCount(),
OnDiskSize: t.OnDiskSize(),
StaleDataSize: t.StaleDataSize(),
IndexSz: t.IndexSize(),
BloomFilterSize: t.BloomFilterSize(),
UncompressedSize: t.UncompressedSize(),
MaxVersion: t.MaxVersion(),
}
result = append(result, info)
}
l.RUnlock()
}
sort.Slice(result, func(i, j int) bool {
if result[i].Level != result[j].Level {
return result[i].Level < result[j].Level
}
return result[i].ID < result[j].ID
})
return
}
type LevelInfo struct {
Level int
NumTables int
Size int64
TargetSize int64
TargetFileSize int64
IsBaseLevel bool
Score float64
Adjusted float64
StaleDatSize int64
}
func (s *levelsController) getLevelInfo() []LevelInfo {
t := s.levelTargets()
prios := s.pickCompactLevels(nil)
result := make([]LevelInfo, len(s.levels))
for i, l := range s.levels {
l.RLock()
result[i].Level = i
result[i].Size = l.totalSize
result[i].NumTables = len(l.tables)
result[i].StaleDatSize = l.totalStaleSize
l.RUnlock()
result[i].TargetSize = t.targetSz[i]
result[i].TargetFileSize = t.fileSz[i]
result[i].IsBaseLevel = t.baseLevel == i
}
for _, p := range prios {
result[p.level].Score = p.score
result[p.level].Adjusted = p.adjusted
}
return result
}
// verifyChecksum verifies checksum for all tables on all levels.
func (s *levelsController) verifyChecksum() error {
var tables []*table.Table
for _, l := range s.levels {
l.RLock()
tables = tables[:0]
for _, t := range l.tables {
tables = append(tables, t)
t.IncrRef()
}
l.RUnlock()
for _, t := range tables {
errChkVerify := t.VerifyChecksum()
if err := t.DecrRef(); err != nil {
s.kv.opt.Errorf("unable to decrease reference of table: %s while "+
"verifying checksum with error: %s", t.Filename(), err)
}
if errChkVerify != nil {
return errChkVerify
}
}
}
return nil
}
// Returns the sorted list of splits for all the levels and tables based
// on the block offsets.
func (s *levelsController) keySplits(numPerTable int, prefix []byte) []string {
splits := make([]string, 0)
for _, l := range s.levels {
l.RLock()
for _, t := range l.tables {
tableSplits := t.KeySplits(numPerTable, prefix)
splits = append(splits, tableSplits...)
}
l.RUnlock()
}
sort.Strings(splits)
return splits
}
================================================
FILE: levels_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"fmt"
"math"
"math/rand"
"os"
"sort"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/dgraph-io/badger/v4/options"
"github.com/dgraph-io/badger/v4/pb"
"github.com/dgraph-io/badger/v4/table"
"github.com/dgraph-io/badger/v4/y"
)
// createAndOpen creates a table with the given data and adds it to the given level.
func createAndOpen(db *DB, td []keyValVersion, level int) {
opts := table.Options{
BlockSize: db.opt.BlockSize,
BloomFalsePositive: db.opt.BloomFalsePositive,
ChkMode: options.NoVerification,
}
b := table.NewTableBuilder(opts)
defer b.Close()
// Add all keys and versions to the table.
for _, item := range td {
key := y.KeyWithTs([]byte(item.key), uint64(item.version))
val := y.ValueStruct{Value: []byte(item.val), Meta: item.meta}
b.Add(key, val, 0)
}
fname := table.NewFilename(db.lc.reserveFileID(), db.opt.Dir)
tab, err := table.CreateTable(fname, b)
if err != nil {
panic(err)
}
if err := db.manifest.addChanges([]*pb.ManifestChange{
newCreateChange(tab.ID(), level, 0, tab.CompressionType()),
}, db.opt); err != nil {
panic(err)
}
db.lc.levels[level].Lock()
// Add table to the given level.
db.lc.levels[level].tables = append(db.lc.levels[level].tables, tab)
db.lc.levels[level].Unlock()
}
type keyValVersion struct {
key string
val string
version int
meta byte
}
func TestCheckOverlap(t *testing.T) {
t.Run("overlap", func(t *testing.T) {
// This test consists of one table on level 0 and one on level 1.
// There is an overlap amongst the tables but there is no overlap
// with rest of the levels.
t.Run("same keys", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
l0 := []keyValVersion{{"foo", "bar", 3, 0}}
l1 := []keyValVersion{{"foo", "bar", 2, 0}}
createAndOpen(db, l0, 0)
createAndOpen(db, l1, 1)
// Level 0 should overlap with level 0 tables.
require.True(t, db.lc.checkOverlap(db.lc.levels[0].tables, 0))
// Level 1 should overlap with level 0 tables (they have the same keys).
require.True(t, db.lc.checkOverlap(db.lc.levels[0].tables, 1))
// Level 2 and 3 should not overlap with level 0 tables.
require.False(t, db.lc.checkOverlap(db.lc.levels[0].tables, 2))
require.False(t, db.lc.checkOverlap(db.lc.levels[1].tables, 2))
require.False(t, db.lc.checkOverlap(db.lc.levels[0].tables, 3))
require.False(t, db.lc.checkOverlap(db.lc.levels[1].tables, 3))
})
})
t.Run("overlapping keys", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
l0 := []keyValVersion{{"a", "x", 1, 0}, {"b", "x", 1, 0}, {"foo", "bar", 3, 0}}
l1 := []keyValVersion{{"foo", "bar", 2, 0}}
createAndOpen(db, l0, 0)
createAndOpen(db, l1, 1)
// Level 0 should overlap with level 0 tables.
require.True(t, db.lc.checkOverlap(db.lc.levels[0].tables, 0))
require.True(t, db.lc.checkOverlap(db.lc.levels[1].tables, 1))
// Level 1 should overlap with level 0 tables, "foo" key is common.
require.True(t, db.lc.checkOverlap(db.lc.levels[0].tables, 1))
// Level 2 and 3 should not overlap with level 0 tables.
require.False(t, db.lc.checkOverlap(db.lc.levels[0].tables, 2))
require.False(t, db.lc.checkOverlap(db.lc.levels[0].tables, 3))
})
})
})
t.Run("non-overlapping", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
l0 := []keyValVersion{{"a", "x", 1, 0}, {"b", "x", 1, 0}, {"c", "bar", 3, 0}}
l1 := []keyValVersion{{"foo", "bar", 2, 0}}
createAndOpen(db, l0, 0)
createAndOpen(db, l1, 1)
// Level 1 should not overlap with level 0 tables
require.False(t, db.lc.checkOverlap(db.lc.levels[0].tables, 1))
// Level 2 and 3 should not overlap with level 0 tables.
require.False(t, db.lc.checkOverlap(db.lc.levels[0].tables, 2))
require.False(t, db.lc.checkOverlap(db.lc.levels[0].tables, 3))
})
})
}
func getAllAndCheck(t *testing.T, db *DB, expected []keyValVersion) {
require.NoError(t, db.View(func(txn *Txn) error {
opt := DefaultIteratorOptions
opt.AllVersions = true
opt.InternalAccess = true
it := txn.NewIterator(opt)
defer it.Close()
i := 0
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
v, err := item.ValueCopy(nil)
require.NoError(t, err)
// fmt.Printf("k: %s v: %d val: %s\n", item.key, item.Version(), v)
require.Less(t, i, len(expected), "DB has more number of key than expected")
expect := expected[i]
require.Equal(t, expect.key, string(item.Key()), "expected key: %s actual key: %s",
expect.key, item.Key())
require.Equal(t, expect.val, string(v), "key: %s expected value: %s actual %s",
item.key, expect.val, v)
require.Equal(t, expect.version, int(item.Version()),
"key: %s expected version: %d actual %d", item.key, expect.version, item.Version())
require.Equal(t, expect.meta, item.meta,
"key: %s expected meta: %d meta %d", item.key, expect.meta, item.meta)
i++
}
require.Equal(t, len(expected), i, "keys examined should be equal to keys expected")
return nil
}))
}
func TestCompaction(t *testing.T) {
// Disable compactions and keep single version of each key.
opt := DefaultOptions("").WithNumCompactors(0).WithNumVersionsToKeep(1)
opt.managedTxns = true
t.Run("level 0 to level 1", func(t *testing.T) {
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
l0 := []keyValVersion{{"foo", "bar", 3, 0}, {"fooz", "baz", 1, 0}}
l01 := []keyValVersion{{"foo", "bar", 2, 0}}
l1 := []keyValVersion{{"foo", "bar", 1, 0}}
// Level 0 has table l0 and l01.
createAndOpen(db, l0, 0)
createAndOpen(db, l01, 0)
// Level 1 has table l1.
createAndOpen(db, l1, 1)
// Set a high discard timestamp so that all the keys are below the discard timestamp.
db.SetDiscardTs(10)
getAllAndCheck(t, db, []keyValVersion{
{"foo", "bar", 3, 0}, {"foo", "bar", 2, 0},
{"foo", "bar", 1, 0}, {"fooz", "baz", 1, 0},
})
cdef := compactDef{
thisLevel: db.lc.levels[0],
nextLevel: db.lc.levels[1],
top: db.lc.levels[0].tables,
bot: db.lc.levels[1].tables,
t: db.lc.levelTargets(),
}
cdef.t.baseLevel = 1
require.NoError(t, db.lc.runCompactDef(-1, 0, cdef))
// foo version 2 should be dropped after compaction.
getAllAndCheck(t, db, []keyValVersion{{"foo", "bar", 3, 0}, {"fooz", "baz", 1, 0}})
})
})
t.Run("level 0 to level 1 with duplicates", func(t *testing.T) {
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
// We have foo version 3 on L0 because we gc'ed it.
l0 := []keyValVersion{{"foo", "barNew", 3, 0}, {"fooz", "baz", 1, 0}}
l01 := []keyValVersion{{"foo", "bar", 4, 0}}
l1 := []keyValVersion{{"foo", "bar", 3, 0}}
// Level 0 has table l0 and l01.
createAndOpen(db, l0, 0)
createAndOpen(db, l01, 0)
// Level 1 has table l1.
createAndOpen(db, l1, 1)
// Set a high discard timestamp so that all the keys are below the discard timestamp.
db.SetDiscardTs(10)
getAllAndCheck(t, db, []keyValVersion{
{"foo", "bar", 4, 0}, {"foo", "barNew", 3, 0},
{"fooz", "baz", 1, 0},
})
cdef := compactDef{
thisLevel: db.lc.levels[0],
nextLevel: db.lc.levels[1],
top: db.lc.levels[0].tables,
bot: db.lc.levels[1].tables,
t: db.lc.levelTargets(),
}
cdef.t.baseLevel = 1
require.NoError(t, db.lc.runCompactDef(-1, 0, cdef))
// foo version 3 (both) should be dropped after compaction.
getAllAndCheck(t, db, []keyValVersion{{"foo", "bar", 4, 0}, {"fooz", "baz", 1, 0}})
})
})
t.Run("level 0 to level 1 with lower overlap", func(t *testing.T) {
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
l0 := []keyValVersion{{"foo", "bar", 4, 0}, {"fooz", "baz", 1, 0}}
l01 := []keyValVersion{{"foo", "bar", 3, 0}}
l1 := []keyValVersion{{"foo", "bar", 2, 0}}
l2 := []keyValVersion{{"foo", "bar", 1, 0}}
// Level 0 has table l0 and l01.
createAndOpen(db, l0, 0)
createAndOpen(db, l01, 0)
// Level 1 has table l1.
createAndOpen(db, l1, 1)
// Level 2 has table l2.
createAndOpen(db, l2, 2)
// Set a high discard timestamp so that all the keys are below the discard timestamp.
db.SetDiscardTs(10)
getAllAndCheck(t, db, []keyValVersion{
{"foo", "bar", 4, 0}, {"foo", "bar", 3, 0}, {"foo", "bar", 2, 0},
{"foo", "bar", 1, 0}, {"fooz", "baz", 1, 0},
})
cdef := compactDef{
thisLevel: db.lc.levels[0],
nextLevel: db.lc.levels[1],
top: db.lc.levels[0].tables,
bot: db.lc.levels[1].tables,
t: db.lc.levelTargets(),
}
cdef.t.baseLevel = 1
require.NoError(t, db.lc.runCompactDef(-1, 0, cdef))
// foo version 2 and version 1 should be dropped after compaction.
getAllAndCheck(t, db, []keyValVersion{
{"foo", "bar", 4, 0}, {"foo", "bar", 1, 0}, {"fooz", "baz", 1, 0},
})
})
})
t.Run("level 1 to level 2", func(t *testing.T) {
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
l1 := []keyValVersion{{"foo", "bar", 3, 0}, {"fooz", "baz", 1, 0}}
l2 := []keyValVersion{{"foo", "bar", 2, 0}}
createAndOpen(db, l1, 1)
createAndOpen(db, l2, 2)
// Set a high discard timestamp so that all the keys are below the discard timestamp.
db.SetDiscardTs(10)
getAllAndCheck(t, db, []keyValVersion{
{"foo", "bar", 3, 0}, {"foo", "bar", 2, 0}, {"fooz", "baz", 1, 0},
})
cdef := compactDef{
thisLevel: db.lc.levels[1],
nextLevel: db.lc.levels[2],
top: db.lc.levels[1].tables,
bot: db.lc.levels[2].tables,
t: db.lc.levelTargets(),
}
cdef.t.baseLevel = 2
require.NoError(t, db.lc.runCompactDef(-1, 1, cdef))
// foo version 2 should be dropped after compaction.
getAllAndCheck(t, db, []keyValVersion{{"foo", "bar", 3, 0}, {"fooz", "baz", 1, 0}})
})
})
t.Run("level 1 to level 2 with delete", func(t *testing.T) {
t.Run("with overlap", func(t *testing.T) {
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
l1 := []keyValVersion{{"foo", "bar", 3, bitDelete}, {"fooz", "baz", 1, bitDelete}}
l2 := []keyValVersion{{"foo", "bar", 2, 0}}
l3 := []keyValVersion{{"foo", "bar", 1, 0}}
createAndOpen(db, l1, 1)
createAndOpen(db, l2, 2)
createAndOpen(db, l3, 3)
// Set a high discard timestamp so that all the keys are below the discard timestamp.
db.SetDiscardTs(10)
getAllAndCheck(t, db, []keyValVersion{
{"foo", "bar", 3, 1},
{"foo", "bar", 2, 0},
{"foo", "bar", 1, 0},
{"fooz", "baz", 1, 1},
})
cdef := compactDef{
thisLevel: db.lc.levels[1],
nextLevel: db.lc.levels[2],
top: db.lc.levels[1].tables,
bot: db.lc.levels[2].tables,
t: db.lc.levelTargets(),
}
cdef.t.baseLevel = 2
require.NoError(t, db.lc.runCompactDef(-1, 1, cdef))
// foo bar version 2 should be dropped after compaction. fooz
// baz version 1 will remain because overlap exists, which is
// expected because `hasOverlap` is only checked once at the
// beginning of `compactBuildTables` method.
// everything from level 1 is now in level 2.
getAllAndCheck(t, db, []keyValVersion{
{"foo", "bar", 3, bitDelete},
{"foo", "bar", 1, 0},
{"fooz", "baz", 1, 1},
})
cdef = compactDef{
thisLevel: db.lc.levels[2],
nextLevel: db.lc.levels[3],
top: db.lc.levels[2].tables,
bot: db.lc.levels[3].tables,
t: db.lc.levelTargets(),
}
cdef.t.baseLevel = 3
require.NoError(t, db.lc.runCompactDef(-1, 2, cdef))
// everything should be removed now
getAllAndCheck(t, db, []keyValVersion{})
})
})
t.Run("with bottom overlap", func(t *testing.T) {
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
l1 := []keyValVersion{{"foo", "bar", 3, bitDelete}}
l2 := []keyValVersion{{"foo", "bar", 2, 0}, {"fooz", "baz", 2, bitDelete}}
l3 := []keyValVersion{{"fooz", "baz", 1, 0}}
createAndOpen(db, l1, 1)
createAndOpen(db, l2, 2)
createAndOpen(db, l3, 3)
// Set a high discard timestamp so that all the keys are below the discard timestamp.
db.SetDiscardTs(10)
getAllAndCheck(t, db, []keyValVersion{
{"foo", "bar", 3, bitDelete},
{"foo", "bar", 2, 0},
{"fooz", "baz", 2, bitDelete},
{"fooz", "baz", 1, 0},
})
cdef := compactDef{
thisLevel: db.lc.levels[1],
nextLevel: db.lc.levels[2],
top: db.lc.levels[1].tables,
bot: db.lc.levels[2].tables,
t: db.lc.levelTargets(),
}
cdef.t.baseLevel = 2
require.NoError(t, db.lc.runCompactDef(-1, 1, cdef))
// the top table at L1 doesn't overlap L3, but the bottom table at L2
// does, delete keys should not be removed.
getAllAndCheck(t, db, []keyValVersion{
{"foo", "bar", 3, bitDelete},
{"fooz", "baz", 2, bitDelete},
{"fooz", "baz", 1, 0},
})
})
})
t.Run("without overlap", func(t *testing.T) {
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
l1 := []keyValVersion{{"foo", "bar", 3, bitDelete}, {"fooz", "baz", 1, bitDelete}}
l2 := []keyValVersion{{"fooo", "barr", 2, 0}}
createAndOpen(db, l1, 1)
createAndOpen(db, l2, 2)
// Set a high discard timestamp so that all the keys are below the discard timestamp.
db.SetDiscardTs(10)
getAllAndCheck(t, db, []keyValVersion{
{"foo", "bar", 3, 1}, {"fooo", "barr", 2, 0}, {"fooz", "baz", 1, 1},
})
cdef := compactDef{
thisLevel: db.lc.levels[1],
nextLevel: db.lc.levels[2],
top: db.lc.levels[1].tables,
bot: db.lc.levels[2].tables,
t: db.lc.levelTargets(),
}
cdef.t.baseLevel = 2
require.NoError(t, db.lc.runCompactDef(-1, 1, cdef))
// foo version 2 should be dropped after compaction.
getAllAndCheck(t, db, []keyValVersion{{"fooo", "barr", 2, 0}})
})
})
t.Run("with splits", func(t *testing.T) {
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
l1 := []keyValVersion{{"C", "bar", 3, bitDelete}}
l21 := []keyValVersion{{"A", "bar", 2, 0}}
l22 := []keyValVersion{{"B", "bar", 2, 0}}
l23 := []keyValVersion{{"C", "bar", 2, 0}}
l24 := []keyValVersion{{"D", "bar", 2, 0}}
l3 := []keyValVersion{{"fooz", "baz", 1, 0}}
createAndOpen(db, l1, 1)
createAndOpen(db, l21, 2)
createAndOpen(db, l22, 2)
createAndOpen(db, l23, 2)
createAndOpen(db, l24, 2)
createAndOpen(db, l3, 3)
// Set a high discard timestamp so that all the keys are below the discard timestamp.
db.SetDiscardTs(10)
getAllAndCheck(t, db, []keyValVersion{
{"A", "bar", 2, 0},
{"B", "bar", 2, 0},
{"C", "bar", 3, bitDelete},
{"C", "bar", 2, 0},
{"D", "bar", 2, 0},
{"fooz", "baz", 1, 0},
})
cdef := compactDef{
thisLevel: db.lc.levels[1],
nextLevel: db.lc.levels[2],
top: db.lc.levels[1].tables,
bot: db.lc.levels[2].tables,
t: db.lc.levelTargets(),
}
cdef.t.baseLevel = 2
require.NoError(t, db.lc.runCompactDef(-1, 1, cdef))
getAllAndCheck(t, db, []keyValVersion{
{"A", "bar", 2, 0},
{"B", "bar", 2, 0},
{"D", "bar", 2, 0},
{"fooz", "baz", 1, 0},
})
})
})
})
}
func TestCompactionTwoVersions(t *testing.T) {
// Disable compactions and keep two versions of each key.
opt := DefaultOptions("").WithNumCompactors(0).WithNumVersionsToKeep(2)
opt.managedTxns = true
t.Run("with overlap", func(t *testing.T) {
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
l1 := []keyValVersion{{"foo", "bar", 3, 0}, {"fooz", "baz", 1, bitDelete}}
l2 := []keyValVersion{{"foo", "bar", 2, 0}}
l3 := []keyValVersion{{"foo", "bar", 1, 0}}
createAndOpen(db, l1, 1)
createAndOpen(db, l2, 2)
createAndOpen(db, l3, 3)
// Set a high discard timestamp so that all the keys are below the discard timestamp.
db.SetDiscardTs(10)
getAllAndCheck(t, db, []keyValVersion{
{"foo", "bar", 3, 0},
{"foo", "bar", 2, 0},
{"foo", "bar", 1, 0},
{"fooz", "baz", 1, 1},
})
cdef := compactDef{
thisLevel: db.lc.levels[1],
nextLevel: db.lc.levels[2],
top: db.lc.levels[1].tables,
bot: db.lc.levels[2].tables,
t: db.lc.levelTargets(),
}
cdef.t.baseLevel = 2
require.NoError(t, db.lc.runCompactDef(-1, 1, cdef))
// Nothing should be dropped after compaction because number of
// versions to keep is 2.
getAllAndCheck(t, db, []keyValVersion{
{"foo", "bar", 3, 0},
{"foo", "bar", 2, 0},
{"foo", "bar", 1, 0},
{"fooz", "baz", 1, 1},
})
cdef = compactDef{
thisLevel: db.lc.levels[2],
nextLevel: db.lc.levels[3],
top: db.lc.levels[2].tables,
bot: db.lc.levels[3].tables,
t: db.lc.levelTargets(),
}
cdef.t.baseLevel = 3
require.NoError(t, db.lc.runCompactDef(-1, 2, cdef))
getAllAndCheck(t, db, []keyValVersion{
{"foo", "bar", 3, 0},
{"foo", "bar", 2, 0},
})
})
})
}
func TestCompactionAllVersions(t *testing.T) {
// Disable compactions and keep all versions of the each key.
opt := DefaultOptions("").WithNumCompactors(0).WithNumVersionsToKeep(math.MaxInt32)
opt.managedTxns = true
t.Run("without overlap", func(t *testing.T) {
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
l1 := []keyValVersion{{"foo", "bar", 3, 0}, {"fooz", "baz", 1, bitDelete}}
l2 := []keyValVersion{{"foo", "bar", 2, 0}}
l3 := []keyValVersion{{"foo", "bar", 1, 0}}
createAndOpen(db, l1, 1)
createAndOpen(db, l2, 2)
createAndOpen(db, l3, 3)
// Set a high discard timestamp so that all the keys are below the discard timestamp.
db.SetDiscardTs(10)
getAllAndCheck(t, db, []keyValVersion{
{"foo", "bar", 3, 0},
{"foo", "bar", 2, 0},
{"foo", "bar", 1, 0},
{"fooz", "baz", 1, 1},
})
cdef := compactDef{
thisLevel: db.lc.levels[1],
nextLevel: db.lc.levels[2],
top: db.lc.levels[1].tables,
bot: db.lc.levels[2].tables,
t: db.lc.levelTargets(),
}
cdef.t.baseLevel = 2
require.NoError(t, db.lc.runCompactDef(-1, 1, cdef))
// Nothing should be dropped after compaction because all versions
// should be kept.
getAllAndCheck(t, db, []keyValVersion{
{"foo", "bar", 3, 0},
{"foo", "bar", 2, 0},
{"foo", "bar", 1, 0},
{"fooz", "baz", 1, 1},
})
cdef = compactDef{
thisLevel: db.lc.levels[2],
nextLevel: db.lc.levels[3],
top: db.lc.levels[2].tables,
bot: db.lc.levels[3].tables,
t: db.lc.levelTargets(),
}
cdef.t.baseLevel = 3
require.NoError(t, db.lc.runCompactDef(-1, 2, cdef))
getAllAndCheck(t, db, []keyValVersion{
{"foo", "bar", 3, 0},
{"foo", "bar", 2, 0},
{"foo", "bar", 1, 0},
})
})
})
t.Run("without overlap", func(t *testing.T) {
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
l1 := []keyValVersion{{"foo", "bar", 3, bitDelete}, {"fooz", "baz", 1, bitDelete}}
l2 := []keyValVersion{{"fooo", "barr", 2, 0}}
createAndOpen(db, l1, 1)
createAndOpen(db, l2, 2)
// Set a high discard timestamp so that all the keys are below the discard timestamp.
db.SetDiscardTs(10)
getAllAndCheck(t, db, []keyValVersion{
{"foo", "bar", 3, 1}, {"fooo", "barr", 2, 0}, {"fooz", "baz", 1, 1},
})
cdef := compactDef{
thisLevel: db.lc.levels[1],
nextLevel: db.lc.levels[2],
top: db.lc.levels[1].tables,
bot: db.lc.levels[2].tables,
t: db.lc.levelTargets(),
}
cdef.t.baseLevel = 2
require.NoError(t, db.lc.runCompactDef(-1, 1, cdef))
// foo version 2 should be dropped after compaction.
getAllAndCheck(t, db, []keyValVersion{{"fooo", "barr", 2, 0}})
})
})
}
func TestDiscardTs(t *testing.T) {
// Disable compactions and keep single version of each key.
opt := DefaultOptions("").WithNumCompactors(0).WithNumVersionsToKeep(1)
opt.managedTxns = true
t.Run("all keys above discardTs", func(t *testing.T) {
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
l0 := []keyValVersion{{"foo", "bar", 4, 0}, {"fooz", "baz", 3, 0}}
l01 := []keyValVersion{{"foo", "bar", 3, 0}}
l1 := []keyValVersion{{"foo", "bar", 2, 0}}
// Level 0 has table l0 and l01.
createAndOpen(db, l0, 0)
createAndOpen(db, l01, 0)
// Level 1 has table l1.
createAndOpen(db, l1, 1)
// Set dicardTs to 1. All the keys are above discardTs.
db.SetDiscardTs(1)
getAllAndCheck(t, db, []keyValVersion{
{"foo", "bar", 4, 0}, {"foo", "bar", 3, 0},
{"foo", "bar", 2, 0}, {"fooz", "baz", 3, 0},
})
cdef := compactDef{
thisLevel: db.lc.levels[0],
nextLevel: db.lc.levels[1],
top: db.lc.levels[0].tables,
bot: db.lc.levels[1].tables,
t: db.lc.levelTargets(),
}
cdef.t.baseLevel = 1
require.NoError(t, db.lc.runCompactDef(-1, 0, cdef))
// No keys should be dropped.
getAllAndCheck(t, db, []keyValVersion{
{"foo", "bar", 4, 0}, {"foo", "bar", 3, 0},
{"foo", "bar", 2, 0}, {"fooz", "baz", 3, 0},
})
})
})
t.Run("some keys above discardTs", func(t *testing.T) {
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
l0 := []keyValVersion{
{"foo", "bar", 4, 0}, {"foo", "bar", 3, 0},
{"foo", "bar", 2, 0}, {"fooz", "baz", 2, 0},
}
l1 := []keyValVersion{{"foo", "bbb", 1, 0}}
createAndOpen(db, l0, 0)
createAndOpen(db, l1, 1)
// Set dicardTs to 3. foo2 and foo1 should be dropped.
db.SetDiscardTs(3)
getAllAndCheck(t, db, []keyValVersion{
{"foo", "bar", 4, 0}, {"foo", "bar", 3, 0}, {"foo", "bar", 2, 0},
{"foo", "bbb", 1, 0}, {"fooz", "baz", 2, 0},
})
cdef := compactDef{
thisLevel: db.lc.levels[0],
nextLevel: db.lc.levels[1],
top: db.lc.levels[0].tables,
bot: db.lc.levels[1].tables,
t: db.lc.levelTargets(),
}
cdef.t.baseLevel = 1
require.NoError(t, db.lc.runCompactDef(-1, 0, cdef))
// foo1 and foo2 should be dropped.
getAllAndCheck(t, db, []keyValVersion{
{"foo", "bar", 4, 0}, {"foo", "bar", 3, 0}, {"fooz", "baz", 2, 0},
})
})
})
t.Run("all keys below discardTs", func(t *testing.T) {
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
l0 := []keyValVersion{{"foo", "bar", 4, 0}, {"fooz", "baz", 3, 0}}
l01 := []keyValVersion{{"foo", "bar", 3, 0}}
l1 := []keyValVersion{{"foo", "bar", 2, 0}}
// Level 0 has table l0 and l01.
createAndOpen(db, l0, 0)
createAndOpen(db, l01, 0)
// Level 1 has table l1.
createAndOpen(db, l1, 1)
// Set dicardTs to 10. All the keys are below discardTs.
db.SetDiscardTs(10)
getAllAndCheck(t, db, []keyValVersion{
{"foo", "bar", 4, 0}, {"foo", "bar", 3, 0},
{"foo", "bar", 2, 0}, {"fooz", "baz", 3, 0},
})
cdef := compactDef{
thisLevel: db.lc.levels[0],
nextLevel: db.lc.levels[1],
top: db.lc.levels[0].tables,
bot: db.lc.levels[1].tables,
t: db.lc.levelTargets(),
}
cdef.t.baseLevel = 1
require.NoError(t, db.lc.runCompactDef(-1, 0, cdef))
// Only one version of every key should be left.
getAllAndCheck(t, db, []keyValVersion{{"foo", "bar", 4, 0}, {"fooz", "baz", 3, 0}})
})
})
}
// This is a test to ensure that the first entry with DiscardEarlierversion bit < DiscardTs
// is kept around (when numversionstokeep is infinite).
func TestDiscardFirstVersion(t *testing.T) {
opt := DefaultOptions("")
opt.NumCompactors = 0
opt.NumVersionsToKeep = math.MaxInt32
opt.managedTxns = true
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
l0 := []keyValVersion{{"foo", "bar", 1, 0}}
l01 := []keyValVersion{{"foo", "bar", 2, bitDiscardEarlierVersions}}
l02 := []keyValVersion{{"foo", "bar", 3, 0}}
l03 := []keyValVersion{{"foo", "bar", 4, 0}}
l04 := []keyValVersion{{"foo", "bar", 9, 0}}
l05 := []keyValVersion{{"foo", "bar", 10, bitDiscardEarlierVersions}}
// Level 0 has all the tables.
createAndOpen(db, l0, 0)
createAndOpen(db, l01, 0)
createAndOpen(db, l02, 0)
createAndOpen(db, l03, 0)
createAndOpen(db, l04, 0)
createAndOpen(db, l05, 0)
// Discard Time stamp is set to 7.
db.SetDiscardTs(7)
// Compact L0 to L1
cdef := compactDef{
thisLevel: db.lc.levels[0],
nextLevel: db.lc.levels[1],
top: db.lc.levels[0].tables,
bot: db.lc.levels[1].tables,
t: db.lc.levelTargets(),
}
cdef.t.baseLevel = 1
require.NoError(t, db.lc.runCompactDef(-1, 0, cdef))
// - Version 10, 9 lie above version 7 so they should be there.
// - Version 4, 3, 2 lie below the discardTs but they don't have the
// "bitDiscardEarlierVersions" versions set so they should not be removed because number
// of versions to keep is set to infinite.
// - Version 1 is below DiscardTS and below the first "bitDiscardEarlierVersions"
// marker so IT WILL BE REMOVED.
ExpectedKeys := []keyValVersion{
{"foo", "bar", 10, bitDiscardEarlierVersions},
{"foo", "bar", 9, 0},
{"foo", "bar", 4, 0},
{"foo", "bar", 3, 0},
{"foo", "bar", 2, bitDiscardEarlierVersions}}
getAllAndCheck(t, db, ExpectedKeys)
})
}
// This test ensures we don't stall when L1's size is greater than opt.LevelOneSize.
// We should stall only when L0 tables more than the opt.NumLevelZeroTableStall.
func TestL1Stall(t *testing.T) {
// TODO(ibrahim): Is this test still valid?
t.Skip()
opt := DefaultOptions("")
// Disable all compactions.
opt.NumCompactors = 0
// Number of level zero tables.
opt.NumLevelZeroTables = 3
// Addition of new tables will stall if there are 4 or more L0 tables.
opt.NumLevelZeroTablesStall = 4
// Level 1 size is 10 bytes.
opt.BaseLevelSize = 10
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
// Level 0 has 4 tables.
db.lc.levels[0].Lock()
db.lc.levels[0].tables = []*table.Table{createEmptyTable(db), createEmptyTable(db),
createEmptyTable(db), createEmptyTable(db)}
db.lc.levels[0].Unlock()
timeout := time.After(5 * time.Second)
done := make(chan bool)
// This is important. Set level 1 size more than the opt.LevelOneSize (we've set it to 10).
db.lc.levels[1].totalSize = 100
go func() {
tab := createEmptyTable(db)
require.NoError(t, db.lc.addLevel0Table(tab))
require.NoError(t, tab.DecrRef())
done <- true
}()
time.Sleep(time.Second)
db.lc.levels[0].Lock()
// Drop two tables from Level 0 so that addLevel0Table can make progress. Earlier table
// count was 4 which is equal to L0 stall count.
toDrop := db.lc.levels[0].tables[:2]
require.NoError(t, decrRefs(toDrop))
db.lc.levels[0].tables = db.lc.levels[0].tables[2:]
db.lc.levels[0].Unlock()
select {
case <-timeout:
t.Fatal("Test didn't finish in time")
case <-done:
}
})
}
func createEmptyTable(db *DB) *table.Table {
opts := table.Options{
BloomFalsePositive: db.opt.BloomFalsePositive,
ChkMode: options.NoVerification,
}
b := table.NewTableBuilder(opts)
defer b.Close()
// Add one key so that we can open this table.
b.Add(y.KeyWithTs([]byte("foo"), 1), y.ValueStruct{}, 0)
// Open table in memory to avoid adding changes to manifest file.
tab, err := table.OpenInMemoryTable(b.Finish(), db.lc.reserveFileID(), &opts)
if err != nil {
panic(err)
}
return tab
}
func TestL0Stall(t *testing.T) {
// TODO(ibrahim): Is this test still valid?
t.Skip()
opt := DefaultOptions("")
// Disable all compactions.
opt.NumCompactors = 0
// Number of level zero tables.
opt.NumLevelZeroTables = 3
// Addition of new tables will stall if there are 4 or more L0 tables.
opt.NumLevelZeroTablesStall = 4
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
db.lc.levels[0].Lock()
// Add NumLevelZeroTableStall+1 number of tables to level 0. This would fill up level
// zero and all new additions are expected to stall if L0 is in memory.
for i := 0; i < opt.NumLevelZeroTablesStall+1; i++ {
db.lc.levels[0].tables = append(db.lc.levels[0].tables, createEmptyTable(db))
}
db.lc.levels[0].Unlock()
timeout := time.After(5 * time.Second)
done := make(chan bool)
go func() {
tab := createEmptyTable(db)
require.NoError(t, db.lc.addLevel0Table(tab))
require.NoError(t, tab.DecrRef())
done <- true
}()
// Let it stall for a second.
time.Sleep(time.Second)
select {
case <-timeout:
t.Log("Timeout triggered")
// Mark this test as successful since L0 is in memory and the
// addition of new table to L0 is supposed to stall.
// Remove tables from level 0 so that the stalled
// compaction can make progress. This does not have any
// effect on the test. This is done so that the goroutine
// stuck on addLevel0Table can make progress and end.
db.lc.levels[0].Lock()
db.lc.levels[0].tables = nil
db.lc.levels[0].Unlock()
<-done
case <-done:
// The test completed before 5 second timeout. Mark it as successful.
t.Fatal("Test did not stall")
}
})
}
func TestLevelGet(t *testing.T) {
createLevel := func(db *DB, level int, data [][]keyValVersion) {
for _, v := range data {
createAndOpen(db, v, level)
}
}
type testData struct {
name string
// Keys on each level. keyValVersion[0] is the first table and so on.
levelData map[int][][]keyValVersion
expect []keyValVersion
}
test := func(t *testing.T, ti testData, db *DB) {
for level, data := range ti.levelData {
createLevel(db, level, data)
}
for _, item := range ti.expect {
key := y.KeyWithTs([]byte(item.key), uint64(item.version))
vs, err := db.get(key)
require.NoError(t, err)
require.Equal(t, item.val, string(vs.Value), "key:%s ver:%d", item.key, item.version)
}
}
tt := []testData{
{
"Normal",
map[int][][]keyValVersion{
0: { // Level 0 has 2 tables and each table has single key.
{{"foo", "bar10", 10, 0}},
{{"foo", "barSeven", 7, 0}},
},
1: { // Level 1 has 1 table with a single key.
{{"foo", "bar", 1, 0}},
},
},
[]keyValVersion{
{"foo", "bar", 1, 0},
{"foo", "barSeven", 7, 0},
{"foo", "bar10", 10, 0},
{"foo", "bar10", 11, 0}, // ver 11 doesn't exist so we should get bar10.
{"foo", "barSeven", 9, 0}, // ver 9 doesn't exist so we should get barSeven.
{"foo", "bar10", 100000, 0}, // ver doesn't exist so we should get bar10.
},
},
{"after gc",
map[int][][]keyValVersion{
0: { // Level 0 has 3 tables and each table has single key.
{{"foo", "barNew", 1, 0}}, // foo1 is above foo10 because of the GC.
{{"foo", "bar10", 10, 0}},
{{"foo", "barSeven", 7, 0}},
},
1: { // Level 1 has 1 table with a single key.
{{"foo", "bar", 1, 0}},
},
},
[]keyValVersion{
{"foo", "barNew", 1, 0},
{"foo", "barSeven", 7, 0},
{"foo", "bar10", 10, 0},
{"foo", "bar10", 11, 0}, // Should return biggest version.
},
},
{"after two gc",
map[int][][]keyValVersion{
0: { // Level 0 has 4 tables and each table has single key.
{{"foo", "barL0", 1, 0}}, // foo1 is above foo10 because of the GC.
{{"foo", "bar10", 10, 0}},
{{"foo", "barSeven", 7, 0}},
},
1: { // Level 1 has 1 table with a single key.
// Level 1 also has a foo because it was moved twice during GC.
{{"foo", "barL1", 1, 0}},
},
2: { // Level 1 has 1 table with a single key.
{{"foo", "bar", 1, 0}},
},
},
[]keyValVersion{
{"foo", "barL0", 1, 0},
{"foo", "barSeven", 7, 0},
{"foo", "bar10", 10, 0},
{"foo", "bar10", 11, 0}, // Should return biggest version.
},
},
}
for _, ti := range tt {
t.Run(ti.name, func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
test(t, ti, db)
})
})
}
}
func TestKeyVersions(t *testing.T) {
inMemoryOpt := DefaultOptions("").
WithSyncWrites(false).
WithInMemory(true)
t.Run("disk", func(t *testing.T) {
t.Run("small table", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
l0 := make([]keyValVersion, 0)
for i := 0; i < 10; i++ {
l0 = append(l0, keyValVersion{fmt.Sprintf("%05d", i), "foo", 1, 0})
}
createAndOpen(db, l0, 0)
require.Equal(t, 2, len(db.Ranges(nil, 10000)))
})
})
t.Run("medium table", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
l0 := make([]keyValVersion, 0)
for i := 0; i < 1000; i++ {
l0 = append(l0, keyValVersion{fmt.Sprintf("%05d", i), "foo", 1, 0})
}
createAndOpen(db, l0, 0)
require.Equal(t, 8, len(db.Ranges(nil, 10000)))
})
})
t.Run("large table", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
l0 := make([]keyValVersion, 0)
for i := 0; i < 10000; i++ {
l0 = append(l0, keyValVersion{fmt.Sprintf("%05d", i), "foo", 1, 0})
}
createAndOpen(db, l0, 0)
require.Equal(t, 62, len(db.Ranges(nil, 10000)))
})
})
t.Run("prefix", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
l0 := make([]keyValVersion, 0)
for i := 0; i < 1000; i++ {
l0 = append(l0, keyValVersion{fmt.Sprintf("%05d", i), "foo", 1, 0})
}
createAndOpen(db, l0, 0)
require.Equal(t, 1, len(db.Ranges([]byte("a"), 10000)))
})
})
})
t.Run("in-memory", func(t *testing.T) {
t.Run("small table", func(t *testing.T) {
runBadgerTest(t, &inMemoryOpt, func(t *testing.T, db *DB) {
writer := db.newWriteBatch(false)
for i := 0; i < 10; i++ {
require.NoError(t, writer.Set([]byte(fmt.Sprintf("%05d", i)), []byte("foo")))
}
require.NoError(t, writer.Flush())
require.Equal(t, 2, len(db.Ranges(nil, 10000)))
})
})
t.Run("large table", func(t *testing.T) {
runBadgerTest(t, &inMemoryOpt, func(t *testing.T, db *DB) {
writer := db.newWriteBatch(false)
for i := 0; i < 100000; i++ {
require.NoError(t, writer.Set([]byte(fmt.Sprintf("%05d", i)), []byte("foo")))
}
require.NoError(t, writer.Flush())
require.Equal(t, 11, len(db.Ranges(nil, 10000)))
})
})
t.Run("prefix", func(t *testing.T) {
runBadgerTest(t, &inMemoryOpt, func(t *testing.T, db *DB) {
writer := db.newWriteBatch(false)
for i := 0; i < 10000; i++ {
require.NoError(t, writer.Set([]byte(fmt.Sprintf("%05d", i)), []byte("foo")))
}
require.NoError(t, writer.Flush())
require.Equal(t, 1, len(db.Ranges([]byte("a"), 10000)))
})
})
})
}
func TestSameLevel(t *testing.T) {
opt := DefaultOptions("")
opt.NumCompactors = 0
opt.NumVersionsToKeep = math.MaxInt32
opt.managedTxns = true
opt.LmaxCompaction = true
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
l6 := []keyValVersion{
{"A", "bar", 4, bitDiscardEarlierVersions}, {"A", "bar", 3, 0},
{"A", "bar", 2, 0}, {"Afoo", "baz", 2, 0},
}
l61 := []keyValVersion{
{"B", "bar", 4, bitDiscardEarlierVersions}, {"B", "bar", 3, 0},
{"B", "bar", 2, 0}, {"Bfoo", "baz", 2, 0},
}
l62 := []keyValVersion{
{"C", "bar", 4, bitDiscardEarlierVersions}, {"C", "bar", 3, 0},
{"C", "bar", 2, 0}, {"Cfoo", "baz", 2, 0},
}
createAndOpen(db, l6, 6)
createAndOpen(db, l61, 6)
createAndOpen(db, l62, 6)
require.NoError(t, db.lc.validate())
getAllAndCheck(t, db, []keyValVersion{
{"A", "bar", 4, bitDiscardEarlierVersions}, {"A", "bar", 3, 0},
{"A", "bar", 2, 0}, {"Afoo", "baz", 2, 0},
{"B", "bar", 4, bitDiscardEarlierVersions}, {"B", "bar", 3, 0},
{"B", "bar", 2, 0}, {"Bfoo", "baz", 2, 0},
{"C", "bar", 4, bitDiscardEarlierVersions}, {"C", "bar", 3, 0},
{"C", "bar", 2, 0}, {"Cfoo", "baz", 2, 0},
})
cdef := compactDef{
thisLevel: db.lc.levels[6],
nextLevel: db.lc.levels[6],
top: []*table.Table{db.lc.levels[6].tables[0]},
bot: db.lc.levels[6].tables[1:],
t: db.lc.levelTargets(),
}
cdef.t.baseLevel = 1
// Set dicardTs to 3. foo2 and foo1 should be dropped.
db.SetDiscardTs(3)
require.NoError(t, db.lc.runCompactDef(-1, 6, cdef))
getAllAndCheck(t, db, []keyValVersion{
{"A", "bar", 4, bitDiscardEarlierVersions}, {"A", "bar", 3, 0},
{"A", "bar", 2, 0}, {"Afoo", "baz", 2, 0},
{"B", "bar", 4, bitDiscardEarlierVersions}, {"B", "bar", 3, 0},
{"B", "bar", 2, 0}, {"Bfoo", "baz", 2, 0},
{"C", "bar", 4, bitDiscardEarlierVersions}, {"C", "bar", 3, 0},
{"C", "bar", 2, 0}, {"Cfoo", "baz", 2, 0},
})
require.NoError(t, db.lc.validate())
// Set dicardTs to 7.
db.SetDiscardTs(7)
cdef = compactDef{
thisLevel: db.lc.levels[6],
nextLevel: db.lc.levels[6],
top: []*table.Table{db.lc.levels[6].tables[0]},
bot: db.lc.levels[6].tables[1:],
t: db.lc.levelTargets(),
}
cdef.t.baseLevel = 1
require.NoError(t, db.lc.runCompactDef(-1, 6, cdef))
getAllAndCheck(t, db, []keyValVersion{
{"A", "bar", 4, bitDiscardEarlierVersions}, {"Afoo", "baz", 2, 0},
{"B", "bar", 4, bitDiscardEarlierVersions}, {"Bfoo", "baz", 2, 0},
{"C", "bar", 4, bitDiscardEarlierVersions}, {"Cfoo", "baz", 2, 0}})
require.NoError(t, db.lc.validate())
})
}
func TestTableContainsPrefix(t *testing.T) {
opts := table.Options{
BlockSize: 4 * 1024,
BloomFalsePositive: 0.01,
}
buildTable := func(keys []string) *table.Table {
filename := fmt.Sprintf("%s%s%d.sst", os.TempDir(), string(os.PathSeparator), rand.Uint32())
b := table.NewTableBuilder(opts)
defer b.Close()
v := []byte("value")
sort.Slice(keys, func(i, j int) bool {
return keys[i] < keys[j]
})
for _, k := range keys {
b.Add(y.KeyWithTs([]byte(k), 1), y.ValueStruct{Value: v}, 0)
b.Add(y.KeyWithTs([]byte(k), 2), y.ValueStruct{Value: v}, 0)
}
tbl, err := table.CreateTable(filename, b)
require.NoError(t, err)
return tbl
}
tbl := buildTable([]string{"key1", "key3", "key31", "key32", "key4"})
defer func() { require.NoError(t, tbl.DecrRef()) }()
require.True(t, containsPrefix(tbl, []byte("key")))
require.True(t, containsPrefix(tbl, []byte("key1")))
require.True(t, containsPrefix(tbl, []byte("key3")))
require.True(t, containsPrefix(tbl, []byte("key32")))
require.True(t, containsPrefix(tbl, []byte("key4")))
require.False(t, containsPrefix(tbl, []byte("key0")))
require.False(t, containsPrefix(tbl, []byte("key2")))
require.False(t, containsPrefix(tbl, []byte("key323")))
require.False(t, containsPrefix(tbl, []byte("key5")))
}
// Test that if a compaction fails during fill tables process, its tables are cleaned up and we are able
// to do compaction on them again.
func TestFillTableCleanup(t *testing.T) {
opt := DefaultOptions("")
opt.managedTxns = true
// Stop normal compactions from happening. They can take up the entire space causing the test to fail.
opt.NumCompactors = 0
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
opts := table.Options{
BlockSize: 4 * 1024,
BloomFalsePositive: 0.01,
}
buildTable := func(prefix byte) *table.Table {
filename := table.NewFilename(db.lc.reserveFileID(), db.opt.Dir)
b := table.NewTableBuilder(opts)
defer b.Close()
key := make([]byte, 100)
val := make([]byte, 500)
rand.Read(val)
copy(key, []byte{prefix})
count := uint64(40000)
for i := count; i > 0; i-- {
var meta byte
if i == 0 {
meta = bitDiscardEarlierVersions
}
b.AddStaleKey(y.KeyWithTs(key, i), y.ValueStruct{Meta: meta, Value: val}, 0)
}
tbl, err := table.CreateTable(filename, b)
require.NoError(t, err)
return tbl
}
buildLevel := func(level int, num_tab int) {
lh := db.lc.levels[level]
for i := byte(1); i < byte(num_tab); i++ {
tab := buildTable(i)
require.NoError(t, db.manifest.addChanges([]*pb.ManifestChange{
newCreateChange(tab.ID(), level, 0, tab.CompressionType()),
}, db.opt))
tab.CreatedAt = time.Now().Add(-10 * time.Hour)
// Add table to the given level.
lh.addTable(tab)
}
require.NoError(t, db.lc.validate())
require.NotZero(t, lh.getTotalStaleSize())
}
level := 6
buildLevel(level-1, 2)
buildLevel(level, 2)
db.SetDiscardTs(1 << 30)
// Modify the target file size so that we can compact all tables at once.
tt := db.lc.levelTargets()
tt.fileSz[6] = 1 << 30
prio := compactionPriority{level: 6, t: tt}
cd := compactDef{
compactorId: 0,
p: prio,
t: prio.t,
thisLevel: db.lc.levels[level-1],
nextLevel: db.lc.levels[level],
}
// Fill tables passes first.
require.Equal(t, db.lc.fillTables(&cd), true)
// Make sure that running compaction again fails, as the tables are being compacted.
require.Equal(t, db.lc.fillTables(&cd), false)
// Reset, to remove compaction being happening
db.lc.cstatus.delete(cd)
// Test that compaction should be able to run again on these tables.
require.Equal(t, db.lc.fillTables(&cd), true)
})
}
func TestStaleDataCleanup(t *testing.T) {
opt := DefaultOptions("")
opt.managedTxns = true
opt.LmaxCompaction = true
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
opts := table.Options{
BlockSize: 4 * 1024,
BloomFalsePositive: 0.01,
}
buildStaleTable := func(prefix byte) *table.Table {
filename := table.NewFilename(db.lc.reserveFileID(), db.opt.Dir)
b := table.NewTableBuilder(opts)
defer b.Close()
key := make([]byte, 100)
val := make([]byte, 500)
rand.Read(val)
copy(key, []byte{prefix})
count := uint64(40000)
for i := count; i > 0; i-- {
var meta byte
if i == 0 {
meta = bitDiscardEarlierVersions
}
b.AddStaleKey(y.KeyWithTs(key, i), y.ValueStruct{Meta: meta, Value: val}, 0)
}
tbl, err := table.CreateTable(filename, b)
require.NoError(t, err)
return tbl
}
level := 6
lh := db.lc.levels[level]
for i := byte(1); i < 5; i++ {
tab := buildStaleTable(i)
require.NoError(t, db.manifest.addChanges([]*pb.ManifestChange{
newCreateChange(tab.ID(), level, 0, tab.CompressionType()),
}, db.opt))
tab.CreatedAt = time.Now().Add(-10 * time.Hour)
// Add table to the given level.
lh.addTable(tab)
}
require.NoError(t, db.lc.validate())
require.NotZero(t, lh.getTotalStaleSize())
db.SetDiscardTs(1 << 30)
// Modify the target file size so that we can compact all tables at once.
tt := db.lc.levelTargets()
tt.fileSz[6] = 1 << 30
prio := compactionPriority{level: 6, t: tt}
require.NoError(t, db.lc.doCompact(-1, prio))
require.Zero(t, lh.getTotalStaleSize())
})
}
================================================
FILE: logger.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"log"
"os"
)
// Logger is implemented by any logging system that is used for standard logs.
type Logger interface {
Errorf(string, ...interface{})
Warningf(string, ...interface{})
Infof(string, ...interface{})
Debugf(string, ...interface{})
}
// Errorf logs an ERROR log message to the logger specified in opts or to the
// global logger if no logger is specified in opts.
func (opt *Options) Errorf(format string, v ...interface{}) {
if opt.Logger == nil {
return
}
opt.Logger.Errorf(format, v...)
}
// Infof logs an INFO message to the logger specified in opts.
func (opt *Options) Infof(format string, v ...interface{}) {
if opt.Logger == nil {
return
}
opt.Logger.Infof(format, v...)
}
// Warningf logs a WARNING message to the logger specified in opts.
func (opt *Options) Warningf(format string, v ...interface{}) {
if opt.Logger == nil {
return
}
opt.Logger.Warningf(format, v...)
}
// Debugf logs a DEBUG message to the logger specified in opts.
func (opt *Options) Debugf(format string, v ...interface{}) {
if opt.Logger == nil {
return
}
opt.Logger.Debugf(format, v...)
}
type loggingLevel int
const (
DEBUG loggingLevel = iota
INFO
WARNING
ERROR
)
type defaultLog struct {
*log.Logger
level loggingLevel
}
func defaultLogger(level loggingLevel) *defaultLog {
return &defaultLog{Logger: log.New(os.Stderr, "badger ", log.LstdFlags), level: level}
}
func (l *defaultLog) Errorf(f string, v ...interface{}) {
if l.level <= ERROR {
l.Printf("ERROR: "+f, v...)
}
}
func (l *defaultLog) Warningf(f string, v ...interface{}) {
if l.level <= WARNING {
l.Printf("WARNING: "+f, v...)
}
}
func (l *defaultLog) Infof(f string, v ...interface{}) {
if l.level <= INFO {
l.Printf("INFO: "+f, v...)
}
}
func (l *defaultLog) Debugf(f string, v ...interface{}) {
if l.level <= DEBUG {
l.Printf("DEBUG: "+f, v...)
}
}
================================================
FILE: logger_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"fmt"
"testing"
"github.com/stretchr/testify/require"
)
type mockLogger struct {
output string
}
func (l *mockLogger) Errorf(f string, v ...interface{}) {
l.output = fmt.Sprintf("ERROR: "+f, v...)
}
func (l *mockLogger) Infof(f string, v ...interface{}) {
l.output = fmt.Sprintf("INFO: "+f, v...)
}
func (l *mockLogger) Warningf(f string, v ...interface{}) {
l.output = fmt.Sprintf("WARNING: "+f, v...)
}
func (l *mockLogger) Debugf(f string, v ...interface{}) {
l.output = fmt.Sprintf("DEBUG: "+f, v...)
}
// Test that the DB-specific log is used instead of the global log.
func TestDbLog(t *testing.T) {
l := &mockLogger{}
opt := Options{Logger: l}
opt.Errorf("test")
require.Equal(t, "ERROR: test", l.output)
opt.Infof("test")
require.Equal(t, "INFO: test", l.output)
opt.Warningf("test")
require.Equal(t, "WARNING: test", l.output)
}
// Test that the global logger is used when no logger is specified in Options.
func TestNoDbLog(t *testing.T) {
l := &mockLogger{}
opt := Options{}
opt.Logger = l
opt.Errorf("test")
require.Equal(t, "ERROR: test", l.output)
opt.Infof("test")
require.Equal(t, "INFO: test", l.output)
opt.Warningf("test")
require.Equal(t, "WARNING: test", l.output)
}
================================================
FILE: managed_db.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
// OpenManaged returns a new DB, which allows more control over setting
// transaction timestamps, aka managed mode.
//
// This is only useful for databases built on top of Badger (like Dgraph), and
// can be ignored by most users.
func OpenManaged(opts Options) (*DB, error) {
opts.managedTxns = true
return Open(opts)
}
// NewTransactionAt follows the same logic as DB.NewTransaction(), but uses the
// provided read timestamp.
//
// This is only useful for databases built on top of Badger (like Dgraph), and
// can be ignored by most users.
func (db *DB) NewTransactionAt(readTs uint64, update bool) *Txn {
if !db.opt.managedTxns {
panic("Cannot use NewTransactionAt with managedDB=false. Use NewTransaction instead.")
}
txn := db.newTransaction(update, true)
txn.readTs = readTs
return txn
}
// NewWriteBatchAt is similar to NewWriteBatch but it allows user to set the commit timestamp.
// NewWriteBatchAt is supposed to be used only in the managed mode.
func (db *DB) NewWriteBatchAt(commitTs uint64) *WriteBatch {
if !db.opt.managedTxns {
panic("cannot use NewWriteBatchAt with managedDB=false. Use NewWriteBatch instead")
}
wb := db.newWriteBatch(true)
wb.commitTs = commitTs
wb.txn.commitTs = commitTs
return wb
}
func (db *DB) NewManagedWriteBatch() *WriteBatch {
if !db.opt.managedTxns {
panic("cannot use NewManagedWriteBatch with managedDB=false. Use NewWriteBatch instead")
}
wb := db.newWriteBatch(true)
return wb
}
// CommitAt commits the transaction, following the same logic as Commit(), but
// at the given commit timestamp. This will panic if not used with managed transactions.
//
// This is only useful for databases built on top of Badger (like Dgraph), and
// can be ignored by most users.
func (txn *Txn) CommitAt(commitTs uint64, callback func(error)) error {
if !txn.db.opt.managedTxns {
panic("Cannot use CommitAt with managedDB=false. Use Commit instead.")
}
txn.commitTs = commitTs
if callback == nil {
return txn.Commit()
}
txn.CommitWith(callback)
return nil
}
// SetDiscardTs sets a timestamp at or below which, any invalid or deleted
// versions can be discarded from the LSM tree, and thence from the value log to
// reclaim disk space. Can only be used with managed transactions.
func (db *DB) SetDiscardTs(ts uint64) {
if !db.opt.managedTxns {
panic("Cannot use SetDiscardTs with managedDB=false.")
}
db.orc.setDiscardTs(ts)
}
================================================
FILE: managed_db_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"fmt"
"math"
"math/rand"
"os"
"runtime"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2/z"
)
func val(large bool) []byte {
var buf []byte
if large {
buf = make([]byte, 8192)
} else {
buf = make([]byte, 16)
}
rand.Read(buf)
return buf
}
func numKeys(db *DB) int {
var count int
err := db.View(func(txn *Txn) error {
itr := txn.NewIterator(DefaultIteratorOptions)
defer itr.Close()
for itr.Rewind(); itr.Valid(); itr.Next() {
count++
}
return nil
})
y.Check(err)
return count
}
func numKeysManaged(db *DB, readTs uint64) int {
txn := db.NewTransactionAt(readTs, false)
defer txn.Discard()
itr := txn.NewIterator(DefaultIteratorOptions)
defer itr.Close()
var count int
for itr.Rewind(); itr.Valid(); itr.Next() {
count++
}
return count
}
func TestDropAllManaged(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opts := getTestOptions(dir)
opts.managedTxns = true
opts.ValueLogFileSize = 5 << 20
db, err := Open(opts)
require.NoError(t, err)
N := uint64(10000)
populate := func(db *DB, start uint64) {
var wg sync.WaitGroup
for i := start; i < start+N; i++ {
wg.Add(1)
txn := db.NewTransactionAt(math.MaxUint64, true)
require.NoError(t, txn.SetEntry(NewEntry([]byte(key("key", int(i))), val(true))))
require.NoError(t, txn.CommitAt(i, func(err error) {
require.NoError(t, err)
wg.Done()
}))
}
wg.Wait()
}
populate(db, N)
require.Equal(t, int(N), numKeysManaged(db, math.MaxUint64))
require.NoError(t, db.DropAll())
require.NoError(t, db.DropAll()) // Just call it twice, for fun.
require.Equal(t, 0, numKeysManaged(db, math.MaxUint64))
// Check that we can still write to db, and using lower timestamps.
populate(db, 1)
require.Equal(t, int(N), numKeysManaged(db, math.MaxUint64))
require.NoError(t, db.Close())
// Ensure that value log is correctly replayed, that we are preserving badgerHead.
opts.managedTxns = true
db2, err := Open(opts)
require.NoError(t, err)
require.Equal(t, int(N), numKeysManaged(db2, math.MaxUint64))
require.NoError(t, db2.Close())
}
func TestDropAll(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opts := getTestOptions(dir)
opts.ValueLogFileSize = 5 << 20
db, err := Open(opts)
require.NoError(t, err)
N := uint64(10000)
populate := func(db *DB) {
writer := db.NewWriteBatch()
for i := uint64(0); i < N; i++ {
require.NoError(t, writer.Set([]byte(key("key", int(i))), val(true)))
}
require.NoError(t, writer.Flush())
}
populate(db)
require.Equal(t, int(N), numKeys(db))
require.NoError(t, db.DropAll())
require.Equal(t, 0, numKeys(db))
// Check that we can still write to mdb, and using lower timestamps.
populate(db)
require.Equal(t, int(N), numKeys(db))
require.NoError(t, db.Close())
// Ensure that value log is correctly replayed.
db2, err := Open(opts)
require.NoError(t, err)
require.Equal(t, int(N), numKeys(db2))
require.NoError(t, db2.Close())
}
func TestDropAllTwice(t *testing.T) {
test := func(t *testing.T, opts Options) {
db, err := Open(opts)
require.NoError(t, err)
defer func() {
require.NoError(t, db.Close())
}()
N := uint64(10000)
populate := func(db *DB) {
writer := db.NewWriteBatch()
for i := uint64(0); i < N; i++ {
require.NoError(t, writer.Set([]byte(key("key", int(i))), val(false)))
}
require.NoError(t, writer.Flush())
}
populate(db)
require.Equal(t, int(N), numKeys(db))
require.NoError(t, db.DropAll())
require.Equal(t, 0, numKeys(db))
// Call DropAll again.
require.NoError(t, db.DropAll())
require.NoError(t, db.Close())
}
t.Run("disk mode", func(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opts := getTestOptions(dir)
opts.ValueLogFileSize = 5 << 20
test(t, opts)
})
t.Run("InMemory mode", func(t *testing.T) {
opts := getTestOptions("")
opts.InMemory = true
test(t, opts)
})
}
func TestDropAllWithPendingTxn(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opts := getTestOptions(dir)
opts.ValueLogFileSize = 5 << 20
db, err := Open(opts)
require.NoError(t, err)
defer func() {
require.NoError(t, db.Close())
}()
N := uint64(10000)
populate := func(db *DB) {
writer := db.NewWriteBatch()
for i := uint64(0); i < N; i++ {
require.NoError(t, writer.Set([]byte(key("key", int(i))), val(true)))
}
require.NoError(t, writer.Flush())
}
populate(db)
require.Equal(t, int(N), numKeys(db))
txn := db.NewTransaction(true)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
itr := txn.NewIterator(DefaultIteratorOptions)
defer itr.Close()
var keys []string
for {
var count int
for itr.Rewind(); itr.Valid(); itr.Next() {
count++
item := itr.Item()
keys = append(keys, string(item.KeyCopy(nil)))
_, err := item.ValueCopy(nil)
if err != nil {
t.Logf("Got error during value copy: %v", err)
return
}
}
t.Logf("Got number of keys: %d\n", count)
for _, key := range keys {
item, err := txn.Get([]byte(key))
if err != nil {
t.Logf("Got error during key lookup: %v", err)
return
}
if _, err := item.ValueCopy(nil); err != nil {
t.Logf("Got error during second value copy: %v", err)
return
}
}
}
}()
// Do not cancel txn.
wg.Add(1)
go func() {
defer wg.Done()
time.Sleep(2 * time.Second)
require.NoError(t, db.DropAll())
}()
wg.Wait()
}
func TestDropReadOnly(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opts := getTestOptions(dir)
opts.ValueLogFileSize = 5 << 20
db, err := Open(opts)
require.NoError(t, err)
N := uint64(1000)
populate := func(db *DB) {
writer := db.NewWriteBatch()
for i := uint64(0); i < N; i++ {
require.NoError(t, writer.Set([]byte(key("key", int(i))), val(true)))
}
require.NoError(t, writer.Flush())
}
populate(db)
require.Equal(t, int(N), numKeys(db))
require.NoError(t, db.Close())
opts.ReadOnly = true
db2, err := Open(opts)
// acquireDirectoryLock returns ErrWindowsNotSupported on Windows. It can be ignored safely.
if runtime.GOOS == "windows" {
require.Equal(t, err, ErrWindowsNotSupported)
} else {
require.NoError(t, err)
require.Panics(t, func() { _ = db2.DropAll() })
require.NoError(t, db2.Close())
}
}
func TestWriteAfterClose(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opts := getTestOptions(dir)
opts.ValueLogFileSize = 5 << 20
db, err := Open(opts)
require.NoError(t, err)
N := uint64(1000)
populate := func(db *DB) {
writer := db.NewWriteBatch()
for i := uint64(0); i < N; i++ {
require.NoError(t, writer.Set([]byte(key("key", int(i))), val(true)))
}
require.NoError(t, writer.Flush())
}
populate(db)
require.Equal(t, int(N), numKeys(db))
require.NoError(t, db.Close())
err = db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry([]byte("a"), []byte("b")))
})
require.Equal(t, ErrDBClosed, err)
}
func TestDropAllRace(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opts := getTestOptions(dir)
opts.managedTxns = true
db, err := Open(opts)
require.NoError(t, err)
N := 10000
// Start a goroutine to keep trying to write to DB while DropAll happens.
closer := z.NewCloser(1)
go func() {
defer closer.Done()
ticker := time.NewTicker(time.Millisecond)
defer ticker.Stop()
i := N + 1 // Writes would happen above N.
var errors atomic.Int32
for {
select {
case <-ticker.C:
i++
txn := db.NewTransactionAt(math.MaxUint64, true)
require.NoError(t, txn.SetEntry(NewEntry([]byte(key("key", i)), val(false))))
if err := txn.CommitAt(uint64(i), func(err error) {
if err != nil {
errors.Add(1)
}
}); err != nil {
errors.Add(1)
}
case <-closer.HasBeenClosed():
// The following causes a data race.
// t.Logf("i: %d. Number of (expected) write errors: %d.\n", i, errors)
return
}
}
}()
var wg sync.WaitGroup
for i := 1; i <= N; i++ {
wg.Add(1)
txn := db.NewTransactionAt(math.MaxUint64, true)
require.NoError(t, txn.SetEntry(NewEntry([]byte(key("key", i)), val(false))))
require.NoError(t, txn.CommitAt(uint64(i), func(err error) {
require.NoError(t, err)
wg.Done()
}))
}
wg.Wait()
before := numKeysManaged(db, math.MaxUint64)
require.True(t, before > N)
require.NoError(t, db.DropAll())
closer.SignalAndWait()
after := numKeysManaged(db, math.MaxUint64)
t.Logf("Before: %d. After dropall: %d\n", before, after)
require.True(t, after < before)
db.Close()
}
func TestDropPrefix(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opts := getTestOptions(dir)
opts.ValueLogFileSize = 5 << 20
db, err := Open(opts)
require.NoError(t, err)
N := uint64(10000)
populate := func(db *DB) {
writer := db.NewWriteBatch()
for i := uint64(0); i < N; i++ {
require.NoError(t, writer.Set([]byte(key("key", int(i))), val(true)))
}
require.NoError(t, writer.Flush())
}
populate(db)
require.Equal(t, int(N), numKeys(db))
require.NoError(t, db.DropPrefix([]byte("key000")))
require.Equal(t, int(N)-10, numKeys(db))
require.NoError(t, db.DropPrefix([]byte("key00")))
require.Equal(t, int(N)-100, numKeys(db))
expected := int(N)
for i := 0; i < 10; i++ {
require.NoError(t, db.DropPrefix([]byte(fmt.Sprintf("key%d", i))))
expected -= 1000
require.Equal(t, expected, numKeys(db))
}
require.NoError(t, db.DropPrefix([]byte("key1")))
require.Equal(t, 0, numKeys(db))
require.NoError(t, db.DropPrefix([]byte("key")))
require.Equal(t, 0, numKeys(db))
// Check that we can still write to mdb, and using lower timestamps.
populate(db)
require.Equal(t, int(N), numKeys(db))
require.NoError(t, db.DropPrefix([]byte("key")))
require.Equal(t, 0, numKeys(db))
require.NoError(t, db.Close())
// Ensure that value log is correctly replayed.
db2, err := Open(opts)
require.NoError(t, err)
require.Equal(t, 0, numKeys(db2))
require.NoError(t, db2.Close())
}
func TestDropPrefixWithPendingTxn(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opts := getTestOptions(dir)
opts.ValueLogFileSize = 5 << 20
db, err := Open(opts)
require.NoError(t, err)
defer func() {
require.NoError(t, db.Close())
}()
N := uint64(10000)
populate := func(db *DB) {
writer := db.NewWriteBatch()
for i := uint64(0); i < N; i++ {
require.NoError(t, writer.Set([]byte(key("key", int(i))), val(true)))
}
require.NoError(t, writer.Flush())
}
populate(db)
require.Equal(t, int(N), numKeys(db))
txn := db.NewTransaction(true)
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
itr := txn.NewIterator(DefaultIteratorOptions)
defer itr.Close()
var keys []string
for {
var count int
for itr.Rewind(); itr.Valid(); itr.Next() {
count++
item := itr.Item()
keys = append(keys, string(item.KeyCopy(nil)))
_, err := item.ValueCopy(nil)
if err != nil {
t.Logf("Got error during value copy: %v", err)
return
}
}
t.Logf("Got number of keys: %d\n", count)
for _, key := range keys {
item, err := txn.Get([]byte(key))
if err != nil {
t.Logf("Got error during key lookup: %v", err)
return
}
if _, err := item.ValueCopy(nil); err != nil {
t.Logf("Got error during second value copy: %v", err)
return
}
}
}
}()
// Do not cancel txn.
go func() {
defer wg.Done()
time.Sleep(2 * time.Second)
require.NoError(t, db.DropPrefix([]byte("key0")))
require.NoError(t, db.DropPrefix([]byte("key00")))
require.NoError(t, db.DropPrefix([]byte("key")))
}()
wg.Wait()
}
func TestDropPrefixReadOnly(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opts := getTestOptions(dir)
opts.ValueLogFileSize = 5 << 20
db, err := Open(opts)
require.NoError(t, err)
N := uint64(1000)
populate := func(db *DB) {
writer := db.NewWriteBatch()
for i := uint64(0); i < N; i++ {
require.NoError(t, writer.Set([]byte(key("key", int(i))), val(true)))
}
require.NoError(t, writer.Flush())
}
populate(db)
require.Equal(t, int(N), numKeys(db))
require.NoError(t, db.Close())
opts.ReadOnly = true
db2, err := Open(opts)
// acquireDirectoryLock returns ErrWindowsNotSupported on Windows. It can be ignored safely.
if runtime.GOOS == "windows" {
require.Equal(t, err, ErrWindowsNotSupported)
} else {
require.NoError(t, err)
require.Panics(t, func() { _ = db2.DropPrefix([]byte("key0")) })
require.NoError(t, db2.Close())
}
}
func TestDropPrefixRace(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opts := getTestOptions(dir)
opts.managedTxns = true
db, err := Open(opts)
require.NoError(t, err)
N := 10000
// Start a goroutine to keep trying to write to DB while DropPrefix happens.
closer := z.NewCloser(1)
go func() {
defer closer.Done()
ticker := time.NewTicker(time.Millisecond)
defer ticker.Stop()
i := N + 1 // Writes would happen above N.
var errors atomic.Int32
for {
select {
case <-ticker.C:
i++
txn := db.NewTransactionAt(math.MaxUint64, true)
require.NoError(t, txn.SetEntry(NewEntry([]byte(key("key", i)), val(false))))
if err := txn.CommitAt(uint64(i), func(err error) {
if err != nil {
errors.Add(1)
}
}); err != nil {
errors.Add(1)
}
case <-closer.HasBeenClosed():
// The following causes a data race.
// t.Logf("i: %d. Number of (expected) write errors: %d.\n", i, errors)
return
}
}
}()
var wg sync.WaitGroup
for i := 1; i <= N; i++ {
wg.Add(1)
txn := db.NewTransactionAt(math.MaxUint64, true)
require.NoError(t, txn.SetEntry(NewEntry([]byte(key("key", i)), val(false))))
require.NoError(t, txn.CommitAt(uint64(i), func(err error) {
require.NoError(t, err)
wg.Done()
}))
}
wg.Wait()
before := numKeysManaged(db, math.MaxUint64)
require.True(t, before > N)
require.NoError(t, db.DropPrefix([]byte("key00")))
require.NoError(t, db.DropPrefix([]byte("key1")))
require.NoError(t, db.DropPrefix([]byte("key")))
closer.SignalAndWait()
after := numKeysManaged(db, math.MaxUint64)
t.Logf("Before: %d. After dropprefix: %d\n", before, after)
require.True(t, after < before)
require.NoError(t, db.Close())
}
func TestWriteBatchManagedMode(t *testing.T) {
key := func(i int) []byte {
return []byte(fmt.Sprintf("%10d", i))
}
val := func(i int) []byte {
return []byte(fmt.Sprintf("%128d", i))
}
opt := DefaultOptions("")
opt.managedTxns = true
opt.BaseTableSize = 1 << 20 // This would create multiple transactions in write batch.
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
wb := db.NewWriteBatchAt(1)
defer wb.Cancel()
N, M := 50000, 1000
start := time.Now()
for i := 0; i < N; i++ {
require.NoError(t, wb.Set(key(i), val(i)))
}
for i := 0; i < M; i++ {
require.NoError(t, wb.Delete(key(i)))
}
require.NoError(t, wb.Flush())
t.Logf("Time taken for %d writes (w/ test options): %s\n", N+M, time.Since(start))
err := db.View(func(txn *Txn) error {
itr := txn.NewIterator(DefaultIteratorOptions)
defer itr.Close()
i := M
for itr.Rewind(); itr.Valid(); itr.Next() {
item := itr.Item()
require.Equal(t, string(key(i)), string(item.Key()))
require.Equal(t, item.Version(), uint64(1))
valcopy, err := item.ValueCopy(nil)
require.NoError(t, err)
require.Equal(t, val(i), valcopy)
i++
}
require.Equal(t, N, i)
return nil
})
require.NoError(t, err)
})
}
func TestWriteBatchManaged(t *testing.T) {
key := func(i int) []byte {
return []byte(fmt.Sprintf("%10d", i))
}
val := func(i int) []byte {
return []byte(fmt.Sprintf("%128d", i))
}
opt := DefaultOptions("")
opt.managedTxns = true
opt.BaseTableSize = 1 << 15 // This would create multiple transactions in write batch.
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
wb := db.NewManagedWriteBatch()
defer wb.Cancel()
N, M := 50000, 1000
start := time.Now()
for i := 0; i < N; i++ {
require.NoError(t, wb.SetEntryAt(&Entry{Key: key(i), Value: val(i)}, 1))
}
for i := 0; i < M; i++ {
require.NoError(t, wb.DeleteAt(key(i), 2))
}
require.NoError(t, wb.Flush())
t.Logf("Time taken for %d writes (w/ test options): %s\n", N+M, time.Since(start))
err := db.View(func(txn *Txn) error {
itr := txn.NewIterator(DefaultIteratorOptions)
defer itr.Close()
i := M
for itr.Rewind(); itr.Valid(); itr.Next() {
item := itr.Item()
require.Equal(t, string(key(i)), string(item.Key()))
require.Equal(t, item.Version(), uint64(1))
valcopy, err := item.ValueCopy(nil)
require.NoError(t, err)
require.Equal(t, val(i), valcopy)
i++
}
require.Equal(t, N, i)
return nil
})
require.NoError(t, err)
})
}
func TestWriteBatchDuplicate(t *testing.T) {
N := 10
k := []byte("key")
v := []byte("val")
readVerify := func(t *testing.T, db *DB, n int, versions []int) {
err := db.View(func(txn *Txn) error {
iopt := DefaultIteratorOptions
iopt.AllVersions = true
itr := txn.NewIterator(iopt)
defer itr.Close()
i := 0
for itr.Rewind(); itr.Valid(); itr.Next() {
item := itr.Item()
require.Equal(t, k, item.Key())
require.Equal(t, uint64(versions[i]), item.Version())
err := item.Value(func(val []byte) error {
require.Equal(t, v, val)
return nil
})
require.NoError(t, err)
i++
}
require.Equal(t, n, i)
return nil
})
require.NoError(t, err)
}
t.Run("writebatch", func(t *testing.T) {
opt := DefaultOptions("")
opt.BaseTableSize = 1 << 15 // This would create multiple transactions in write batch.
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
wb := db.NewWriteBatch()
defer wb.Cancel()
for i := uint64(0); i < uint64(N); i++ {
// Multiple versions of the same key.
require.NoError(t, wb.SetEntry(&Entry{Key: k, Value: v}))
}
require.NoError(t, wb.Flush())
readVerify(t, db, 1, []int{1})
})
})
t.Run("writebatch at", func(t *testing.T) {
opt := DefaultOptions("")
opt.BaseTableSize = 1 << 15 // This would create multiple transactions in write batch.
opt.managedTxns = true
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
wb := db.NewWriteBatchAt(10)
defer wb.Cancel()
for i := uint64(0); i < uint64(N); i++ {
// Multiple versions of the same key.
require.NoError(t, wb.SetEntry(&Entry{Key: k, Value: v}))
}
require.NoError(t, wb.Flush())
readVerify(t, db, 1, []int{10})
})
})
t.Run("managed writebatch", func(t *testing.T) {
opt := DefaultOptions("")
opt.managedTxns = true
opt.BaseTableSize = 1 << 15 // This would create multiple transactions in write batch.
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
wb := db.NewManagedWriteBatch()
defer wb.Cancel()
for i := uint64(1); i <= uint64(N); i++ {
// Multiple versions of the same key.
require.NoError(t, wb.SetEntryAt(&Entry{Key: k, Value: v}, i))
}
require.NoError(t, wb.Flush())
readVerify(t, db, N, []int{10, 9, 8, 7, 6, 5, 4, 3, 2, 1})
})
})
}
func TestZeroDiscardStats(t *testing.T) {
N := uint64(10000)
populate := func(t *testing.T, db *DB) {
writer := db.NewWriteBatch()
for i := uint64(0); i < N; i++ {
require.NoError(t, writer.Set([]byte(key("key", int(i))), val(true)))
}
require.NoError(t, writer.Flush())
}
t.Run("after rewrite", func(t *testing.T) {
opts := getTestOptions("")
opts.ValueLogFileSize = 5 << 20
opts.ValueThreshold = 1 << 10
opts.MemTableSize = 1 << 15
runBadgerTest(t, &opts, func(t *testing.T, db *DB) {
populate(t, db)
require.Equal(t, int(N), numKeys(db))
fids := db.vlog.sortedFids()
for _, fid := range fids {
db.vlog.discardStats.Update(fid, 1)
}
// Ensure we have some valid fids.
require.True(t, len(fids) > 2)
fid := fids[0]
require.NoError(t, db.vlog.rewrite(db.vlog.filesMap[fid]))
// All data should still be present.
require.Equal(t, int(N), numKeys(db))
db.vlog.discardStats.Iterate(func(id, val uint64) {
// Vlog with id=fid has been re-written, it's discard stats should be zero.
if uint32(id) == fid {
require.Zero(t, val)
}
})
})
})
t.Run("after dropall", func(t *testing.T) {
opts := getTestOptions("")
opts.ValueLogFileSize = 5 << 20
runBadgerTest(t, &opts, func(t *testing.T, db *DB) {
populate(t, db)
require.Equal(t, int(N), numKeys(db))
// Fill discard stats. Normally these are filled by compaction.
fids := db.vlog.sortedFids()
for _, fid := range fids {
db.vlog.discardStats.Update(fid, 1)
}
db.vlog.discardStats.Iterate(func(id, val uint64) { require.NotZero(t, val) })
require.NoError(t, db.DropAll())
require.Equal(t, 0, numKeys(db))
// We've deleted everything. DS should be zero.
db.vlog.discardStats.Iterate(func(id, val uint64) { require.Zero(t, val) })
})
})
}
================================================
FILE: manifest.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"bufio"
"bytes"
"encoding/binary"
"errors"
"fmt"
"hash/crc32"
"io"
"math"
"os"
"path/filepath"
"sync"
"google.golang.org/protobuf/proto"
"github.com/dgraph-io/badger/v4/options"
"github.com/dgraph-io/badger/v4/pb"
"github.com/dgraph-io/badger/v4/y"
)
// Manifest represents the contents of the MANIFEST file in a Badger store.
//
// The MANIFEST file describes the startup state of the db -- all LSM files and what level they're
// at.
//
// It consists of a sequence of ManifestChangeSet objects. Each of these is treated atomically,
// and contains a sequence of ManifestChange's (file creations/deletions) which we use to
// reconstruct the manifest at startup.
type Manifest struct {
Levels []levelManifest
Tables map[uint64]TableManifest
// Contains total number of creation and deletion changes in the manifest -- used to compute
// whether it'd be useful to rewrite the manifest.
Creations int
Deletions int
}
func createManifest() Manifest {
levels := make([]levelManifest, 0)
return Manifest{
Levels: levels,
Tables: make(map[uint64]TableManifest),
}
}
// levelManifest contains information about LSM tree levels
// in the MANIFEST file.
type levelManifest struct {
Tables map[uint64]struct{} // Set of table id's
}
// TableManifest contains information about a specific table
// in the LSM tree.
type TableManifest struct {
Level uint8
KeyID uint64
Compression options.CompressionType
}
// manifestFile holds the file pointer (and other info) about the manifest file, which is a log
// file we append to.
type manifestFile struct {
fp *os.File
directory string
// The external magic number used by the application running badger.
externalMagic uint16
// We make this configurable so that unit tests can hit rewrite() code quickly
deletionsRewriteThreshold int
// Guards appends, which includes access to the manifest field.
appendLock sync.Mutex
// Used to track the current state of the manifest, used when rewriting.
manifest Manifest
// Used to indicate if badger was opened in InMemory mode.
inMemory bool
}
const (
// ManifestFilename is the filename for the manifest file.
ManifestFilename = "MANIFEST"
manifestRewriteFilename = "MANIFEST-REWRITE"
manifestDeletionsRewriteThreshold = 10000
manifestDeletionsRatio = 10
)
// asChanges returns a sequence of changes that could be used to recreate the Manifest in its
// present state.
func (m *Manifest) asChanges() []*pb.ManifestChange {
changes := make([]*pb.ManifestChange, 0, len(m.Tables))
for id, tm := range m.Tables {
changes = append(changes, newCreateChange(id, int(tm.Level), tm.KeyID, tm.Compression))
}
return changes
}
func (m *Manifest) clone(opt Options) Manifest {
changeSet := pb.ManifestChangeSet{Changes: m.asChanges()}
ret := createManifest()
y.Check(applyChangeSet(&ret, &changeSet, opt))
return ret
}
// openOrCreateManifestFile opens a Badger manifest file if it exists, or creates one if
// doesn’t exists.
func openOrCreateManifestFile(opt Options) (
ret *manifestFile, result Manifest, err error) {
if opt.InMemory {
return &manifestFile{inMemory: true}, Manifest{}, nil
}
return helpOpenOrCreateManifestFile(opt.Dir, opt.ReadOnly, opt.ExternalMagicVersion,
manifestDeletionsRewriteThreshold, opt)
}
func helpOpenOrCreateManifestFile(dir string, readOnly bool, extMagic uint16,
deletionsThreshold int, opt Options) (*manifestFile, Manifest, error) {
path := filepath.Join(dir, ManifestFilename)
var flags y.Flags
if readOnly {
flags |= y.ReadOnly
}
fp, err := y.OpenExistingFile(path, flags) // We explicitly sync in addChanges, outside the lock.
if err != nil {
if !os.IsNotExist(err) {
return nil, Manifest{}, err
}
if readOnly {
return nil, Manifest{}, fmt.Errorf("no manifest found, required for read-only db")
}
m := createManifest()
fp, netCreations, err := helpRewrite(dir, &m, extMagic)
if err != nil {
return nil, Manifest{}, err
}
y.AssertTrue(netCreations == 0)
mf := &manifestFile{
fp: fp,
directory: dir,
externalMagic: extMagic,
manifest: m.clone(opt),
deletionsRewriteThreshold: deletionsThreshold,
}
return mf, m, nil
}
manifest, truncOffset, err := ReplayManifestFile(fp, extMagic, opt)
if err != nil {
_ = fp.Close()
return nil, Manifest{}, err
}
if !readOnly {
// Truncate file so we don't have a half-written entry at the end.
if err := fp.Truncate(truncOffset); err != nil {
_ = fp.Close()
return nil, Manifest{}, err
}
}
if _, err = fp.Seek(0, io.SeekEnd); err != nil {
_ = fp.Close()
return nil, Manifest{}, err
}
mf := &manifestFile{
fp: fp,
directory: dir,
externalMagic: extMagic,
manifest: manifest.clone(opt),
deletionsRewriteThreshold: deletionsThreshold,
}
return mf, manifest, nil
}
func (mf *manifestFile) close() error {
if mf.inMemory {
return nil
}
return mf.fp.Close()
}
// addChanges writes a batch of changes, atomically, to the file. By "atomically" that means when
// we replay the MANIFEST file, we'll either replay all the changes or none of them. (The truth of
// this depends on the filesystem -- some might append garbage data if a system crash happens at
// the wrong time.)
func (mf *manifestFile) addChanges(changesParam []*pb.ManifestChange, opt Options) error {
if mf.inMemory {
return nil
}
changes := pb.ManifestChangeSet{Changes: changesParam}
buf, err := proto.Marshal(&changes)
if err != nil {
return err
}
// Maybe we could use O_APPEND instead (on certain file systems)
mf.appendLock.Lock()
defer mf.appendLock.Unlock()
if err := applyChangeSet(&mf.manifest, &changes, opt); err != nil {
return err
}
// Rewrite manifest if it'd shrink by 1/10 and it's big enough to care
if mf.manifest.Deletions > mf.deletionsRewriteThreshold &&
mf.manifest.Deletions > manifestDeletionsRatio*(mf.manifest.Creations-mf.manifest.Deletions) {
if err := mf.rewrite(); err != nil {
return err
}
} else {
var lenCrcBuf [8]byte
binary.BigEndian.PutUint32(lenCrcBuf[0:4], uint32(len(buf)))
binary.BigEndian.PutUint32(lenCrcBuf[4:8], crc32.Checksum(buf, y.CastagnoliCrcTable))
buf = append(lenCrcBuf[:], buf...)
if _, err := mf.fp.Write(buf); err != nil {
return err
}
}
return syncFunc(mf.fp)
}
// this function is saved here to allow injection of fake filesystem latency at test time.
var syncFunc = func(f *os.File) error { return f.Sync() }
// Has to be 4 bytes. The value can never change, ever, anyway.
var magicText = [4]byte{'B', 'd', 'g', 'r'}
// The magic version number. It is allocated 2 bytes, so it's value must be <= math.MaxUint16
const badgerMagicVersion = 8
func helpRewrite(dir string, m *Manifest, extMagic uint16) (*os.File, int, error) {
rewritePath := filepath.Join(dir, manifestRewriteFilename)
// We explicitly sync.
fp, err := y.OpenTruncFile(rewritePath, false)
if err != nil {
return nil, 0, err
}
// magic bytes are structured as
// +---------------------+-------------------------+-----------------------+
// | magicText (4 bytes) | externalMagic (2 bytes) | badgerMagic (2 bytes) |
// +---------------------+-------------------------+-----------------------+
y.AssertTrue(badgerMagicVersion <= math.MaxUint16)
buf := make([]byte, 8)
copy(buf[0:4], magicText[:])
binary.BigEndian.PutUint16(buf[4:6], extMagic)
binary.BigEndian.PutUint16(buf[6:8], badgerMagicVersion)
netCreations := len(m.Tables)
changes := m.asChanges()
set := pb.ManifestChangeSet{Changes: changes}
changeBuf, err := proto.Marshal(&set)
if err != nil {
fp.Close()
return nil, 0, err
}
var lenCrcBuf [8]byte
binary.BigEndian.PutUint32(lenCrcBuf[0:4], uint32(len(changeBuf)))
binary.BigEndian.PutUint32(lenCrcBuf[4:8], crc32.Checksum(changeBuf, y.CastagnoliCrcTable))
buf = append(buf, lenCrcBuf[:]...)
buf = append(buf, changeBuf...)
if _, err := fp.Write(buf); err != nil {
fp.Close()
return nil, 0, err
}
if err := fp.Sync(); err != nil {
fp.Close()
return nil, 0, err
}
// In Windows the files should be closed before doing a Rename.
if err = fp.Close(); err != nil {
return nil, 0, err
}
manifestPath := filepath.Join(dir, ManifestFilename)
if err := os.Rename(rewritePath, manifestPath); err != nil {
return nil, 0, err
}
fp, err = y.OpenExistingFile(manifestPath, 0)
if err != nil {
return nil, 0, err
}
if _, err := fp.Seek(0, io.SeekEnd); err != nil {
fp.Close()
return nil, 0, err
}
if err := syncDir(dir); err != nil {
fp.Close()
return nil, 0, err
}
return fp, netCreations, nil
}
// Must be called while appendLock is held.
func (mf *manifestFile) rewrite() error {
// In Windows the files should be closed before doing a Rename.
if err := mf.fp.Close(); err != nil {
return err
}
fp, netCreations, err := helpRewrite(mf.directory, &mf.manifest, mf.externalMagic)
if err != nil {
return err
}
mf.fp = fp
mf.manifest.Creations = netCreations
mf.manifest.Deletions = 0
return nil
}
type countingReader struct {
wrapped *bufio.Reader
count int64
}
func (r *countingReader) Read(p []byte) (n int, err error) {
n, err = r.wrapped.Read(p)
r.count += int64(n)
return
}
func (r *countingReader) ReadByte() (b byte, err error) {
b, err = r.wrapped.ReadByte()
if err == nil {
r.count++
}
return
}
var (
errBadMagic = errors.New("manifest has bad magic")
errBadChecksum = errors.New("manifest has checksum mismatch")
)
// ReplayManifestFile reads the manifest file and constructs two manifest objects. (We need one
// immutable copy and one mutable copy of the manifest. Easiest way is to construct two of them.)
// Also, returns the last offset after a completely read manifest entry -- the file must be
// truncated at that point before further appends are made (if there is a partial entry after
// that). In normal conditions, truncOffset is the file size.
func ReplayManifestFile(fp *os.File, extMagic uint16, opt Options) (Manifest, int64, error) {
r := countingReader{wrapped: bufio.NewReader(fp)}
var magicBuf [8]byte
if _, err := io.ReadFull(&r, magicBuf[:]); err != nil {
return Manifest{}, 0, errBadMagic
}
if !bytes.Equal(magicBuf[0:4], magicText[:]) {
return Manifest{}, 0, errBadMagic
}
extVersion := y.BytesToU16(magicBuf[4:6])
version := y.BytesToU16(magicBuf[6:8])
if version != badgerMagicVersion {
return Manifest{}, 0,
//nolint:lll
fmt.Errorf("manifest has unsupported version: %d (we support %d).\n"+
"Please see https://github.com/dgraph-io/badger/blob/main/docs/troubleshooting.md#i-see-manifest-has-unsupported-version-x-we-support-y-error"+
" on how to fix this",
version, badgerMagicVersion)
}
if extVersion != extMagic {
return Manifest{}, 0,
fmt.Errorf("cannot open DB because the external magic number doesn't match, "+
"expected: %d, version present in manifest: %d", extMagic, extVersion)
}
stat, err := fp.Stat()
if err != nil {
return Manifest{}, 0, err
}
build := createManifest()
var offset int64
for {
offset = r.count
var lenCrcBuf [8]byte
_, err := io.ReadFull(&r, lenCrcBuf[:])
if err != nil {
if err == io.EOF || err == io.ErrUnexpectedEOF {
break
}
return Manifest{}, 0, err
}
length := y.BytesToU32(lenCrcBuf[0:4])
// Sanity check to ensure we don't over-allocate memory.
if length > uint32(stat.Size()) {
return Manifest{}, 0, fmt.Errorf(
"Buffer length: %d greater than file size: %d. Manifest file might be corrupted",
length, stat.Size())
}
var buf = make([]byte, length)
if _, err := io.ReadFull(&r, buf); err != nil {
if err == io.EOF || err == io.ErrUnexpectedEOF {
break
}
return Manifest{}, 0, err
}
if crc32.Checksum(buf, y.CastagnoliCrcTable) != y.BytesToU32(lenCrcBuf[4:8]) {
return Manifest{}, 0, errBadChecksum
}
var changeSet pb.ManifestChangeSet
if err := proto.Unmarshal(buf, &changeSet); err != nil {
return Manifest{}, 0, err
}
if err := applyChangeSet(&build, &changeSet, opt); err != nil {
return Manifest{}, 0, err
}
}
return build, offset, nil
}
func applyManifestChange(build *Manifest, tc *pb.ManifestChange, opt Options) error {
switch tc.Op {
case pb.ManifestChange_CREATE:
if _, ok := build.Tables[tc.Id]; ok {
return fmt.Errorf("MANIFEST invalid, table %d exists", tc.Id)
}
build.Tables[tc.Id] = TableManifest{
Level: uint8(tc.Level),
KeyID: tc.KeyId,
Compression: options.CompressionType(tc.Compression),
}
for len(build.Levels) <= int(tc.Level) {
build.Levels = append(build.Levels, levelManifest{make(map[uint64]struct{})})
}
build.Levels[tc.Level].Tables[tc.Id] = struct{}{}
build.Creations++
case pb.ManifestChange_DELETE:
tm, ok := build.Tables[tc.Id]
if !ok {
opt.Warningf("MANIFEST delete: table %d has already been removed", tc.Id)
for _, level := range build.Levels {
delete(level.Tables, tc.Id)
}
} else {
delete(build.Levels[tm.Level].Tables, tc.Id)
delete(build.Tables, tc.Id)
}
build.Deletions++
default:
return fmt.Errorf("MANIFEST file has invalid manifestChange op")
}
return nil
}
// This is not a "recoverable" error -- opening the KV store fails because the MANIFEST file is
// just plain broken.
func applyChangeSet(build *Manifest, changeSet *pb.ManifestChangeSet, opt Options) error {
for _, change := range changeSet.Changes {
if err := applyManifestChange(build, change, opt); err != nil {
return err
}
}
return nil
}
func newCreateChange(
id uint64, level int, keyID uint64, c options.CompressionType) *pb.ManifestChange {
return &pb.ManifestChange{
Id: id,
Op: pb.ManifestChange_CREATE,
Level: uint32(level),
KeyId: keyID,
// Hard coding it, since we're supporting only AES for now.
EncryptionAlgo: pb.EncryptionAlgo_aes,
Compression: uint32(c),
}
}
func newDeleteChange(id uint64) *pb.ManifestChange {
return &pb.ManifestChange{
Id: id,
Op: pb.ManifestChange_DELETE,
}
}
================================================
FILE: manifest_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"fmt"
"math/rand"
"os"
"path/filepath"
"sort"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/dgraph-io/badger/v4/options"
"github.com/dgraph-io/badger/v4/pb"
"github.com/dgraph-io/badger/v4/table"
"github.com/dgraph-io/badger/v4/y"
)
func TestManifestBasic(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := getTestOptions(dir)
{
kv, err := Open(opt)
require.NoError(t, err)
n := 5000
for i := 0; i < n; i++ {
if (i % 10000) == 0 {
fmt.Printf("Putting i=%d\n", i)
}
k := []byte(fmt.Sprintf("%16x", rand.Int63()))
txnSet(t, kv, k, k, 0x00)
}
txnSet(t, kv, []byte("testkey"), []byte("testval"), 0x05)
require.NoError(t, kv.validate())
require.NoError(t, kv.Close())
}
kv, err := Open(opt)
require.NoError(t, err)
require.NoError(t, kv.View(func(txn *Txn) error {
item, err := txn.Get([]byte("testkey"))
require.NoError(t, err)
require.EqualValues(t, "testval", string(getItemValue(t, item)))
require.EqualValues(t, byte(0x05), item.UserMeta())
return nil
}))
require.NoError(t, kv.Close())
}
func helpTestManifestFileCorruption(t *testing.T, off int64, errorContent string) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := getTestOptions(dir)
{
kv, err := Open(opt)
require.NoError(t, err)
require.NoError(t, kv.Close())
}
fp, err := os.OpenFile(filepath.Join(dir, ManifestFilename), os.O_RDWR, 0)
require.NoError(t, err)
// Mess with magic value or version to force error
_, err = fp.WriteAt([]byte{'X'}, off)
require.NoError(t, err)
require.NoError(t, fp.Close())
kv, err := Open(opt)
defer func() {
if kv != nil {
kv.Close()
}
}()
require.Error(t, err)
require.Contains(t, err.Error(), errorContent)
}
func TestManifestMagic(t *testing.T) {
helpTestManifestFileCorruption(t, 3, "bad magic")
}
func TestManifestVersion(t *testing.T) {
helpTestManifestFileCorruption(t, 6, "unsupported version")
}
func TestManifestChecksum(t *testing.T) {
helpTestManifestFileCorruption(t, 15, "checksum mismatch")
}
func key(prefix string, i int) string {
return prefix + fmt.Sprintf("%04d", i)
}
// TODO - Move these to somewhere where table package can also use it.
// keyValues is n by 2 where n is number of pairs.
func buildTable(t *testing.T, keyValues [][]string, bopts table.Options) *table.Table {
if bopts.BloomFalsePositive == 0 {
bopts.BloomFalsePositive = 0.01
}
if bopts.BlockSize == 0 {
bopts.BlockSize = 4 * 1024
}
b := table.NewTableBuilder(bopts)
defer b.Close()
// TODO: Add test for file garbage collection here. No files should be left after the tests here.
filename := fmt.Sprintf("%s%s%d.sst", os.TempDir(), string(os.PathSeparator), rand.Uint32())
sort.Slice(keyValues, func(i, j int) bool {
return keyValues[i][0] < keyValues[j][0]
})
for _, kv := range keyValues {
y.AssertTrue(len(kv) == 2)
b.Add(y.KeyWithTs([]byte(kv[0]), 10), y.ValueStruct{
Value: []byte(kv[1]),
Meta: 'A',
UserMeta: 0,
}, 0)
}
tbl, err := table.CreateTable(filename, b)
require.NoError(t, err)
return tbl
}
func TestOverlappingKeyRangeError(t *testing.T) {
// [Aman] This test is not making sense to me right now. When fixing warnings from
// linter, I realized that the runCompactDef function below always returns error.
t.Skip()
buildTestTable := func(t *testing.T, prefix string, n int, opts table.Options) *table.Table {
y.AssertTrue(n <= 10000)
keyValues := make([][]string, n)
for i := 0; i < n; i++ {
k := key(prefix, i)
v := fmt.Sprintf("%d", i)
keyValues[i] = []string{k, v}
}
return buildTable(t, keyValues, opts)
}
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
kv, err := Open(DefaultOptions(dir))
require.NoError(t, err)
defer func() { require.NoError(t, kv.Close()) }()
lh0 := newLevelHandler(kv, 0)
lh1 := newLevelHandler(kv, 1)
opts := table.Options{ChkMode: options.OnTableAndBlockRead}
t1 := buildTestTable(t, "k", 2, opts)
defer func() { require.NoError(t, t1.DecrRef()) }()
done := lh0.tryAddLevel0Table(t1)
require.Equal(t, true, done)
cd := compactDef{
thisLevel: lh0,
nextLevel: lh1,
t: kv.lc.levelTargets(),
}
cd.t.baseLevel = 1
manifest := createManifest()
lc, err := newLevelsController(kv, &manifest)
require.NoError(t, err)
done = lc.fillTablesL0(&cd)
require.Equal(t, true, done)
require.NoError(t, lc.runCompactDef(-1, 0, cd))
t2 := buildTestTable(t, "l", 2, opts)
defer func() { require.NoError(t, t2.DecrRef()) }()
done = lh0.tryAddLevel0Table(t2)
require.Equal(t, true, done)
cd = compactDef{
thisLevel: lh0,
nextLevel: lh1,
t: kv.lc.levelTargets(),
}
cd.t.baseLevel = 1
lc.fillTablesL0(&cd)
require.NoError(t, lc.runCompactDef(-1, 0, cd))
}
func TestManifestRewrite(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
db, err := Open(DefaultOptions(dir))
require.NoError(t, err, "error while opening db")
defer func() {
require.NoError(t, db.Close())
removeDir(dir)
}()
deletionsThreshold := 10
mf, m, err := helpOpenOrCreateManifestFile(dir, false, 0, deletionsThreshold, db.opt)
defer func() {
if mf != nil {
mf.close()
}
}()
require.NoError(t, err)
require.Equal(t, 0, m.Creations)
require.Equal(t, 0, m.Deletions)
err = mf.addChanges([]*pb.ManifestChange{
newCreateChange(0, 0, 0, 0),
}, db.opt)
require.NoError(t, err)
for i := uint64(0); i < uint64(deletionsThreshold*3); i++ {
ch := []*pb.ManifestChange{
newCreateChange(i+1, 0, 0, 0),
newDeleteChange(i),
}
err := mf.addChanges(ch, db.opt)
require.NoError(t, err)
}
err = mf.close()
require.NoError(t, err)
mf = nil
mf, m, err = helpOpenOrCreateManifestFile(dir, false, 0, deletionsThreshold, db.opt)
require.NoError(t, err)
require.Equal(t, map[uint64]TableManifest{
uint64(deletionsThreshold * 3): {Level: 0},
}, m.Tables)
}
func TestConcurrentManifestCompaction(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
db, err := Open(DefaultOptions(dir))
require.NoError(t, err, "error while opening db")
defer func() {
require.NoError(t, db.Close())
}()
// overwrite the sync function to make this race condition easily reproducible
syncFunc = func(f *os.File) error {
// effectively making the Sync() take around 1s makes this reproduce every time
time.Sleep(1 * time.Second)
return f.Sync()
}
mf, _, err := helpOpenOrCreateManifestFile(dir, false, 0, 0, db.opt)
require.NoError(t, err)
cs := &pb.ManifestChangeSet{}
for i := uint64(0); i < 1000; i++ {
cs.Changes = append(cs.Changes,
newCreateChange(i, 0, 0, 0),
newDeleteChange(i),
)
}
// simulate 2 concurrent compaction threads
n := 2
wg := sync.WaitGroup{}
wg.Add(n)
for i := 0; i < n; i++ {
go func() {
defer wg.Done()
require.NoError(t, mf.addChanges(cs.Changes, db.opt))
}()
}
wg.Wait()
require.NoError(t, mf.close())
}
================================================
FILE: memtable.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"bufio"
"bytes"
"crypto/aes"
cryptorand "crypto/rand"
"encoding/binary"
"fmt"
"hash/crc32"
"io"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"github.com/dgraph-io/badger/v4/pb"
"github.com/dgraph-io/badger/v4/skl"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2/z"
)
// memTable structure stores a skiplist and a corresponding WAL. Writes to memTable are written
// both to the WAL and the skiplist. On a crash, the WAL is replayed to bring the skiplist back to
// its pre-crash form.
type memTable struct {
// TODO: Give skiplist z.Calloc'd []byte.
sl *skl.Skiplist
wal *logFile
maxVersion uint64
opt Options
buf *bytes.Buffer
}
func (db *DB) openMemTables(opt Options) error {
// We don't need to open any tables in in-memory mode.
if db.opt.InMemory {
return nil
}
files, err := os.ReadDir(db.opt.Dir)
if err != nil {
return errFile(err, db.opt.Dir, "Unable to open mem dir.")
}
var fids []int
for _, file := range files {
if !strings.HasSuffix(file.Name(), memFileExt) {
continue
}
fsz := len(file.Name())
fid, err := strconv.ParseInt(file.Name()[:fsz-len(memFileExt)], 10, 64)
if err != nil {
return errFile(err, file.Name(), "Unable to parse log id.")
}
fids = append(fids, int(fid))
}
// Sort in ascending order.
sort.Slice(fids, func(i, j int) bool {
return fids[i] < fids[j]
})
for _, fid := range fids {
flags := os.O_RDWR
if db.opt.ReadOnly {
flags = os.O_RDONLY
}
mt, err := db.openMemTable(fid, flags)
if err != nil {
return y.Wrapf(err, "while opening fid: %d", fid)
}
// If this memtable is empty we don't need to add it. This is a
// memtable that was completely truncated.
if mt.sl.Empty() {
mt.DecrRef()
continue
}
// These should no longer be written to. So, make them part of the imm.
db.imm = append(db.imm, mt)
}
if len(fids) != 0 {
db.nextMemFid = fids[len(fids)-1]
}
db.nextMemFid++
return nil
}
const memFileExt string = ".mem"
func (db *DB) openMemTable(fid, flags int) (*memTable, error) {
filepath := db.mtFilePath(fid)
s := skl.NewSkiplist(arenaSize(db.opt))
mt := &memTable{
sl: s,
opt: db.opt,
buf: &bytes.Buffer{},
}
// We don't need to create the wal for the skiplist in in-memory mode so return the mt.
if db.opt.InMemory {
return mt, z.NewFile
}
mt.wal = &logFile{
fid: uint32(fid),
path: filepath,
registry: db.registry,
writeAt: vlogHeaderSize,
opt: db.opt,
}
lerr := mt.wal.open(filepath, flags, 2*db.opt.MemTableSize)
if lerr != z.NewFile && lerr != nil {
return nil, y.Wrapf(lerr, "While opening memtable: %s", filepath)
}
// Have a callback set to delete WAL when skiplist reference count goes down to zero. That is,
// when it gets flushed to L0.
s.OnClose = func() {
if err := mt.wal.Delete(); err != nil {
db.opt.Errorf("while deleting file: %s, err: %v", filepath, err)
}
}
if lerr == z.NewFile {
return mt, lerr
}
err := mt.UpdateSkipList()
return mt, y.Wrapf(err, "while updating skiplist")
}
func (db *DB) newMemTable() (*memTable, error) {
mt, err := db.openMemTable(db.nextMemFid, os.O_CREATE|os.O_RDWR)
if err == z.NewFile {
db.nextMemFid++
return mt, nil
}
if err != nil {
db.opt.Errorf("Got error: %v for id: %d\n", err, db.nextMemFid)
return nil, y.Wrapf(err, "newMemTable")
}
return nil, fmt.Errorf("File %s already exists", mt.wal.Fd.Name())
}
func (db *DB) mtFilePath(fid int) string {
return filepath.Join(db.opt.Dir, fmt.Sprintf("%05d%s", fid, memFileExt))
}
func (mt *memTable) SyncWAL() error {
return mt.wal.Sync()
}
func (mt *memTable) isFull() bool {
if mt.sl.MemSize() >= mt.opt.MemTableSize {
return true
}
if mt.opt.InMemory {
// InMemory mode doesn't have any WAL.
return false
}
return int64(mt.wal.writeAt) >= mt.opt.MemTableSize
}
func (mt *memTable) Put(key []byte, value y.ValueStruct) error {
entry := &Entry{
Key: key,
Value: value.Value,
UserMeta: value.UserMeta,
meta: value.Meta,
ExpiresAt: value.ExpiresAt,
}
// wal is nil only when badger in running in in-memory mode and we don't need the wal.
if mt.wal != nil {
// If WAL exceeds opt.ValueLogFileSize, we'll force flush the memTable. See logic in
// ensureRoomForWrite.
if err := mt.wal.writeEntry(mt.buf, entry, mt.opt); err != nil {
return y.Wrapf(err, "cannot write entry to WAL file")
}
}
// We insert the finish marker in the WAL but not in the memtable.
if entry.meta&bitFinTxn > 0 {
return nil
}
// Write to skiplist and update maxVersion encountered.
mt.sl.Put(key, value)
if ts := y.ParseTs(entry.Key); ts > mt.maxVersion {
mt.maxVersion = ts
}
y.NumBytesWrittenToL0Add(mt.opt.MetricsEnabled, entry.estimateSizeAndSetThreshold(mt.opt.ValueThreshold))
return nil
}
func (mt *memTable) UpdateSkipList() error {
if mt.wal == nil || mt.sl == nil {
return nil
}
endOff, err := mt.wal.iterate(true, 0, mt.replayFunction(mt.opt))
if err != nil {
return y.Wrapf(err, "while iterating wal: %s", mt.wal.Fd.Name())
}
if endOff < mt.wal.size.Load() && mt.opt.ReadOnly {
return y.Wrapf(ErrTruncateNeeded, "end offset: %d < size: %d", endOff, mt.wal.size.Load())
}
return mt.wal.Truncate(int64(endOff))
}
// IncrRef increases the refcount
func (mt *memTable) IncrRef() {
mt.sl.IncrRef()
}
// DecrRef decrements the refcount, deallocating the Skiplist when done using it
func (mt *memTable) DecrRef() {
mt.sl.DecrRef()
}
func (mt *memTable) replayFunction(opt Options) func(Entry, valuePointer) error {
first := true
return func(e Entry, _ valuePointer) error { // Function for replaying.
if first {
opt.Debugf("First key=%q\n", e.Key)
}
first = false
if ts := y.ParseTs(e.Key); ts > mt.maxVersion {
mt.maxVersion = ts
}
v := y.ValueStruct{
Value: e.Value,
Meta: e.meta,
UserMeta: e.UserMeta,
ExpiresAt: e.ExpiresAt,
}
// This is already encoded correctly. Value would be either a vptr, or a full value
// depending upon how big the original value was. Skiplist makes a copy of the key and
// value.
mt.sl.Put(e.Key, v)
return nil
}
}
type logFile struct {
*z.MmapFile
path string
// This is a lock on the log file. It guards the fd’s value, the file’s
// existence and the file’s memory map.
//
// Use shared ownership when reading/writing the file or memory map, use
// exclusive ownership to open/close the descriptor, unmap or remove the file.
lock sync.RWMutex
fid uint32
size atomic.Uint32
dataKey *pb.DataKey
baseIV []byte
registry *KeyRegistry
writeAt uint32
opt Options
}
func (lf *logFile) Truncate(end int64) error {
if fi, err := lf.Fd.Stat(); err != nil {
return fmt.Errorf("while file.stat on file: %s, error: %v\n", lf.Fd.Name(), err)
} else if fi.Size() == end {
return nil
}
y.AssertTrue(!lf.opt.ReadOnly)
lf.size.Store(uint32(end))
return lf.MmapFile.Truncate(end)
}
// encodeEntry will encode entry to the buf
// layout of entry
// +--------+-----+-------+-------+
// | header | key | value | crc32 |
// +--------+-----+-------+-------+
func (lf *logFile) encodeEntry(buf *bytes.Buffer, e *Entry, offset uint32) (int, error) {
h := header{
klen: uint32(len(e.Key)),
vlen: uint32(len(e.Value)),
expiresAt: e.ExpiresAt,
meta: e.meta,
userMeta: e.UserMeta,
}
hash := crc32.New(y.CastagnoliCrcTable)
writer := io.MultiWriter(buf, hash)
// encode header.
var headerEnc [maxHeaderSize]byte
sz := h.Encode(headerEnc[:])
y.Check2(writer.Write(headerEnc[:sz]))
// we'll encrypt only key and value.
if lf.encryptionEnabled() {
// TODO: no need to allocate the bytes. we can calculate the encrypted buf one by one
// since we're using ctr mode of AES encryption. Ordering won't changed. Need some
// refactoring in XORBlock which will work like stream cipher.
eBuf := make([]byte, 0, len(e.Key)+len(e.Value))
eBuf = append(eBuf, e.Key...)
eBuf = append(eBuf, e.Value...)
if err := y.XORBlockStream(
writer, eBuf, lf.dataKey.Data, lf.generateIV(offset)); err != nil {
return 0, y.Wrapf(err, "Error while encoding entry for vlog.")
}
} else {
// Encryption is disabled so writing directly to the buffer.
y.Check2(writer.Write(e.Key))
y.Check2(writer.Write(e.Value))
}
// write crc32 hash.
var crcBuf [crc32.Size]byte
binary.BigEndian.PutUint32(crcBuf[:], hash.Sum32())
y.Check2(buf.Write(crcBuf[:]))
// return encoded length.
return len(headerEnc[:sz]) + len(e.Key) + len(e.Value) + len(crcBuf), nil
}
func (lf *logFile) writeEntry(buf *bytes.Buffer, e *Entry, opt Options) error {
buf.Reset()
plen, err := lf.encodeEntry(buf, e, lf.writeAt)
if err != nil {
return err
}
y.AssertTrue(plen == copy(lf.Data[lf.writeAt:], buf.Bytes()))
lf.writeAt += uint32(plen)
lf.zeroNextEntry()
return nil
}
func (lf *logFile) decodeEntry(buf []byte, offset uint32) (*Entry, error) {
var h header
hlen := h.Decode(buf)
kv := buf[hlen:]
if lf.encryptionEnabled() {
var err error
// No need to worry about mmap. because, XORBlock allocates a byte array to do the
// xor. So, the given slice is not being mutated.
if kv, err = lf.decryptKV(kv, offset); err != nil {
return nil, err
}
}
e := &Entry{
meta: h.meta,
UserMeta: h.userMeta,
ExpiresAt: h.expiresAt,
offset: offset,
Key: kv[:h.klen],
Value: kv[h.klen : h.klen+h.vlen],
}
return e, nil
}
func (lf *logFile) decryptKV(buf []byte, offset uint32) ([]byte, error) {
return y.XORBlockAllocate(buf, lf.dataKey.Data, lf.generateIV(offset))
}
// KeyID returns datakey's ID.
func (lf *logFile) keyID() uint64 {
if lf.dataKey == nil {
// If there is no datakey, then we'll return 0. Which means no encryption.
return 0
}
return lf.dataKey.KeyId
}
func (lf *logFile) encryptionEnabled() bool {
return lf.dataKey != nil
}
// Acquire lock on mmap/file if you are calling this
func (lf *logFile) read(p valuePointer) (buf []byte, err error) {
offset := p.Offset
// Do not convert size to uint32, because the lf.Data can be of size
// 4GB, which overflows the uint32 during conversion to make the size 0,
// causing the read to fail with ErrEOF. See issue #585.
size := int64(len(lf.Data))
valsz := p.Len
lfsz := lf.size.Load()
if int64(offset) >= size || int64(offset+valsz) > size ||
// Ensure that the read is within the file's actual size. It might be possible that
// the offset+valsz length is beyond the file's actual size. This could happen when
// dropAll and iterations are running simultaneously.
int64(offset+valsz) > int64(lfsz) {
err = y.ErrEOF
} else {
buf = lf.Data[offset : offset+valsz]
}
return buf, err
}
// generateIV will generate IV by appending given offset with the base IV.
func (lf *logFile) generateIV(offset uint32) []byte {
iv := make([]byte, aes.BlockSize)
// baseIV is of 12 bytes.
y.AssertTrue(12 == copy(iv[:12], lf.baseIV))
// remaining 4 bytes is obtained from offset.
binary.BigEndian.PutUint32(iv[12:], offset)
return iv
}
func (lf *logFile) doneWriting(offset uint32) error {
if lf.opt.SyncWrites {
if err := lf.Sync(); err != nil {
return y.Wrapf(err, "Unable to sync value log: %q", lf.path)
}
}
// Before we were acquiring a lock here on lf.lock, because we were invalidating the file
// descriptor due to reopening it as read-only. Now, we don't invalidate the fd, but unmap it,
// truncate it and remap it. That creates a window where we have segfaults because the mmap is
// no longer valid, while someone might be reading it. Therefore, we need a lock here again.
lf.lock.Lock()
defer lf.lock.Unlock()
if err := lf.Truncate(int64(offset)); err != nil {
return y.Wrapf(err, "Unable to truncate file: %q", lf.path)
}
// Previously we used to close the file after it was written and reopen it in read-only mode.
// We no longer open files in read-only mode. We keep all vlog files open in read-write mode.
return nil
}
// iterate iterates over log file. It doesn't not allocate new memory for every kv pair.
// Therefore, the kv pair is only valid for the duration of fn call.
func (lf *logFile) iterate(readOnly bool, offset uint32, fn logEntry) (uint32, error) {
if offset == 0 {
// If offset is set to zero, let's advance past the encryption key header.
offset = vlogHeaderSize
}
// For now, read directly from file, because it allows
reader := bufio.NewReader(lf.NewReader(int(offset)))
read := &safeRead{
k: make([]byte, 10),
v: make([]byte, 10),
recordOffset: offset,
lf: lf,
}
var lastCommit uint64
var validEndOffset uint32 = offset
var entries []*Entry
var vptrs []valuePointer
loop:
for {
e, err := read.Entry(reader)
switch {
// We have not reached the end of the file but the entry we read is
// zero. This happens because we have truncated the file and
// zero'ed it out.
case err == io.EOF:
break loop
case err == io.ErrUnexpectedEOF || err == errTruncate:
break loop
case err != nil:
return 0, err
case e == nil:
continue
case e.isZero():
break loop
}
var vp valuePointer
vp.Len = uint32(e.hlen + len(e.Key) + len(e.Value) + crc32.Size)
read.recordOffset += vp.Len
vp.Offset = e.offset
vp.Fid = lf.fid
switch {
case e.meta&bitTxn > 0:
txnTs := y.ParseTs(e.Key)
if lastCommit == 0 {
lastCommit = txnTs
}
if lastCommit != txnTs {
break loop
}
entries = append(entries, e)
vptrs = append(vptrs, vp)
case e.meta&bitFinTxn > 0:
txnTs, err := strconv.ParseUint(string(e.Value), 10, 64)
if err != nil || lastCommit != txnTs {
break loop
}
// Got the end of txn. Now we can store them.
lastCommit = 0
validEndOffset = read.recordOffset
for i, e := range entries {
vp := vptrs[i]
if err := fn(*e, vp); err != nil {
if err == errStop {
break
}
return 0, errFile(err, lf.path, "Iteration function")
}
}
entries = entries[:0]
vptrs = vptrs[:0]
default:
if lastCommit != 0 {
// This is most likely an entry which was moved as part of GC.
// We shouldn't get this entry in the middle of a transaction.
break loop
}
validEndOffset = read.recordOffset
if err := fn(*e, vp); err != nil {
if err == errStop {
break
}
return 0, errFile(err, lf.path, "Iteration function")
}
}
}
return validEndOffset, nil
}
// Zero out the next entry to deal with any crashes.
func (lf *logFile) zeroNextEntry() {
z.ZeroOut(lf.Data, int(lf.writeAt), int(lf.writeAt+maxHeaderSize))
}
func (lf *logFile) open(path string, flags int, fsize int64) error {
mf, ferr := z.OpenMmapFile(path, flags, int(fsize))
lf.MmapFile = mf
if ferr == z.NewFile {
if err := lf.bootstrap(); err != nil {
os.Remove(path)
return err
}
lf.size.Store(vlogHeaderSize)
} else if ferr != nil {
return y.Wrapf(ferr, "while opening file: %s", path)
}
lf.size.Store(uint32(len(lf.Data)))
if lf.size.Load() < vlogHeaderSize {
// Every vlog file should have at least vlogHeaderSize. If it is less than vlogHeaderSize
// then it must have been corrupted. But no need to handle here. log replayer will truncate
// and bootstrap the logfile. So ignoring here.
return nil
}
// Copy over the encryption registry data.
buf := make([]byte, vlogHeaderSize)
y.AssertTruef(vlogHeaderSize == copy(buf, lf.Data),
"Unable to copy from %s, size %d", path, lf.size.Load())
keyID := binary.BigEndian.Uint64(buf[:8])
// retrieve datakey.
if dk, err := lf.registry.DataKey(keyID); err != nil {
return y.Wrapf(err, "While opening vlog file %d", lf.fid)
} else {
lf.dataKey = dk
}
lf.baseIV = buf[8:]
y.AssertTrue(len(lf.baseIV) == 12)
// Preserved ferr so we can return if this was a new file.
return ferr
}
// bootstrap will initialize the log file with key id and baseIV.
// The below figure shows the layout of log file.
// +----------------+------------------+------------------+
// | keyID(8 bytes) | baseIV(12 bytes)| entry... |
// +----------------+------------------+------------------+
func (lf *logFile) bootstrap() error {
var err error
// generate data key for the log file.
var dk *pb.DataKey
if dk, err = lf.registry.LatestDataKey(); err != nil {
return y.Wrapf(err, "Error while retrieving datakey in logFile.bootstarp")
}
lf.dataKey = dk
// We'll always preserve vlogHeaderSize for key id and baseIV.
buf := make([]byte, vlogHeaderSize)
// write key id to the buf.
// key id will be zero if the logfile is in plain text.
binary.BigEndian.PutUint64(buf[:8], lf.keyID())
// generate base IV. It'll be used with offset of the vptr to encrypt the entry.
if _, err := cryptorand.Read(buf[8:]); err != nil {
return y.Wrapf(err, "Error while creating base IV, while creating logfile")
}
// Initialize base IV.
lf.baseIV = buf[8:]
y.AssertTrue(len(lf.baseIV) == 12)
// Copy over to the logFile.
y.AssertTrue(vlogHeaderSize == copy(lf.Data[0:], buf))
// Zero out the next entry.
lf.zeroNextEntry()
return nil
}
================================================
FILE: merge.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
stderrors "errors"
"sync"
"time"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2/z"
)
// MergeOperator represents a Badger merge operator.
type MergeOperator struct {
sync.RWMutex
f MergeFunc
db *DB
key []byte
closer *z.Closer
}
// MergeFunc accepts two byte slices, one representing an existing value, and
// another representing a new value that needs to be ‘merged’ into it. MergeFunc
// contains the logic to perform the ‘merge’ and return an updated value.
// MergeFunc could perform operations like integer addition, list appends etc.
// Note that the ordering of the operands is maintained.
type MergeFunc func(existingVal, newVal []byte) []byte
// GetMergeOperator creates a new MergeOperator for a given key and returns a
// pointer to it. It also fires off a goroutine that performs a compaction using
// the merge function that runs periodically, as specified by dur.
func (db *DB) GetMergeOperator(key []byte,
f MergeFunc, dur time.Duration) *MergeOperator {
op := &MergeOperator{
f: f,
db: db,
key: key,
closer: z.NewCloser(1),
}
go op.runCompactions(dur)
return op
}
var errNoMerge = stderrors.New("No need for merge")
func (op *MergeOperator) iterateAndMerge() (newVal []byte, latest uint64, err error) {
txn := op.db.NewTransaction(false)
defer txn.Discard()
opt := DefaultIteratorOptions
opt.AllVersions = true
it := txn.NewKeyIterator(op.key, opt)
defer it.Close()
var numVersions int
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
if item.IsDeletedOrExpired() {
break
}
numVersions++
if numVersions == 1 {
// This should be the newVal, considering this is the latest version.
newVal, err = item.ValueCopy(newVal)
if err != nil {
return nil, 0, err
}
latest = item.Version()
} else {
if err := item.Value(func(oldVal []byte) error {
// The merge should always be on the newVal considering it has the merge result of
// the latest version. The value read should be the oldVal.
newVal = op.f(oldVal, newVal)
return nil
}); err != nil {
return nil, 0, err
}
}
if item.DiscardEarlierVersions() {
break
}
}
if numVersions == 0 {
return nil, latest, ErrKeyNotFound
} else if numVersions == 1 {
return newVal, latest, errNoMerge
}
return newVal, latest, nil
}
func (op *MergeOperator) compact() error {
op.Lock()
defer op.Unlock()
val, version, err := op.iterateAndMerge()
if err == ErrKeyNotFound || err == errNoMerge {
return nil
} else if err != nil {
return err
}
entries := []*Entry{
{
Key: y.KeyWithTs(op.key, version),
Value: val,
meta: bitDiscardEarlierVersions,
},
}
// Write value back to the DB. It is important that we do not set the bitMergeEntry bit
// here. When compaction happens, all the older merged entries will be removed.
return op.db.batchSetAsync(entries, func(err error) {
if err != nil {
op.db.opt.Errorf("failed to insert the result of merge compaction: %s", err)
}
})
}
func (op *MergeOperator) runCompactions(dur time.Duration) {
ticker := time.NewTicker(dur)
defer op.closer.Done()
var stop bool
for {
select {
case <-op.closer.HasBeenClosed():
stop = true
case <-ticker.C: // wait for tick
}
if err := op.compact(); err != nil {
op.db.opt.Errorf("failure while running merge operation: %s", err)
}
if stop {
ticker.Stop()
break
}
}
}
// Add records a value in Badger which will eventually be merged by a background
// routine into the values that were recorded by previous invocations to Add().
func (op *MergeOperator) Add(val []byte) error {
return op.db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry(op.key, val).withMergeBit())
})
}
// Get returns the latest value for the merge operator, which is derived by
// applying the merge function to all the values added so far.
//
// If Add has not been called even once, Get will return ErrKeyNotFound.
func (op *MergeOperator) Get() ([]byte, error) {
op.RLock()
defer op.RUnlock()
var existing []byte
err := op.db.View(func(txn *Txn) (err error) {
existing, _, err = op.iterateAndMerge()
return err
})
if err == errNoMerge {
return existing, nil
}
return existing, err
}
// Stop waits for any pending merge to complete and then stops the background
// goroutine.
func (op *MergeOperator) Stop() {
op.closer.SignalAndWait()
}
================================================
FILE: merge_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"encoding/binary"
"os"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestGetMergeOperator(t *testing.T) {
t.Run("Get before Add", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
m := db.GetMergeOperator([]byte("merge"), add, 200*time.Millisecond)
defer m.Stop()
val, err := m.Get()
require.Equal(t, ErrKeyNotFound, err)
require.Nil(t, val)
})
})
t.Run("Add and Get", func(t *testing.T) {
key := []byte("merge")
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
m := db.GetMergeOperator(key, add, 200*time.Millisecond)
defer m.Stop()
require.NoError(t, m.Add(uint64ToBytes(1)))
require.NoError(t, m.Add(uint64ToBytes(2)))
require.NoError(t, m.Add(uint64ToBytes(3)))
res, err := m.Get()
require.NoError(t, err)
require.Equal(t, uint64(6), bytesToUint64(res))
})
})
t.Run("Add and Get slices", func(t *testing.T) {
// Merge function to merge two byte slices
add := func(originalValue, newValue []byte) []byte {
return append(originalValue, newValue...)
}
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
m := db.GetMergeOperator([]byte("fooprefix"), add, 2*time.Millisecond)
defer m.Stop()
require.NoError(t, m.Add([]byte("A")))
require.NoError(t, m.Add([]byte("B")))
require.NoError(t, m.Add([]byte("C")))
value, err := m.Get()
require.NoError(t, err)
require.Equal(t, "ABC", string(value))
})
})
t.Run("Get Before Compact", func(t *testing.T) {
key := []byte("merge")
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
m := db.GetMergeOperator(key, add, 500*time.Millisecond)
defer m.Stop()
require.NoError(t, m.Add(uint64ToBytes(1)))
require.NoError(t, m.Add(uint64ToBytes(2)))
require.NoError(t, m.Add(uint64ToBytes(3)))
res, err := m.Get()
require.NoError(t, err)
require.Equal(t, uint64(6), bytesToUint64(res))
})
})
t.Run("Get after Delete", func(t *testing.T) {
key := []byte("merge")
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
m := db.GetMergeOperator(key, add, 200*time.Millisecond)
require.NoError(t, m.Add(uint64ToBytes(1)))
require.NoError(t, m.Add(uint64ToBytes(2)))
require.NoError(t, m.Add(uint64ToBytes(3)))
m.Stop()
res, err := m.Get()
require.NoError(t, err)
require.Equal(t, uint64(6), bytesToUint64(res))
require.NoError(t, db.Update(func(txn *Txn) error {
return txn.Delete(key)
}))
m = db.GetMergeOperator(key, add, 200*time.Millisecond)
require.NoError(t, m.Add(uint64ToBytes(1)))
m.Stop()
res, err = m.Get()
require.NoError(t, err)
require.Equal(t, uint64(1), bytesToUint64(res))
})
})
t.Run("Get after Stop", func(t *testing.T) {
key := []byte("merge")
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
m := db.GetMergeOperator(key, add, 1*time.Second)
require.NoError(t, m.Add(uint64ToBytes(1)))
require.NoError(t, m.Add(uint64ToBytes(2)))
require.NoError(t, m.Add(uint64ToBytes(3)))
m.Stop()
res, err := m.Get()
require.NoError(t, err)
require.Equal(t, uint64(6), bytesToUint64(res))
})
})
t.Run("Old keys should be removed after compaction", func(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
// This test relies on CompactL0OnClose
opts := getTestOptions(dir).WithCompactL0OnClose(true)
db, err := Open(opts)
require.NoError(t, err)
mergeKey := []byte("foo")
m := db.GetMergeOperator(mergeKey, add, 2*time.Millisecond)
count := 5000 // This will cause compaction from L0->L1
for i := 0; i < count; i++ {
require.NoError(t, m.Add(uint64ToBytes(1)))
}
value, err := m.Get()
require.Nil(t, err)
require.Equal(t, uint64(count), bytesToUint64(value))
m.Stop()
// Force compaction by closing DB. The compaction should discard all the old merged values
require.Nil(t, db.Close())
db, err = Open(opts)
require.NoError(t, err)
defer db.Close()
keyCount := 0
txn := db.NewTransaction(false)
defer txn.Discard()
iopt := DefaultIteratorOptions
iopt.AllVersions = true
it := txn.NewKeyIterator(mergeKey, iopt)
defer it.Close()
for it.Rewind(); it.Valid(); it.Next() {
keyCount++
}
// We should have only one key in badger. All the other keys should've been removed by
// compaction
require.Equal(t, 1, keyCount)
})
}
func uint64ToBytes(i uint64) []byte {
var buf [8]byte
binary.BigEndian.PutUint64(buf[:], i)
return buf[:]
}
func bytesToUint64(b []byte) uint64 {
return binary.BigEndian.Uint64(b)
}
// Merge function to add two uint64 numbers
func add(existing, latest []byte) []byte {
return uint64ToBytes(bytesToUint64(existing) + bytesToUint64(latest))
}
================================================
FILE: metrics_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"expvar"
"math/rand"
"testing"
"github.com/stretchr/testify/require"
)
func clearAllMetrics() {
expvar.Do(func(kv expvar.KeyValue) {
// Reset the value of each expvar variable based on its type
switch v := kv.Value.(type) {
case *expvar.Int:
v.Set(0)
case *expvar.Float:
v.Set(0)
case *expvar.Map:
v.Init()
case *expvar.String:
v.Set("")
}
})
}
func TestWriteMetrics(t *testing.T) {
opt := getTestOptions("")
opt.managedTxns = true
opt.CompactL0OnClose = true
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
clearAllMetrics()
num := 10
val := make([]byte, 1<<12)
key := make([]byte, 40)
for i := 0; i < num; i++ {
_, err := rand.Read(key)
require.NoError(t, err)
_, err = rand.Read(val)
require.NoError(t, err)
writer := db.NewManagedWriteBatch()
require.NoError(t, writer.SetEntryAt(NewEntry(key, val), 1))
writer.Flush()
}
expectedSize := int64(len(val)) + 48 + 2 // 48 := size of key (40 + 8(ts)), 2 := meta
write_metric := expvar.Get("badger_write_bytes_user")
require.Equal(t, expectedSize*int64(num), write_metric.(*expvar.Int).Value())
put_metric := expvar.Get("badger_put_num_user")
require.Equal(t, int64(num), put_metric.(*expvar.Int).Value())
lsm_metric := expvar.Get("badger_write_bytes_l0")
require.Equal(t, expectedSize*int64(num), lsm_metric.(*expvar.Int).Value())
compactionMetric := expvar.Get("badger_write_bytes_compaction").(*expvar.Map)
require.Equal(t, nil, compactionMetric.Get("l6"))
// Force compaction
db.Close()
_, err := OpenManaged(opt)
require.NoError(t, err)
compactionMetric = expvar.Get("badger_write_bytes_compaction").(*expvar.Map)
require.GreaterOrEqual(t, expectedSize*int64(num)+int64(num*200), compactionMetric.Get("l6").(*expvar.Int).Value())
// Because we have random values, compression is not able to do much, so we incur a cost on total size
})
}
func TestVlogMetrics(t *testing.T) {
opt := getTestOptions("")
opt.managedTxns = true
opt.CompactL0OnClose = true
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
clearAllMetrics()
num := 10
val := make([]byte, 1<<20) // Large Value
key := make([]byte, 40)
for i := 0; i < num; i++ {
_, err := rand.Read(key)
require.NoError(t, err)
_, err = rand.Read(val)
require.NoError(t, err)
writer := db.NewManagedWriteBatch()
require.NoError(t, writer.SetEntryAt(NewEntry(key, val), 1))
writer.Flush()
}
expectedSize := int64(len(val)) + 200 // vlog expected size
totalWrites := expvar.Get("badger_write_num_vlog")
require.Equal(t, int64(num), totalWrites.(*expvar.Int).Value())
bytesWritten := expvar.Get("badger_write_bytes_vlog")
require.GreaterOrEqual(t, expectedSize*int64(num), bytesWritten.(*expvar.Int).Value())
txn := db.NewTransactionAt(2, false)
item, err := txn.Get(key)
require.NoError(t, err)
require.Equal(t, uint64(1), item.Version())
err = item.Value(func(val []byte) error {
totalReads := expvar.Get("badger_read_num_vlog")
bytesRead := expvar.Get("badger_read_bytes_vlog")
require.Equal(t, int64(1), totalReads.(*expvar.Int).Value())
require.GreaterOrEqual(t, expectedSize, bytesRead.(*expvar.Int).Value())
return nil
})
require.NoError(t, err)
})
}
func TestReadMetrics(t *testing.T) {
opt := getTestOptions("")
opt.managedTxns = true
opt.CompactL0OnClose = true
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
clearAllMetrics()
num := 10
val := make([]byte, 1<<15)
keys := [][]byte{}
writer := db.NewManagedWriteBatch()
for i := 0; i < num; i++ {
keyB := key("byte", 1)
keys = append(keys, []byte(keyB))
_, err := rand.Read(val)
require.NoError(t, err)
require.NoError(t, writer.SetEntryAt(NewEntry([]byte(keyB), val), 1))
}
writer.Flush()
txn := db.NewTransactionAt(2, false)
item, err := txn.Get(keys[0])
require.NoError(t, err)
require.Equal(t, uint64(1), item.Version())
totalGets := expvar.Get("badger_get_num_user")
require.Equal(t, int64(1), totalGets.(*expvar.Int).Value())
totalMemtableReads := expvar.Get("badger_get_num_memtable")
require.Equal(t, int64(1), totalMemtableReads.(*expvar.Int).Value())
totalLSMGets := expvar.Get("badger_get_num_lsm")
require.Nil(t, totalLSMGets.(*expvar.Map).Get("l6"))
// Force compaction
db.Close()
db, err = OpenManaged(opt)
require.NoError(t, err)
txn = db.NewTransactionAt(2, false)
item, err = txn.Get(keys[0])
require.NoError(t, err)
require.Equal(t, uint64(1), item.Version())
_, err = txn.Get([]byte(key("abdbyte", 1000))) // val should be far enough that bloom filter doesn't hit
require.Error(t, err)
totalLSMGets = expvar.Get("badger_get_num_lsm")
require.Equal(t, int64(0x1), totalLSMGets.(*expvar.Map).Get("l6").(*expvar.Int).Value())
totalBloom := expvar.Get("badger_hit_num_lsm_bloom_filter")
require.Equal(t, int64(0x1), totalBloom.(*expvar.Map).Get("l6").(*expvar.Int).Value())
require.Equal(t, int64(0x1), totalBloom.(*expvar.Map).Get("DoesNotHave_HIT").(*expvar.Int).Value())
require.Equal(t, int64(0x2), totalBloom.(*expvar.Map).Get("DoesNotHave_ALL").(*expvar.Int).Value())
bytesLSM := expvar.Get("badger_read_bytes_lsm")
require.Equal(t, int64(len(val)), bytesLSM.(*expvar.Int).Value())
getWithResult := expvar.Get("badger_get_with_result_num_user")
require.Equal(t, int64(2), getWithResult.(*expvar.Int).Value())
iterOpts := DefaultIteratorOptions
iter := txn.NewKeyIterator(keys[0], iterOpts)
iter.Seek(keys[0])
rangeQueries := expvar.Get("badger_iterator_num_user")
require.Equal(t, int64(1), rangeQueries.(*expvar.Int).Value())
})
}
================================================
FILE: options/options.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package options
// ChecksumVerificationMode tells when should DB verify checksum for SSTable blocks.
type ChecksumVerificationMode int
const (
// NoVerification indicates DB should not verify checksum for SSTable blocks.
NoVerification ChecksumVerificationMode = iota
// OnTableRead indicates checksum should be verified while opening SSTtable.
OnTableRead
// OnBlockRead indicates checksum should be verified on every SSTable block read.
OnBlockRead
// OnTableAndBlockRead indicates checksum should be verified
// on SSTable opening and on every block read.
OnTableAndBlockRead
)
// CompressionType specifies how a block should be compressed.
type CompressionType uint32
const (
// None mode indicates that a block is not compressed.
None CompressionType = 0
// Snappy mode indicates that a block is compressed using Snappy algorithm.
Snappy CompressionType = 1
// ZSTD mode indicates that a block is compressed using ZSTD algorithm.
ZSTD CompressionType = 2
)
================================================
FILE: options.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"fmt"
"os"
"reflect"
"strconv"
"strings"
"time"
"github.com/dgraph-io/badger/v4/options"
"github.com/dgraph-io/badger/v4/table"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2/z"
)
// Note: If you add a new option X make sure you also add a WithX method on Options.
// Options are params for creating DB object.
//
// This package provides DefaultOptions which contains options that should
// work for most applications. Consider using that as a starting point before
// customizing it for your own needs.
//
// Each option X is documented on the WithX method.
type Options struct {
testOnlyOptions
// Required options.
Dir string
ValueDir string
// Usually modified options.
SyncWrites bool
NumVersionsToKeep int
ReadOnly bool
Logger Logger
Compression options.CompressionType
InMemory bool
MetricsEnabled bool
// Sets the Stream.numGo field
NumGoroutines int
// Fine tuning options.
MemTableSize int64
BaseTableSize int64
BaseLevelSize int64
LevelSizeMultiplier int
TableSizeMultiplier int
MaxLevels int
VLogPercentile float64
ValueThreshold int64
NumMemtables int
// Changing BlockSize across DB runs will not break badger. The block size is
// read from the block index stored at the end of the table.
BlockSize int
BloomFalsePositive float64
BlockCacheSize int64
IndexCacheSize int64
NumLevelZeroTables int
NumLevelZeroTablesStall int
ValueLogFileSize int64
ValueLogMaxEntries uint32
NumCompactors int
CompactL0OnClose bool
LmaxCompaction bool
ZSTDCompressionLevel int
// When set, checksum will be validated for each entry read from the value log file.
VerifyValueChecksum bool
// Encryption related options.
EncryptionKey []byte // encryption key
EncryptionKeyRotationDuration time.Duration // key rotation duration
// BypassLockGuard will bypass the lock guard on badger. Bypassing lock
// guard can cause data corruption if multiple badger instances are using
// the same directory. Use this options with caution.
BypassLockGuard bool
// ChecksumVerificationMode decides when db should verify checksums for SSTable blocks.
ChecksumVerificationMode options.ChecksumVerificationMode
// DetectConflicts determines whether the transactions would be checked for
// conflicts. The transactions can be processed at a higher rate when
// conflict detection is disabled.
DetectConflicts bool
// NamespaceOffset specifies the offset from where the next 8 bytes contains the namespace.
NamespaceOffset int
// Magic version used by the application using badger to ensure that it doesn't open the DB
// with incompatible data format.
ExternalMagicVersion uint16
// Transaction start and commit timestamps are managed by end-user.
// This is only useful for databases built on top of Badger (like Dgraph).
// Not recommended for most users.
managedTxns bool
// 4. Flags for testing purposes
// ------------------------------
maxBatchCount int64 // max entries in batch
maxBatchSize int64 // max batch size in bytes
maxValueThreshold float64
}
// DefaultOptions sets a list of recommended options for good performance.
// Feel free to modify these to suit your needs with the WithX methods.
func DefaultOptions(path string) Options {
return Options{
Dir: path,
ValueDir: path,
MemTableSize: 64 << 20,
BaseTableSize: 2 << 20,
BaseLevelSize: 10 << 20,
TableSizeMultiplier: 2,
LevelSizeMultiplier: 10,
MaxLevels: 7,
NumGoroutines: 8,
MetricsEnabled: true,
NumCompactors: 4, // Run at least 2 compactors. Zero-th compactor prioritizes L0.
NumLevelZeroTables: 5,
NumLevelZeroTablesStall: 15,
NumMemtables: 5,
BloomFalsePositive: 0.01,
BlockSize: 4 * 1024,
SyncWrites: false,
NumVersionsToKeep: 1,
CompactL0OnClose: false,
VerifyValueChecksum: false,
Compression: options.Snappy,
BlockCacheSize: 256 << 20,
IndexCacheSize: 0,
// The following benchmarks were done on a 4 KB block size (default block size). The
// compression is ratio supposed to increase with increasing compression level but since the
// input for compression algorithm is small (4 KB), we don't get significant benefit at
// level 3.
// NOTE: The benchmarks are with DataDog ZSTD that requires CGO. Hence, no longer valid.
// no_compression-16 10 502848865 ns/op 165.46 MB/s -
// zstd_compression/level_1-16 7 739037966 ns/op 112.58 MB/s 2.93
// zstd_compression/level_3-16 7 756950250 ns/op 109.91 MB/s 2.72
// zstd_compression/level_15-16 1 11135686219 ns/op 7.47 MB/s 4.38
// Benchmark code can be found in table/builder_test.go file
ZSTDCompressionLevel: 1,
// (2^30 - 1)*2 when mmapping < 2^31 - 1, max int32.
// -1 so 2*ValueLogFileSize won't overflow on 32-bit systems.
ValueLogFileSize: 1<<30 - 1,
ValueLogMaxEntries: 1000000,
VLogPercentile: 0.0,
ValueThreshold: maxValueThreshold,
Logger: defaultLogger(INFO),
EncryptionKey: []byte{},
EncryptionKeyRotationDuration: 10 * 24 * time.Hour, // Default 10 days.
DetectConflicts: true,
NamespaceOffset: -1,
}
}
func buildTableOptions(db *DB) table.Options {
opt := db.opt
dk, err := db.registry.LatestDataKey()
y.Check(err)
return table.Options{
ReadOnly: opt.ReadOnly,
MetricsEnabled: db.opt.MetricsEnabled,
TableSize: uint64(opt.BaseTableSize),
BlockSize: opt.BlockSize,
BloomFalsePositive: opt.BloomFalsePositive,
ChkMode: opt.ChecksumVerificationMode,
Compression: opt.Compression,
ZSTDCompressionLevel: opt.ZSTDCompressionLevel,
BlockCache: db.blockCache,
IndexCache: db.indexCache,
AllocPool: db.allocPool,
DataKey: dk,
}
}
const (
maxValueThreshold = (1 << 20) // 1 MB
)
// LSMOnlyOptions follows from DefaultOptions, but sets a higher ValueThreshold
// so values would be collocated with the LSM tree, with value log largely acting
// as a write-ahead log only. These options would reduce the disk usage of value
// log, and make Badger act more like a typical LSM tree.
func LSMOnlyOptions(path string) Options {
// Let's not set any other options, because they can cause issues with the
// size of key-value a user can pass to Badger. For e.g., if we set
// ValueLogFileSize to 64MB, a user can't pass a value more than that.
// Setting it to ValueLogMaxEntries to 1000, can generate too many files.
// These options are better configured on a usage basis, than broadly here.
// The ValueThreshold is the most important setting a user needs to do to
// achieve a heavier usage of LSM tree.
// NOTE: If a user does not want to set 64KB as the ValueThreshold because
// of performance reasons, 1KB would be a good option too, allowing
// values smaller than 1KB to be collocated with the keys in the LSM tree.
return DefaultOptions(path).WithValueThreshold(maxValueThreshold /* 1 MB */)
}
// parseCompression returns badger.compressionType and compression level given compression string
// of format compression-type:compression-level
func parseCompression(cStr string) (options.CompressionType, int, error) {
cStrSplit := strings.Split(cStr, ":")
cType := cStrSplit[0]
level := 3
var err error
if len(cStrSplit) == 2 {
level, err = strconv.Atoi(cStrSplit[1])
y.Check(err)
if level <= 0 {
return 0, 0,
fmt.Errorf("ERROR: compression level(%v) must be greater than zero", level)
}
} else if len(cStrSplit) > 2 {
return 0, 0, fmt.Errorf("ERROR: Invalid badger.compression argument")
}
switch cType {
case "zstd":
return options.ZSTD, level, nil
case "snappy":
return options.Snappy, 0, nil
case "none":
return options.None, 0, nil
}
return 0, 0, fmt.Errorf("ERROR: compression type (%s) invalid", cType)
}
// generateSuperFlag generates an identical SuperFlag string from the provided Options.
func generateSuperFlag(options Options) string {
superflag := ""
v := reflect.ValueOf(&options).Elem()
optionsStruct := v.Type()
for i := 0; i < v.NumField(); i++ {
if field := v.Field(i); field.CanInterface() {
name := strings.ToLower(optionsStruct.Field(i).Name)
kind := v.Field(i).Kind()
switch kind {
case reflect.Bool:
superflag += name + "="
superflag += fmt.Sprintf("%v; ", field.Bool())
case reflect.Int, reflect.Int64:
superflag += name + "="
superflag += fmt.Sprintf("%v; ", field.Int())
case reflect.Uint32, reflect.Uint64:
superflag += name + "="
superflag += fmt.Sprintf("%v; ", field.Uint())
case reflect.Float64:
superflag += name + "="
superflag += fmt.Sprintf("%v; ", field.Float())
case reflect.String:
superflag += name + "="
superflag += fmt.Sprintf("%v; ", field.String())
default:
continue
}
}
}
return superflag
}
// FromSuperFlag fills Options fields for each flag within the superflag. For
// example, replacing the default Options.NumGoroutines:
//
// options := FromSuperFlag("numgoroutines=4", DefaultOptions(""))
//
// It's important to note that if you pass an empty Options struct, FromSuperFlag
// will not fill it with default values. FromSuperFlag only writes to the fields
// present within the superflag string (case insensitive).
//
// It specially handles compression subflag.
// Valid options are {none,snappy,zstd:}
// Example: compression=zstd:3;
// Unsupported: Options.Logger, Options.EncryptionKey
func (opt Options) FromSuperFlag(superflag string) Options {
// currentOptions act as a default value for the options superflag.
currentOptions := generateSuperFlag(opt)
currentOptions += "compression=;"
flags := z.NewSuperFlag(superflag).MergeAndCheckDefault(currentOptions)
v := reflect.ValueOf(&opt).Elem()
optionsStruct := v.Type()
for i := 0; i < v.NumField(); i++ {
// only iterate over exported fields
if field := v.Field(i); field.CanInterface() {
// z.SuperFlag stores keys as lowercase, keep everything case
// insensitive
name := strings.ToLower(optionsStruct.Field(i).Name)
if name == "compression" {
// We will specially handle this later. Skip it here.
continue
}
kind := v.Field(i).Kind()
switch kind {
case reflect.Bool:
field.SetBool(flags.GetBool(name))
case reflect.Int, reflect.Int64:
field.SetInt(flags.GetInt64(name))
case reflect.Uint32, reflect.Uint64:
field.SetUint(flags.GetUint64(name))
case reflect.Float64:
field.SetFloat(flags.GetFloat64(name))
case reflect.String:
field.SetString(flags.GetString(name))
}
}
}
// Only update the options for special flags that were present in the input superflag.
inputFlag := z.NewSuperFlag(superflag)
if inputFlag.Has("compression") {
ctype, clevel, err := parseCompression(flags.GetString("compression"))
switch err {
case nil:
opt.Compression = ctype
opt.ZSTDCompressionLevel = clevel
default:
ctype = options.CompressionType(flags.GetUint32("compression"))
y.AssertTruef(ctype <= 2, "ERROR: Invalid format or compression type. Got: %s",
flags.GetString("compression"))
opt.Compression = ctype
}
}
return opt
}
// WithDir returns a new Options value with Dir set to the given value.
//
// Dir is the path of the directory where key data will be stored in.
// If it doesn't exist, Badger will try to create it for you.
// This is set automatically to be the path given to `DefaultOptions`.
func (opt Options) WithDir(val string) Options {
opt.Dir = val
return opt
}
// WithValueDir returns a new Options value with ValueDir set to the given value.
//
// ValueDir is the path of the directory where value data will be stored in.
// If it doesn't exist, Badger will try to create it for you.
// This is set automatically to be the path given to `DefaultOptions`.
func (opt Options) WithValueDir(val string) Options {
opt.ValueDir = val
return opt
}
// WithSyncWrites returns a new Options value with SyncWrites set to the given value.
//
// Badger does all writes via mmap. So, all writes can survive process crashes or k8s environments
// with SyncWrites set to false.
//
// When set to true, Badger would call an additional msync after writes to flush mmap buffer over to
// disk to survive hard reboots. Most users of Badger should not need to do this.
//
// The default value of SyncWrites is false.
func (opt Options) WithSyncWrites(val bool) Options {
opt.SyncWrites = val
return opt
}
// WithNumVersionsToKeep returns a new Options value with NumVersionsToKeep set to the given value.
//
// NumVersionsToKeep sets how many versions to keep per key at most.
//
// The default value of NumVersionsToKeep is 1.
func (opt Options) WithNumVersionsToKeep(val int) Options {
opt.NumVersionsToKeep = val
return opt
}
// WithNumGoroutines sets the number of goroutines to be used in Stream.
//
// The default value of NumGoroutines is 8.
func (opt Options) WithNumGoroutines(val int) Options {
opt.NumGoroutines = val
return opt
}
// WithReadOnly returns a new Options value with ReadOnly set to the given value.
//
// When ReadOnly is true the DB will be opened on read-only mode.
// Multiple processes can open the same Badger DB.
// Note: if the DB being opened had crashed before and has vlog data to be replayed,
// ReadOnly will cause Open to fail with an appropriate message.
//
// The default value of ReadOnly is false.
func (opt Options) WithReadOnly(val bool) Options {
opt.ReadOnly = val
return opt
}
// WithMetricsEnabled returns a new Options value with MetricsEnabled set to the given value.
//
// When MetricsEnabled is set to false, then the DB will be opened and no badger metrics
// will be logged. Metrics are defined in metric.go file.
//
// This flag is useful for use cases like in Dgraph where we open temporary badger instances to
// index data. In those cases we don't want badger metrics to be polluted with the noise from
// those temporary instances.
//
// Default value is set to true
func (opt Options) WithMetricsEnabled(val bool) Options {
opt.MetricsEnabled = val
return opt
}
// WithLogger returns a new Options value with Logger set to the given value.
//
// Logger provides a way to configure what logger each value of badger.DB uses.
//
// The default value of Logger writes to stderr using the log package from the Go standard library.
func (opt Options) WithLogger(val Logger) Options {
opt.Logger = val
return opt
}
// WithLoggingLevel returns a new Options value with logging level of the
// default logger set to the given value.
// LoggingLevel sets the level of logging. It should be one of DEBUG, INFO,
// WARNING or ERROR levels.
//
// The default value of LoggingLevel is INFO.
func (opt Options) WithLoggingLevel(val loggingLevel) Options {
opt.Logger = defaultLogger(val)
return opt
}
// WithBaseTableSize returns a new Options value with BaseTableSize set to the given value.
//
// BaseTableSize sets the maximum size in bytes for LSM table or file in the base level.
//
// The default value of BaseTableSize is 2MB.
func (opt Options) WithBaseTableSize(val int64) Options {
opt.BaseTableSize = val
return opt
}
// WithLevelSizeMultiplier returns a new Options value with LevelSizeMultiplier set to the given
// value.
//
// LevelSizeMultiplier sets the ratio between the maximum sizes of contiguous levels in the LSM.
// Once a level grows to be larger than this ratio allowed, the compaction process will be
// triggered.
//
// The default value of LevelSizeMultiplier is 10.
func (opt Options) WithLevelSizeMultiplier(val int) Options {
opt.LevelSizeMultiplier = val
return opt
}
// WithMaxLevels returns a new Options value with MaxLevels set to the given value.
//
// Maximum number of levels of compaction allowed in the LSM.
//
// The default value of MaxLevels is 7.
func (opt Options) WithMaxLevels(val int) Options {
opt.MaxLevels = val
return opt
}
// WithValueThreshold returns a new Options value with ValueThreshold set to the given value.
//
// ValueThreshold sets the threshold used to decide whether a value is stored directly in the LSM
// tree or separately in the log value files.
//
// The default value of ValueThreshold is 1 MB, and LSMOnlyOptions sets it to maxValueThreshold
// which is set to 1 MB too.
func (opt Options) WithValueThreshold(val int64) Options {
opt.ValueThreshold = val
return opt
}
// WithVLogPercentile returns a new Options value with ValLogPercentile set to given value.
//
// VLogPercentile with 0.0 means no dynamic thresholding is enabled.
// MinThreshold value will always act as the value threshold.
//
// VLogPercentile with value 0.99 means 99 percentile of value will be put in LSM tree
// and only 1 percent in vlog. The value threshold will be dynamically updated within the range of
// [ValueThreshold, Options.maxValueThreshold]
//
// # Say VLogPercentile with 1.0 means threshold will eventually set to Options.maxValueThreshold
//
// The default value of VLogPercentile is 0.0.
func (opt Options) WithVLogPercentile(t float64) Options {
opt.VLogPercentile = t
return opt
}
// WithNumMemtables returns a new Options value with NumMemtables set to the given value.
//
// NumMemtables sets the maximum number of tables to keep in memory before stalling.
//
// The default value of NumMemtables is 5.
func (opt Options) WithNumMemtables(val int) Options {
opt.NumMemtables = val
return opt
}
// WithMemTableSize returns a new Options value with MemTableSize set to the given value.
//
// MemTableSize sets the maximum size in bytes for memtable table.
//
// The default value of MemTableSize is 64MB.
func (opt Options) WithMemTableSize(val int64) Options {
opt.MemTableSize = val
return opt
}
// WithBloomFalsePositive returns a new Options value with BloomFalsePositive set
// to the given value.
//
// BloomFalsePositive sets the false positive probability of the bloom filter in any SSTable.
// Before reading a key from table, the bloom filter is checked for key existence.
// BloomFalsePositive might impact read performance of DB. Lower BloomFalsePositive value might
// consume more memory.
//
// The default value of BloomFalsePositive is 0.01.
//
// Setting this to 0 disables the bloom filter completely.
func (opt Options) WithBloomFalsePositive(val float64) Options {
opt.BloomFalsePositive = val
return opt
}
// WithBlockSize returns a new Options value with BlockSize set to the given value.
//
// BlockSize sets the size of any block in SSTable. SSTable is divided into multiple blocks
// internally. Each block is compressed using prefix diff encoding.
//
// The default value of BlockSize is 4KB.
func (opt Options) WithBlockSize(val int) Options {
opt.BlockSize = val
return opt
}
// WithNumLevelZeroTables sets the maximum number of Level 0 tables before compaction starts.
//
// The default value of NumLevelZeroTables is 5.
func (opt Options) WithNumLevelZeroTables(val int) Options {
opt.NumLevelZeroTables = val
return opt
}
// WithNumLevelZeroTablesStall sets the number of Level 0 tables that once reached causes the DB to
// stall until compaction succeeds.
//
// The default value of NumLevelZeroTablesStall is 15.
func (opt Options) WithNumLevelZeroTablesStall(val int) Options {
opt.NumLevelZeroTablesStall = val
return opt
}
// WithBaseLevelSize sets the maximum size target for the base level.
//
// The default value is 10MB.
func (opt Options) WithBaseLevelSize(val int64) Options {
opt.BaseLevelSize = val
return opt
}
// WithValueLogFileSize sets the maximum size of a single value log file.
//
// The default value of ValueLogFileSize is 1GB.
func (opt Options) WithValueLogFileSize(val int64) Options {
opt.ValueLogFileSize = val
return opt
}
// WithValueLogMaxEntries sets the maximum number of entries a value log file
// can hold approximately. A actual size limit of a value log file is the
// minimum of ValueLogFileSize and ValueLogMaxEntries.
//
// The default value of ValueLogMaxEntries is one million (1000000).
func (opt Options) WithValueLogMaxEntries(val uint32) Options {
opt.ValueLogMaxEntries = val
return opt
}
// WithNumCompactors sets the number of compaction workers to run concurrently. Setting this to
// zero stops compactions, which could eventually cause writes to block forever.
//
// The default value of NumCompactors is 4. One is dedicated just for L0 and L1.
func (opt Options) WithNumCompactors(val int) Options {
opt.NumCompactors = val
return opt
}
// WithCompactL0OnClose determines whether Level 0 should be compacted before closing the DB. This
// ensures that both reads and writes are efficient when the DB is opened later.
//
// The default value of CompactL0OnClose is false.
func (opt Options) WithCompactL0OnClose(val bool) Options {
opt.CompactL0OnClose = val
return opt
}
// WithEncryptionKey is used to encrypt the data with AES. Type of AES is used based on the key
// size. For example 16 bytes will use AES-128. 24 bytes will use AES-192. 32 bytes will
// use AES-256.
func (opt Options) WithEncryptionKey(key []byte) Options {
opt.EncryptionKey = key
return opt
}
// WithEncryptionKeyRotationDuration returns new Options value with the duration set to
// the given value.
//
// Key Registry will use this duration to create new keys. If the previous generated
// key exceed the given duration. Then the key registry will create new key.
// The default value is set to 10 days.
func (opt Options) WithEncryptionKeyRotationDuration(d time.Duration) Options {
opt.EncryptionKeyRotationDuration = d
return opt
}
// WithCompression is used to enable or disable compression. When compression is enabled, every
// block will be compressed using the specified algorithm. This option doesn't affect existing
// tables. Only the newly created tables will be compressed.
//
// The default compression algorithm used is snappy. Compression is enabled by default.
func (opt Options) WithCompression(cType options.CompressionType) Options {
opt.Compression = cType
return opt
}
// WithVerifyValueChecksum is used to set VerifyValueChecksum. When VerifyValueChecksum is set to
// true, checksum will be verified for every entry read from the value log. If the value is stored
// in SST (value size less than value threshold) then the checksum validation will not be done.
//
// The default value of VerifyValueChecksum is False.
func (opt Options) WithVerifyValueChecksum(val bool) Options {
opt.VerifyValueChecksum = val
return opt
}
// WithChecksumVerificationMode returns a new Options value with ChecksumVerificationMode set to
// the given value.
//
// ChecksumVerificationMode indicates when the db should verify checksums for SSTable blocks.
//
// The default value of VerifyValueChecksum is options.NoVerification.
func (opt Options) WithChecksumVerificationMode(cvMode options.ChecksumVerificationMode) Options {
opt.ChecksumVerificationMode = cvMode
return opt
}
// WithBlockCacheSize returns a new Options value with BlockCacheSize set to the given value.
//
// This value specifies how much data cache should hold in memory. A small size
// of cache means lower memory consumption and lookups/iterations would take
// longer. It is recommended to use a cache if you're using compression or encryption.
// If compression and encryption both are disabled, adding a cache will lead to
// unnecessary overhead which will affect the read performance. Setting size to
// zero disables the cache altogether.
//
// Default value of BlockCacheSize is 256 MB.
func (opt Options) WithBlockCacheSize(size int64) Options {
opt.BlockCacheSize = size
return opt
}
// WithInMemory returns a new Options value with Inmemory mode set to the given value.
//
// When badger is running in InMemory mode, everything is stored in memory. No value/sst files are
// created. In case of a crash all data will be lost.
func (opt Options) WithInMemory(b bool) Options {
opt.InMemory = b
return opt
}
// WithZSTDCompressionLevel returns a new Options value with ZSTDCompressionLevel set
// to the given value.
//
// The ZSTD compression algorithm supports 20 compression levels. The higher the compression
// level, the better is the compression ratio but lower is the performance. Lower levels
// have better performance and higher levels have better compression ratios.
// We recommend using level 1 ZSTD Compression Level. Any level higher than 1 seems to
// deteriorate badger's performance.
// The following benchmarks were done on a 4 KB block size (default block size). The compression is
// ratio supposed to increase with increasing compression level but since the input for compression
// algorithm is small (4 KB), we don't get significant benefit at level 3. It is advised to write
// your own benchmarks before choosing a compression algorithm or level.
//
// NOTE: The benchmarks are with DataDog ZSTD that requires CGO. Hence, no longer valid.
// no_compression-16 10 502848865 ns/op 165.46 MB/s -
// zstd_compression/level_1-16 7 739037966 ns/op 112.58 MB/s 2.93
// zstd_compression/level_3-16 7 756950250 ns/op 109.91 MB/s 2.72
// zstd_compression/level_15-16 1 11135686219 ns/op 7.47 MB/s 4.38
// Benchmark code can be found in table/builder_test.go file
func (opt Options) WithZSTDCompressionLevel(cLevel int) Options {
opt.ZSTDCompressionLevel = cLevel
return opt
}
// WithBypassLockGuard returns a new Options value with BypassLockGuard
// set to the given value.
//
// When BypassLockGuard option is set, badger will not acquire a lock on the
// directory. This could lead to data corruption if multiple badger instances
// write to the same data directory. Use this option with caution.
//
// The default value of BypassLockGuard is false.
func (opt Options) WithBypassLockGuard(b bool) Options {
opt.BypassLockGuard = b
return opt
}
// WithIndexCacheSize returns a new Options value with IndexCacheSize set to
// the given value.
//
// This value specifies how much memory should be used by table indices. These
// indices include the block offsets and the bloomfilters. Badger uses bloom
// filters to speed up lookups. Each table has its own bloom
// filter and each bloom filter is approximately of 5 MB.
//
// Zero value for IndexCacheSize means all the indices will be kept in
// memory and the cache is disabled.
//
// The default value of IndexCacheSize is 0 which means all indices are kept in
// memory.
func (opt Options) WithIndexCacheSize(size int64) Options {
opt.IndexCacheSize = size
return opt
}
// WithDetectConflicts returns a new Options value with DetectConflicts set to the given value.
//
// Detect conflicts options determines if the transactions would be checked for
// conflicts before committing them. When this option is set to false
// (detectConflicts=false) badger can process transactions at a higher rate.
// Setting this options to false might be useful when the user application
// deals with conflict detection and resolution.
//
// The default value of Detect conflicts is True.
func (opt Options) WithDetectConflicts(b bool) Options {
opt.DetectConflicts = b
return opt
}
// WithNamespaceOffset returns a new Options value with NamespaceOffset set to the given value. DB
// will expect the namespace in each key at the 8 bytes starting from NamespaceOffset. A negative
// value means that namespace is not stored in the key.
//
// The default value for NamespaceOffset is -1.
func (opt Options) WithNamespaceOffset(offset int) Options {
opt.NamespaceOffset = offset
return opt
}
// WithExternalMagic returns a new Options value with ExternalMagicVersion set to the given value.
// The DB would fail to start if either the internal or the external magic number fails validated.
func (opt Options) WithExternalMagic(magic uint16) Options {
opt.ExternalMagicVersion = magic
return opt
}
func (opt Options) getFileFlags() int {
var flags int
// opt.SyncWrites would be using msync to sync. All writes go through mmap.
if opt.ReadOnly {
flags |= os.O_RDONLY
} else {
flags |= os.O_RDWR
}
return flags
}
================================================
FILE: options_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"reflect"
"testing"
"github.com/dgraph-io/badger/v4/options"
)
func TestOptions(t *testing.T) {
t.Run("default options", func(t *testing.T) {
// copy all the default options over to a big SuperFlag string
defaultSuperFlag := generateSuperFlag(DefaultOptions(""))
// fill an empty Options with values from the SuperFlag
generated := Options{}.FromSuperFlag(defaultSuperFlag)
// make sure they're equal
if !optionsEqual(DefaultOptions(""), generated) {
t.Fatal("generated default SuperFlag != default Options")
}
// check that values are overwritten properly
overwritten := DefaultOptions("").FromSuperFlag("numgoroutines=1234")
if overwritten.NumGoroutines != 1234 {
t.Fatal("Option value not overwritten by SuperFlag value")
}
})
t.Run("special flags", func(t *testing.T) {
o1 := DefaultOptions("")
o1.NamespaceOffset = 10
o1.Compression = options.ZSTD
o1.ZSTDCompressionLevel = 2
o1.NumGoroutines = 20
o2 := DefaultOptions("")
o2.NamespaceOffset = 10
o2 = o2.FromSuperFlag("compression=zstd:2; numgoroutines=20;")
// make sure they're equal
if !optionsEqual(o1, o2) {
t.Fatal("generated superFlag != expected options")
}
})
}
// optionsEqual just compares the values of two Options structs
func optionsEqual(o1, o2 Options) bool {
o1v := reflect.ValueOf(&o1).Elem()
o2v := reflect.ValueOf(&o2).Elem()
for i := 0; i < o1v.NumField(); i++ {
if o1v.Field(i).CanInterface() {
kind := o1v.Field(i).Kind()
// compare values
switch kind {
case reflect.Bool:
if o1v.Field(i).Bool() != o2v.Field(i).Bool() {
return false
}
case reflect.Int, reflect.Int64:
if o1v.Field(i).Int() != o2v.Field(i).Int() {
return false
}
case reflect.Uint32, reflect.Uint64:
if o1v.Field(i).Uint() != o2v.Field(i).Uint() {
return false
}
case reflect.Float64:
if o1v.Field(i).Float() != o2v.Field(i).Float() {
return false
}
case reflect.String:
if o1v.Field(i).String() != o2v.Field(i).String() {
return false
}
}
}
}
return true
}
================================================
FILE: pb/badgerpb4.pb.go
================================================
//
// SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
// SPDX-License-Identifier: Apache-2.0
// Use protos/gen.sh to generate .pb.go files.
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.31.0
// protoc v3.21.12
// source: badgerpb4.proto
package pb
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type EncryptionAlgo int32
const (
EncryptionAlgo_aes EncryptionAlgo = 0
)
// Enum value maps for EncryptionAlgo.
var (
EncryptionAlgo_name = map[int32]string{
0: "aes",
}
EncryptionAlgo_value = map[string]int32{
"aes": 0,
}
)
func (x EncryptionAlgo) Enum() *EncryptionAlgo {
p := new(EncryptionAlgo)
*p = x
return p
}
func (x EncryptionAlgo) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (EncryptionAlgo) Descriptor() protoreflect.EnumDescriptor {
return file_badgerpb4_proto_enumTypes[0].Descriptor()
}
func (EncryptionAlgo) Type() protoreflect.EnumType {
return &file_badgerpb4_proto_enumTypes[0]
}
func (x EncryptionAlgo) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use EncryptionAlgo.Descriptor instead.
func (EncryptionAlgo) EnumDescriptor() ([]byte, []int) {
return file_badgerpb4_proto_rawDescGZIP(), []int{0}
}
type ManifestChange_Operation int32
const (
ManifestChange_CREATE ManifestChange_Operation = 0
ManifestChange_DELETE ManifestChange_Operation = 1
)
// Enum value maps for ManifestChange_Operation.
var (
ManifestChange_Operation_name = map[int32]string{
0: "CREATE",
1: "DELETE",
}
ManifestChange_Operation_value = map[string]int32{
"CREATE": 0,
"DELETE": 1,
}
)
func (x ManifestChange_Operation) Enum() *ManifestChange_Operation {
p := new(ManifestChange_Operation)
*p = x
return p
}
func (x ManifestChange_Operation) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (ManifestChange_Operation) Descriptor() protoreflect.EnumDescriptor {
return file_badgerpb4_proto_enumTypes[1].Descriptor()
}
func (ManifestChange_Operation) Type() protoreflect.EnumType {
return &file_badgerpb4_proto_enumTypes[1]
}
func (x ManifestChange_Operation) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use ManifestChange_Operation.Descriptor instead.
func (ManifestChange_Operation) EnumDescriptor() ([]byte, []int) {
return file_badgerpb4_proto_rawDescGZIP(), []int{3, 0}
}
type Checksum_Algorithm int32
const (
Checksum_CRC32C Checksum_Algorithm = 0
Checksum_XXHash64 Checksum_Algorithm = 1
)
// Enum value maps for Checksum_Algorithm.
var (
Checksum_Algorithm_name = map[int32]string{
0: "CRC32C",
1: "XXHash64",
}
Checksum_Algorithm_value = map[string]int32{
"CRC32C": 0,
"XXHash64": 1,
}
)
func (x Checksum_Algorithm) Enum() *Checksum_Algorithm {
p := new(Checksum_Algorithm)
*p = x
return p
}
func (x Checksum_Algorithm) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (Checksum_Algorithm) Descriptor() protoreflect.EnumDescriptor {
return file_badgerpb4_proto_enumTypes[2].Descriptor()
}
func (Checksum_Algorithm) Type() protoreflect.EnumType {
return &file_badgerpb4_proto_enumTypes[2]
}
func (x Checksum_Algorithm) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use Checksum_Algorithm.Descriptor instead.
func (Checksum_Algorithm) EnumDescriptor() ([]byte, []int) {
return file_badgerpb4_proto_rawDescGZIP(), []int{4, 0}
}
type KV struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Key []byte `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
UserMeta []byte `protobuf:"bytes,3,opt,name=user_meta,json=userMeta,proto3" json:"user_meta,omitempty"`
Version uint64 `protobuf:"varint,4,opt,name=version,proto3" json:"version,omitempty"`
ExpiresAt uint64 `protobuf:"varint,5,opt,name=expires_at,json=expiresAt,proto3" json:"expires_at,omitempty"`
Meta []byte `protobuf:"bytes,6,opt,name=meta,proto3" json:"meta,omitempty"`
// Stream id is used to identify which stream the KV came from.
StreamId uint32 `protobuf:"varint,10,opt,name=stream_id,json=streamId,proto3" json:"stream_id,omitempty"`
// Stream done is used to indicate end of stream.
StreamDone bool `protobuf:"varint,11,opt,name=stream_done,json=streamDone,proto3" json:"stream_done,omitempty"`
}
func (x *KV) Reset() {
*x = KV{}
if protoimpl.UnsafeEnabled {
mi := &file_badgerpb4_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *KV) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*KV) ProtoMessage() {}
func (x *KV) ProtoReflect() protoreflect.Message {
mi := &file_badgerpb4_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use KV.ProtoReflect.Descriptor instead.
func (*KV) Descriptor() ([]byte, []int) {
return file_badgerpb4_proto_rawDescGZIP(), []int{0}
}
func (x *KV) GetKey() []byte {
if x != nil {
return x.Key
}
return nil
}
func (x *KV) GetValue() []byte {
if x != nil {
return x.Value
}
return nil
}
func (x *KV) GetUserMeta() []byte {
if x != nil {
return x.UserMeta
}
return nil
}
func (x *KV) GetVersion() uint64 {
if x != nil {
return x.Version
}
return 0
}
func (x *KV) GetExpiresAt() uint64 {
if x != nil {
return x.ExpiresAt
}
return 0
}
func (x *KV) GetMeta() []byte {
if x != nil {
return x.Meta
}
return nil
}
func (x *KV) GetStreamId() uint32 {
if x != nil {
return x.StreamId
}
return 0
}
func (x *KV) GetStreamDone() bool {
if x != nil {
return x.StreamDone
}
return false
}
type KVList struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Kv []*KV `protobuf:"bytes,1,rep,name=kv,proto3" json:"kv,omitempty"`
// alloc_ref used internally for memory management.
AllocRef uint64 `protobuf:"varint,10,opt,name=alloc_ref,json=allocRef,proto3" json:"alloc_ref,omitempty"`
}
func (x *KVList) Reset() {
*x = KVList{}
if protoimpl.UnsafeEnabled {
mi := &file_badgerpb4_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *KVList) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*KVList) ProtoMessage() {}
func (x *KVList) ProtoReflect() protoreflect.Message {
mi := &file_badgerpb4_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use KVList.ProtoReflect.Descriptor instead.
func (*KVList) Descriptor() ([]byte, []int) {
return file_badgerpb4_proto_rawDescGZIP(), []int{1}
}
func (x *KVList) GetKv() []*KV {
if x != nil {
return x.Kv
}
return nil
}
func (x *KVList) GetAllocRef() uint64 {
if x != nil {
return x.AllocRef
}
return 0
}
type ManifestChangeSet struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// A set of changes that are applied atomically.
Changes []*ManifestChange `protobuf:"bytes,1,rep,name=changes,proto3" json:"changes,omitempty"`
}
func (x *ManifestChangeSet) Reset() {
*x = ManifestChangeSet{}
if protoimpl.UnsafeEnabled {
mi := &file_badgerpb4_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *ManifestChangeSet) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ManifestChangeSet) ProtoMessage() {}
func (x *ManifestChangeSet) ProtoReflect() protoreflect.Message {
mi := &file_badgerpb4_proto_msgTypes[2]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ManifestChangeSet.ProtoReflect.Descriptor instead.
func (*ManifestChangeSet) Descriptor() ([]byte, []int) {
return file_badgerpb4_proto_rawDescGZIP(), []int{2}
}
func (x *ManifestChangeSet) GetChanges() []*ManifestChange {
if x != nil {
return x.Changes
}
return nil
}
type ManifestChange struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Id uint64 `protobuf:"varint,1,opt,name=Id,proto3" json:"Id,omitempty"` // Table ID.
Op ManifestChange_Operation `protobuf:"varint,2,opt,name=Op,proto3,enum=badgerpb4.ManifestChange_Operation" json:"Op,omitempty"`
Level uint32 `protobuf:"varint,3,opt,name=Level,proto3" json:"Level,omitempty"` // Only used for CREATE.
KeyId uint64 `protobuf:"varint,4,opt,name=key_id,json=keyId,proto3" json:"key_id,omitempty"`
EncryptionAlgo EncryptionAlgo `protobuf:"varint,5,opt,name=encryption_algo,json=encryptionAlgo,proto3,enum=badgerpb4.EncryptionAlgo" json:"encryption_algo,omitempty"`
Compression uint32 `protobuf:"varint,6,opt,name=compression,proto3" json:"compression,omitempty"` // Only used for CREATE Op.
}
func (x *ManifestChange) Reset() {
*x = ManifestChange{}
if protoimpl.UnsafeEnabled {
mi := &file_badgerpb4_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *ManifestChange) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ManifestChange) ProtoMessage() {}
func (x *ManifestChange) ProtoReflect() protoreflect.Message {
mi := &file_badgerpb4_proto_msgTypes[3]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ManifestChange.ProtoReflect.Descriptor instead.
func (*ManifestChange) Descriptor() ([]byte, []int) {
return file_badgerpb4_proto_rawDescGZIP(), []int{3}
}
func (x *ManifestChange) GetId() uint64 {
if x != nil {
return x.Id
}
return 0
}
func (x *ManifestChange) GetOp() ManifestChange_Operation {
if x != nil {
return x.Op
}
return ManifestChange_CREATE
}
func (x *ManifestChange) GetLevel() uint32 {
if x != nil {
return x.Level
}
return 0
}
func (x *ManifestChange) GetKeyId() uint64 {
if x != nil {
return x.KeyId
}
return 0
}
func (x *ManifestChange) GetEncryptionAlgo() EncryptionAlgo {
if x != nil {
return x.EncryptionAlgo
}
return EncryptionAlgo_aes
}
func (x *ManifestChange) GetCompression() uint32 {
if x != nil {
return x.Compression
}
return 0
}
type Checksum struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Algo Checksum_Algorithm `protobuf:"varint,1,opt,name=algo,proto3,enum=badgerpb4.Checksum_Algorithm" json:"algo,omitempty"` // For storing type of Checksum algorithm used
Sum uint64 `protobuf:"varint,2,opt,name=sum,proto3" json:"sum,omitempty"`
}
func (x *Checksum) Reset() {
*x = Checksum{}
if protoimpl.UnsafeEnabled {
mi := &file_badgerpb4_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Checksum) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Checksum) ProtoMessage() {}
func (x *Checksum) ProtoReflect() protoreflect.Message {
mi := &file_badgerpb4_proto_msgTypes[4]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Checksum.ProtoReflect.Descriptor instead.
func (*Checksum) Descriptor() ([]byte, []int) {
return file_badgerpb4_proto_rawDescGZIP(), []int{4}
}
func (x *Checksum) GetAlgo() Checksum_Algorithm {
if x != nil {
return x.Algo
}
return Checksum_CRC32C
}
func (x *Checksum) GetSum() uint64 {
if x != nil {
return x.Sum
}
return 0
}
type DataKey struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
KeyId uint64 `protobuf:"varint,1,opt,name=key_id,json=keyId,proto3" json:"key_id,omitempty"`
Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"`
Iv []byte `protobuf:"bytes,3,opt,name=iv,proto3" json:"iv,omitempty"`
CreatedAt int64 `protobuf:"varint,4,opt,name=created_at,json=createdAt,proto3" json:"created_at,omitempty"`
}
func (x *DataKey) Reset() {
*x = DataKey{}
if protoimpl.UnsafeEnabled {
mi := &file_badgerpb4_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *DataKey) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*DataKey) ProtoMessage() {}
func (x *DataKey) ProtoReflect() protoreflect.Message {
mi := &file_badgerpb4_proto_msgTypes[5]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use DataKey.ProtoReflect.Descriptor instead.
func (*DataKey) Descriptor() ([]byte, []int) {
return file_badgerpb4_proto_rawDescGZIP(), []int{5}
}
func (x *DataKey) GetKeyId() uint64 {
if x != nil {
return x.KeyId
}
return 0
}
func (x *DataKey) GetData() []byte {
if x != nil {
return x.Data
}
return nil
}
func (x *DataKey) GetIv() []byte {
if x != nil {
return x.Iv
}
return nil
}
func (x *DataKey) GetCreatedAt() int64 {
if x != nil {
return x.CreatedAt
}
return 0
}
type Match struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Prefix []byte `protobuf:"bytes,1,opt,name=prefix,proto3" json:"prefix,omitempty"`
IgnoreBytes string `protobuf:"bytes,2,opt,name=ignore_bytes,json=ignoreBytes,proto3" json:"ignore_bytes,omitempty"` // Comma separated with dash to represent ranges "1, 2-3, 4-7, 9"
}
func (x *Match) Reset() {
*x = Match{}
if protoimpl.UnsafeEnabled {
mi := &file_badgerpb4_proto_msgTypes[6]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Match) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Match) ProtoMessage() {}
func (x *Match) ProtoReflect() protoreflect.Message {
mi := &file_badgerpb4_proto_msgTypes[6]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Match.ProtoReflect.Descriptor instead.
func (*Match) Descriptor() ([]byte, []int) {
return file_badgerpb4_proto_rawDescGZIP(), []int{6}
}
func (x *Match) GetPrefix() []byte {
if x != nil {
return x.Prefix
}
return nil
}
func (x *Match) GetIgnoreBytes() string {
if x != nil {
return x.IgnoreBytes
}
return ""
}
var File_badgerpb4_proto protoreflect.FileDescriptor
var file_badgerpb4_proto_rawDesc = []byte{
0x0a, 0x0f, 0x62, 0x61, 0x64, 0x67, 0x65, 0x72, 0x70, 0x62, 0x34, 0x2e, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x12, 0x09, 0x62, 0x61, 0x64, 0x67, 0x65, 0x72, 0x70, 0x62, 0x34, 0x22, 0xd4, 0x01, 0x0a,
0x02, 0x4b, 0x56, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c,
0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02,
0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x1b, 0x0a, 0x09, 0x75,
0x73, 0x65, 0x72, 0x5f, 0x6d, 0x65, 0x74, 0x61, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08,
0x75, 0x73, 0x65, 0x72, 0x4d, 0x65, 0x74, 0x61, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73,
0x69, 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x04, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69,
0x6f, 0x6e, 0x12, 0x1d, 0x0a, 0x0a, 0x65, 0x78, 0x70, 0x69, 0x72, 0x65, 0x73, 0x5f, 0x61, 0x74,
0x18, 0x05, 0x20, 0x01, 0x28, 0x04, 0x52, 0x09, 0x65, 0x78, 0x70, 0x69, 0x72, 0x65, 0x73, 0x41,
0x74, 0x12, 0x12, 0x0a, 0x04, 0x6d, 0x65, 0x74, 0x61, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0c, 0x52,
0x04, 0x6d, 0x65, 0x74, 0x61, 0x12, 0x1b, 0x0a, 0x09, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x5f,
0x69, 0x64, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x08, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d,
0x49, 0x64, 0x12, 0x1f, 0x0a, 0x0b, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x5f, 0x64, 0x6f, 0x6e,
0x65, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0a, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x44,
0x6f, 0x6e, 0x65, 0x22, 0x44, 0x0a, 0x06, 0x4b, 0x56, 0x4c, 0x69, 0x73, 0x74, 0x12, 0x1d, 0x0a,
0x02, 0x6b, 0x76, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x62, 0x61, 0x64, 0x67,
0x65, 0x72, 0x70, 0x62, 0x34, 0x2e, 0x4b, 0x56, 0x52, 0x02, 0x6b, 0x76, 0x12, 0x1b, 0x0a, 0x09,
0x61, 0x6c, 0x6c, 0x6f, 0x63, 0x5f, 0x72, 0x65, 0x66, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x04, 0x52,
0x08, 0x61, 0x6c, 0x6c, 0x6f, 0x63, 0x52, 0x65, 0x66, 0x22, 0x48, 0x0a, 0x11, 0x4d, 0x61, 0x6e,
0x69, 0x66, 0x65, 0x73, 0x74, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x53, 0x65, 0x74, 0x12, 0x33,
0x0a, 0x07, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32,
0x19, 0x2e, 0x62, 0x61, 0x64, 0x67, 0x65, 0x72, 0x70, 0x62, 0x34, 0x2e, 0x4d, 0x61, 0x6e, 0x69,
0x66, 0x65, 0x73, 0x74, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x52, 0x07, 0x63, 0x68, 0x61, 0x6e,
0x67, 0x65, 0x73, 0x22, 0x8d, 0x02, 0x0a, 0x0e, 0x4d, 0x61, 0x6e, 0x69, 0x66, 0x65, 0x73, 0x74,
0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x12, 0x0e, 0x0a, 0x02, 0x49, 0x64, 0x18, 0x01, 0x20, 0x01,
0x28, 0x04, 0x52, 0x02, 0x49, 0x64, 0x12, 0x33, 0x0a, 0x02, 0x4f, 0x70, 0x18, 0x02, 0x20, 0x01,
0x28, 0x0e, 0x32, 0x23, 0x2e, 0x62, 0x61, 0x64, 0x67, 0x65, 0x72, 0x70, 0x62, 0x34, 0x2e, 0x4d,
0x61, 0x6e, 0x69, 0x66, 0x65, 0x73, 0x74, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x2e, 0x4f, 0x70,
0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x02, 0x4f, 0x70, 0x12, 0x14, 0x0a, 0x05, 0x4c,
0x65, 0x76, 0x65, 0x6c, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x4c, 0x65, 0x76, 0x65,
0x6c, 0x12, 0x15, 0x0a, 0x06, 0x6b, 0x65, 0x79, 0x5f, 0x69, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28,
0x04, 0x52, 0x05, 0x6b, 0x65, 0x79, 0x49, 0x64, 0x12, 0x42, 0x0a, 0x0f, 0x65, 0x6e, 0x63, 0x72,
0x79, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x61, 0x6c, 0x67, 0x6f, 0x18, 0x05, 0x20, 0x01, 0x28,
0x0e, 0x32, 0x19, 0x2e, 0x62, 0x61, 0x64, 0x67, 0x65, 0x72, 0x70, 0x62, 0x34, 0x2e, 0x45, 0x6e,
0x63, 0x72, 0x79, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x41, 0x6c, 0x67, 0x6f, 0x52, 0x0e, 0x65, 0x6e,
0x63, 0x72, 0x79, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x41, 0x6c, 0x67, 0x6f, 0x12, 0x20, 0x0a, 0x0b,
0x63, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x06, 0x20, 0x01, 0x28,
0x0d, 0x52, 0x0b, 0x63, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0x23,
0x0a, 0x09, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x0a, 0x0a, 0x06, 0x43,
0x52, 0x45, 0x41, 0x54, 0x45, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x44, 0x45, 0x4c, 0x45, 0x54,
0x45, 0x10, 0x01, 0x22, 0x76, 0x0a, 0x08, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x73, 0x75, 0x6d, 0x12,
0x31, 0x0a, 0x04, 0x61, 0x6c, 0x67, 0x6f, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1d, 0x2e,
0x62, 0x61, 0x64, 0x67, 0x65, 0x72, 0x70, 0x62, 0x34, 0x2e, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x73,
0x75, 0x6d, 0x2e, 0x41, 0x6c, 0x67, 0x6f, 0x72, 0x69, 0x74, 0x68, 0x6d, 0x52, 0x04, 0x61, 0x6c,
0x67, 0x6f, 0x12, 0x10, 0x0a, 0x03, 0x73, 0x75, 0x6d, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52,
0x03, 0x73, 0x75, 0x6d, 0x22, 0x25, 0x0a, 0x09, 0x41, 0x6c, 0x67, 0x6f, 0x72, 0x69, 0x74, 0x68,
0x6d, 0x12, 0x0a, 0x0a, 0x06, 0x43, 0x52, 0x43, 0x33, 0x32, 0x43, 0x10, 0x00, 0x12, 0x0c, 0x0a,
0x08, 0x58, 0x58, 0x48, 0x61, 0x73, 0x68, 0x36, 0x34, 0x10, 0x01, 0x22, 0x63, 0x0a, 0x07, 0x44,
0x61, 0x74, 0x61, 0x4b, 0x65, 0x79, 0x12, 0x15, 0x0a, 0x06, 0x6b, 0x65, 0x79, 0x5f, 0x69, 0x64,
0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, 0x05, 0x6b, 0x65, 0x79, 0x49, 0x64, 0x12, 0x12, 0x0a,
0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x64, 0x61, 0x74,
0x61, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x76, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x69,
0x76, 0x12, 0x1d, 0x0a, 0x0a, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x18,
0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x41, 0x74,
0x22, 0x42, 0x0a, 0x05, 0x4d, 0x61, 0x74, 0x63, 0x68, 0x12, 0x16, 0x0a, 0x06, 0x70, 0x72, 0x65,
0x66, 0x69, 0x78, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x70, 0x72, 0x65, 0x66, 0x69,
0x78, 0x12, 0x21, 0x0a, 0x0c, 0x69, 0x67, 0x6e, 0x6f, 0x72, 0x65, 0x5f, 0x62, 0x79, 0x74, 0x65,
0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x69, 0x67, 0x6e, 0x6f, 0x72, 0x65, 0x42,
0x79, 0x74, 0x65, 0x73, 0x2a, 0x19, 0x0a, 0x0e, 0x45, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x69,
0x6f, 0x6e, 0x41, 0x6c, 0x67, 0x6f, 0x12, 0x07, 0x0a, 0x03, 0x61, 0x65, 0x73, 0x10, 0x00, 0x42,
0x23, 0x5a, 0x21, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x64, 0x67,
0x72, 0x61, 0x70, 0x68, 0x2d, 0x69, 0x6f, 0x2f, 0x62, 0x61, 0x64, 0x67, 0x65, 0x72, 0x2f, 0x76,
0x34, 0x2f, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_badgerpb4_proto_rawDescOnce sync.Once
file_badgerpb4_proto_rawDescData = file_badgerpb4_proto_rawDesc
)
func file_badgerpb4_proto_rawDescGZIP() []byte {
file_badgerpb4_proto_rawDescOnce.Do(func() {
file_badgerpb4_proto_rawDescData = protoimpl.X.CompressGZIP(file_badgerpb4_proto_rawDescData)
})
return file_badgerpb4_proto_rawDescData
}
var file_badgerpb4_proto_enumTypes = make([]protoimpl.EnumInfo, 3)
var file_badgerpb4_proto_msgTypes = make([]protoimpl.MessageInfo, 7)
var file_badgerpb4_proto_goTypes = []interface{}{
(EncryptionAlgo)(0), // 0: badgerpb4.EncryptionAlgo
(ManifestChange_Operation)(0), // 1: badgerpb4.ManifestChange.Operation
(Checksum_Algorithm)(0), // 2: badgerpb4.Checksum.Algorithm
(*KV)(nil), // 3: badgerpb4.KV
(*KVList)(nil), // 4: badgerpb4.KVList
(*ManifestChangeSet)(nil), // 5: badgerpb4.ManifestChangeSet
(*ManifestChange)(nil), // 6: badgerpb4.ManifestChange
(*Checksum)(nil), // 7: badgerpb4.Checksum
(*DataKey)(nil), // 8: badgerpb4.DataKey
(*Match)(nil), // 9: badgerpb4.Match
}
var file_badgerpb4_proto_depIdxs = []int32{
3, // 0: badgerpb4.KVList.kv:type_name -> badgerpb4.KV
6, // 1: badgerpb4.ManifestChangeSet.changes:type_name -> badgerpb4.ManifestChange
1, // 2: badgerpb4.ManifestChange.Op:type_name -> badgerpb4.ManifestChange.Operation
0, // 3: badgerpb4.ManifestChange.encryption_algo:type_name -> badgerpb4.EncryptionAlgo
2, // 4: badgerpb4.Checksum.algo:type_name -> badgerpb4.Checksum.Algorithm
5, // [5:5] is the sub-list for method output_type
5, // [5:5] is the sub-list for method input_type
5, // [5:5] is the sub-list for extension type_name
5, // [5:5] is the sub-list for extension extendee
0, // [0:5] is the sub-list for field type_name
}
func init() { file_badgerpb4_proto_init() }
func file_badgerpb4_proto_init() {
if File_badgerpb4_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_badgerpb4_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*KV); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_badgerpb4_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*KVList); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_badgerpb4_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*ManifestChangeSet); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_badgerpb4_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*ManifestChange); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_badgerpb4_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Checksum); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_badgerpb4_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*DataKey); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_badgerpb4_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Match); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_badgerpb4_proto_rawDesc,
NumEnums: 3,
NumMessages: 7,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_badgerpb4_proto_goTypes,
DependencyIndexes: file_badgerpb4_proto_depIdxs,
EnumInfos: file_badgerpb4_proto_enumTypes,
MessageInfos: file_badgerpb4_proto_msgTypes,
}.Build()
File_badgerpb4_proto = out.File
file_badgerpb4_proto_rawDesc = nil
file_badgerpb4_proto_goTypes = nil
file_badgerpb4_proto_depIdxs = nil
}
================================================
FILE: pb/badgerpb4.proto
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
// Use protos/gen.sh to generate .pb.go files.
syntax = "proto3";
package badgerpb4;
option go_package = "github.com/dgraph-io/badger/v4/pb";
message KV {
bytes key = 1;
bytes value = 2;
bytes user_meta = 3;
uint64 version = 4;
uint64 expires_at = 5;
bytes meta = 6;
// Stream id is used to identify which stream the KV came from.
uint32 stream_id = 10;
// Stream done is used to indicate end of stream.
bool stream_done = 11;
}
message KVList {
repeated KV kv = 1;
// alloc_ref used internally for memory management.
uint64 alloc_ref = 10;
}
message ManifestChangeSet {
// A set of changes that are applied atomically.
repeated ManifestChange changes = 1;
}
enum EncryptionAlgo {
aes = 0;
}
message ManifestChange {
uint64 Id = 1; // Table ID.
enum Operation {
CREATE = 0;
DELETE = 1;
}
Operation Op = 2;
uint32 Level = 3; // Only used for CREATE.
uint64 key_id = 4;
EncryptionAlgo encryption_algo = 5;
uint32 compression = 6; // Only used for CREATE Op.
}
message Checksum {
enum Algorithm {
CRC32C = 0;
XXHash64 = 1;
}
Algorithm algo = 1; // For storing type of Checksum algorithm used
uint64 sum = 2;
}
message DataKey {
uint64 key_id = 1;
bytes data = 2;
bytes iv = 3;
int64 created_at = 4;
}
message Match {
bytes prefix = 1;
string ignore_bytes = 2; // Comma separated with dash to represent ranges "1, 2-3, 4-7, 9"
}
================================================
FILE: pb/gen.sh
================================================
#!/bin/bash
# Run this script from its directory, so that badgerpb4.proto is where it's expected to
# be.
go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.31.0
protoc --go_out=. --go_opt=paths=source_relative badgerpb4.proto
================================================
FILE: pb/protos_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package pb
import (
"os/exec"
"testing"
"github.com/stretchr/testify/require"
)
func Exec(argv ...string) error {
cmd := exec.Command(argv[0], argv[1:]...)
if err := cmd.Start(); err != nil {
return err
}
return cmd.Wait()
}
func TestProtosRegenerate(t *testing.T) {
err := Exec("./gen.sh")
require.NoError(t, err, "Got error while regenerating protos: %v\n", err)
generatedProtos := "badgerpb4.pb.go"
err = Exec("git", "diff", "--quiet", "--", generatedProtos)
require.NoError(t, err, "badgerpb4.pb.go changed after regenerating")
}
================================================
FILE: publisher.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"sync"
"sync/atomic"
"github.com/dgraph-io/badger/v4/pb"
"github.com/dgraph-io/badger/v4/trie"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2/z"
)
type subscriber struct {
id uint64
matches []pb.Match
sendCh chan *pb.KVList
subCloser *z.Closer
// this will be atomic pointer which will be used to
// track whether the subscriber is active or not
active *atomic.Uint64
}
type publisher struct {
sync.Mutex
pubCh chan requests
subscribers map[uint64]subscriber
nextID uint64
indexer *trie.Trie
}
func newPublisher() *publisher {
return &publisher{
pubCh: make(chan requests, 1000),
subscribers: make(map[uint64]subscriber),
nextID: 0,
indexer: trie.NewTrie(),
}
}
func (p *publisher) listenForUpdates(c *z.Closer) {
defer func() {
p.cleanSubscribers()
c.Done()
}()
slurp := func(batch requests) {
for {
select {
case reqs := <-p.pubCh:
batch = append(batch, reqs...)
default:
p.publishUpdates(batch)
return
}
}
}
for {
select {
case <-c.HasBeenClosed():
return
case reqs := <-p.pubCh:
slurp(reqs)
}
}
}
func (p *publisher) publishUpdates(reqs requests) {
p.Lock()
defer func() {
p.Unlock()
// Release all the request.
reqs.DecrRef()
}()
batchedUpdates := make(map[uint64]*pb.KVList)
for _, req := range reqs {
for _, e := range req.Entries {
ids := p.indexer.Get(e.Key)
if len(ids) == 0 {
continue
}
k := y.SafeCopy(nil, e.Key)
kv := &pb.KV{
Key: y.ParseKey(k),
Value: y.SafeCopy(nil, e.Value),
Meta: []byte{e.UserMeta},
ExpiresAt: e.ExpiresAt,
Version: y.ParseTs(k),
}
for id := range ids {
if _, ok := batchedUpdates[id]; !ok {
batchedUpdates[id] = &pb.KVList{}
}
batchedUpdates[id].Kv = append(batchedUpdates[id].Kv, kv)
}
}
}
for id, kvs := range batchedUpdates {
if p.subscribers[id].active.Load() == 1 {
p.subscribers[id].sendCh <- kvs
}
}
}
func (p *publisher) newSubscriber(c *z.Closer, matches []pb.Match) (subscriber, error) {
p.Lock()
defer p.Unlock()
ch := make(chan *pb.KVList, 1000)
id := p.nextID
// Increment next ID.
p.nextID++
s := subscriber{
id: id,
matches: matches,
sendCh: ch,
subCloser: c,
active: new(atomic.Uint64),
}
s.active.Store(1)
p.subscribers[id] = s
for _, m := range matches {
if err := p.indexer.AddMatch(m, id); err != nil {
return subscriber{}, err
}
}
return s, nil
}
// cleanSubscribers stops all the subscribers. Ideally, It should be called while closing DB.
func (p *publisher) cleanSubscribers() {
p.Lock()
defer p.Unlock()
for id, s := range p.subscribers {
for _, m := range s.matches {
_ = p.indexer.DeleteMatch(m, id)
}
delete(p.subscribers, id)
s.subCloser.SignalAndWait()
}
}
func (p *publisher) deleteSubscriber(id uint64) {
p.Lock()
defer p.Unlock()
if s, ok := p.subscribers[id]; ok {
for _, m := range s.matches {
_ = p.indexer.DeleteMatch(m, id)
}
}
delete(p.subscribers, id)
}
func (p *publisher) sendUpdates(reqs requests) {
if p.noOfSubscribers() != 0 {
reqs.IncrRef()
p.pubCh <- reqs
}
}
func (p *publisher) noOfSubscribers() int {
p.Lock()
defer p.Unlock()
return len(p.subscribers)
}
================================================
FILE: publisher_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"context"
"errors"
"fmt"
"runtime"
"sync"
"sync/atomic"
"testing"
"github.com/stretchr/testify/require"
"github.com/dgraph-io/badger/v4/pb"
)
// This test will result in deadlock for commits before this.
// Exiting this test gracefully will be the proof that the
// publisher is no longer stuck in deadlock.
func TestPublisherDeadlock(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
var subWg sync.WaitGroup
subWg.Add(1)
var firstUpdate sync.WaitGroup
firstUpdate.Add(1)
var allUpdatesDone sync.WaitGroup
allUpdatesDone.Add(1)
var subDone sync.WaitGroup
subDone.Add(1)
go func() {
subWg.Done()
match := pb.Match{Prefix: []byte("ke"), IgnoreBytes: ""}
err := db.Subscribe(context.Background(), func(kvs *pb.KVList) error {
firstUpdate.Done()
// Before exiting Subscribe process, we will wait until each of the
// 1110 updates (defined below) have been completed.
allUpdatesDone.Wait()
return errors.New("error returned")
}, []pb.Match{match})
require.Error(t, err, errors.New("error returned"))
subDone.Done()
}()
subWg.Wait()
go func() {
err := db.Update(func(txn *Txn) error {
e := NewEntry([]byte(fmt.Sprintf("key%d", 0)), []byte(fmt.Sprintf("value%d", 0)))
return txn.SetEntry(e)
})
require.NoError(t, err)
}()
firstUpdate.Wait()
var req atomic.Int64
for i := 1; i < 1110; i++ {
go func(i int) {
err := db.Update(func(txn *Txn) error {
e := NewEntry([]byte(fmt.Sprintf("key%d", i)), []byte(fmt.Sprintf("value%d", i)))
return txn.SetEntry(e)
})
require.NoError(t, err)
req.Add(1)
}(i)
}
for {
if req.Load() == 1109 {
break
}
// FYI: This does the same as "thread.yield()" from other languages.
// In other words, it tells the go-routine scheduler to switch
// to another go-routine. This is strongly preferred over
// time.Sleep(...).
runtime.Gosched()
}
// Free up the subscriber, which is waiting for updates to finish.
allUpdatesDone.Done()
// Exit when the subscription process has been exited.
subDone.Wait()
})
}
func TestPublisherOrdering(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
order := []string{}
var wg sync.WaitGroup
wg.Add(1)
var subWg sync.WaitGroup
subWg.Add(1)
go func() {
subWg.Done()
updates := 0
match := pb.Match{Prefix: []byte("ke"), IgnoreBytes: ""}
err := db.Subscribe(context.Background(), func(kvs *pb.KVList) error {
updates += len(kvs.GetKv())
for _, kv := range kvs.GetKv() {
order = append(order, string(kv.Value))
}
if updates == 5 {
wg.Done()
}
return nil
}, []pb.Match{match})
if err != nil {
require.Equal(t, err.Error(), context.Canceled.Error())
}
}()
subWg.Wait()
for i := 0; i < 5; i++ {
require.NoError(t, db.Update(func(txn *Txn) error {
e := NewEntry([]byte(fmt.Sprintf("key%d", i)), []byte(fmt.Sprintf("value%d", i)))
return txn.SetEntry(e)
}))
}
wg.Wait()
for i := 0; i < 5; i++ {
require.Equal(t, fmt.Sprintf("value%d", i), order[i])
}
})
}
func TestMultiplePrefix(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
var wg sync.WaitGroup
wg.Add(1)
var subWg sync.WaitGroup
subWg.Add(1)
go func() {
subWg.Done()
updates := 0
match1 := pb.Match{Prefix: []byte("ke"), IgnoreBytes: ""}
match2 := pb.Match{Prefix: []byte("hel"), IgnoreBytes: ""}
err := db.Subscribe(context.Background(), func(kvs *pb.KVList) error {
updates += len(kvs.GetKv())
for _, kv := range kvs.GetKv() {
if string(kv.Key) == "key" {
require.Equal(t, string(kv.Value), "value")
} else {
require.Equal(t, string(kv.Value), "badger")
}
}
if updates == 2 {
wg.Done()
}
return nil
}, []pb.Match{match1, match2})
if err != nil {
require.Equal(t, err.Error(), context.Canceled.Error())
}
}()
subWg.Wait()
require.NoError(t, db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry([]byte("key"), []byte("value")))
}))
require.NoError(t, db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry([]byte("hello"), []byte("badger")))
}))
wg.Wait()
})
}
================================================
FILE: skl/README.md
================================================
This is much better than `skiplist` and `slist`.
```sh
BenchmarkReadWrite/frac_0-8 3000000 537 ns/op
BenchmarkReadWrite/frac_1-8 3000000 503 ns/op
BenchmarkReadWrite/frac_2-8 3000000 492 ns/op
BenchmarkReadWrite/frac_3-8 3000000 475 ns/op
BenchmarkReadWrite/frac_4-8 3000000 440 ns/op
BenchmarkReadWrite/frac_5-8 5000000 442 ns/op
BenchmarkReadWrite/frac_6-8 5000000 380 ns/op
BenchmarkReadWrite/frac_7-8 5000000 338 ns/op
BenchmarkReadWrite/frac_8-8 5000000 294 ns/op
BenchmarkReadWrite/frac_9-8 10000000 268 ns/op
BenchmarkReadWrite/frac_10-8 100000000 26.3 ns/op
```
And even better than a simple map with read-write lock:
```sh
BenchmarkReadWriteMap/frac_0-8 2000000 774 ns/op
BenchmarkReadWriteMap/frac_1-8 2000000 647 ns/op
BenchmarkReadWriteMap/frac_2-8 3000000 605 ns/op
BenchmarkReadWriteMap/frac_3-8 3000000 603 ns/op
BenchmarkReadWriteMap/frac_4-8 3000000 556 ns/op
BenchmarkReadWriteMap/frac_5-8 3000000 472 ns/op
BenchmarkReadWriteMap/frac_6-8 3000000 476 ns/op
BenchmarkReadWriteMap/frac_7-8 3000000 457 ns/op
BenchmarkReadWriteMap/frac_8-8 5000000 444 ns/op
BenchmarkReadWriteMap/frac_9-8 5000000 361 ns/op
BenchmarkReadWriteMap/frac_10-8 10000000 212 ns/op
```
# Node Pooling
Command used
```sh
rm -Rf tmp && /usr/bin/time -l ./populate -keys_mil 10
```
For pprof results, we run without using /usr/bin/time. There are four runs below.
Results seem to vary quite a bit between runs.
## Before node pooling
```sh
1311.53MB of 1338.69MB total (97.97%)
Dropped 30 nodes (cum <= 6.69MB)
Showing top 10 nodes out of 37 (cum >= 12.50MB)
flat flat% sum% cum cum%
523.04MB 39.07% 39.07% 523.04MB 39.07% github.com/dgraph-io/badger/skl.(*Skiplist).Put
184.51MB 13.78% 52.85% 184.51MB 13.78% runtime.stringtoslicebyte
166.01MB 12.40% 65.25% 689.04MB 51.47% github.com/dgraph-io/badger/mem.(*Table).Put
165MB 12.33% 77.58% 165MB 12.33% runtime.convT2E
116.92MB 8.73% 86.31% 116.92MB 8.73% bytes.makeSlice
62.50MB 4.67% 90.98% 62.50MB 4.67% main.newValue
34.50MB 2.58% 93.56% 34.50MB 2.58% github.com/dgraph-io/badger/table.(*BlockIterator).parseKV
25.50MB 1.90% 95.46% 100.06MB 7.47% github.com/dgraph-io/badger/y.(*MergeIterator).Next
21.06MB 1.57% 97.04% 21.06MB 1.57% github.com/dgraph-io/badger/table.(*Table).read
12.50MB 0.93% 97.97% 12.50MB 0.93% github.com/dgraph-io/badger/table.header.Encode
128.31 real 329.37 user 17.11 sys
3355660288 maximum resident set size
0 average shared memory size
0 average unshared data size
0 average unshared stack size
2203080 page reclaims
764 page faults
0 swaps
275 block input operations
76 block output operations
0 messages sent
0 messages received
0 signals received
49173 voluntary context switches
599922 involuntary context switches
```
## After node pooling
```sh
1963.13MB of 2026.09MB total (96.89%)
Dropped 29 nodes (cum <= 10.13MB)
Showing top 10 nodes out of 41 (cum >= 185.62MB)
flat flat% sum% cum cum%
658.05MB 32.48% 32.48% 658.05MB 32.48% github.com/dgraph-io/badger/skl.glob..func1
297.51MB 14.68% 47.16% 297.51MB 14.68% runtime.convT2E
257.51MB 12.71% 59.87% 257.51MB 12.71% runtime.stringtoslicebyte
249.01MB 12.29% 72.16% 1007.06MB 49.70% github.com/dgraph-io/badger/mem.(*Table).Put
142.43MB 7.03% 79.19% 142.43MB 7.03% bytes.makeSlice
100MB 4.94% 84.13% 758.05MB 37.41% github.com/dgraph-io/badger/skl.newNode
99.50MB 4.91% 89.04% 99.50MB 4.91% main.newValue
75MB 3.70% 92.74% 75MB 3.70% github.com/dgraph-io/badger/table.(*BlockIterator).parseKV
44.62MB 2.20% 94.94% 44.62MB 2.20% github.com/dgraph-io/badger/table.(*Table).read
39.50MB 1.95% 96.89% 185.62MB 9.16% github.com/dgraph-io/badger/y.(*MergeIterator).Next
135.58 real 374.29 user 17.65 sys
3740614656 maximum resident set size
0 average shared memory size
0 average unshared data size
0 average unshared stack size
2276566 page reclaims
770 page faults
0 swaps
128 block input operations
90 block output operations
0 messages sent
0 messages received
0 signals received
46434 voluntary context switches
597049 involuntary context switches
```
================================================
FILE: skl/arena.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package skl
import (
"sync/atomic"
"unsafe"
"github.com/dgraph-io/badger/v4/y"
)
const (
offsetSize = int(unsafe.Sizeof(uint32(0)))
// Always align nodes on 64-bit boundaries, even on 32-bit architectures,
// so that the node.value field is 64-bit aligned. This is necessary because
// node.getValueOffset uses atomic.LoadUint64, which expects its input
// pointer to be 64-bit aligned.
nodeAlign = int(unsafe.Sizeof(uint64(0))) - 1
)
// Arena should be lock-free.
type Arena struct {
n atomic.Uint32
buf []byte
}
// newArena returns a new arena.
func newArena(n int64) *Arena {
// Don't store data at position 0 in order to reserve offset=0 as a kind
// of nil pointer.
out := &Arena{buf: make([]byte, n)}
out.n.Store(1)
return out
}
func (s *Arena) size() int64 {
return int64(s.n.Load())
}
// putNode allocates a node in the arena. The node is aligned on a pointer-sized
// boundary. The arena offset of the node is returned.
func (s *Arena) putNode(height int) uint32 {
// Compute the amount of the tower that will never be used, since the height
// is less than maxHeight.
unusedSize := (maxHeight - height) * offsetSize
// Pad the allocation with enough bytes to ensure pointer alignment.
l := uint32(MaxNodeSize - unusedSize + nodeAlign)
n := s.n.Add(l)
y.AssertTruef(int(n) <= len(s.buf),
"Arena too small, toWrite:%d newTotal:%d limit:%d",
l, n, len(s.buf))
// Return the aligned offset.
m := (n - l + uint32(nodeAlign)) & ^uint32(nodeAlign)
return m
}
// Put will *copy* val into arena. To make better use of this, reuse your input
// val buffer. Returns an offset into buf. User is responsible for remembering
// size of val. We could also store this size inside arena but the encoding and
// decoding will incur some overhead.
func (s *Arena) putVal(v y.ValueStruct) uint32 {
l := v.EncodedSize()
n := s.n.Add(l)
y.AssertTruef(int(n) <= len(s.buf),
"Arena too small, toWrite:%d newTotal:%d limit:%d",
l, n, len(s.buf))
m := n - l
v.Encode(s.buf[m:])
return m
}
func (s *Arena) putKey(key []byte) uint32 {
l := uint32(len(key))
n := s.n.Add(l)
y.AssertTruef(int(n) <= len(s.buf),
"Arena too small, toWrite:%d newTotal:%d limit:%d",
l, n, len(s.buf))
// m is the offset where you should write.
// n = new len - key len give you the offset at which you should write.
m := n - l
// Copy to buffer from m:n
y.AssertTrue(len(key) == copy(s.buf[m:n], key))
return m
}
// getNode returns a pointer to the node located at offset. If the offset is
// zero, then the nil node pointer is returned.
func (s *Arena) getNode(offset uint32) *node {
if offset == 0 {
return nil
}
return (*node)(unsafe.Pointer(&s.buf[offset]))
}
// getKey returns byte slice at offset.
func (s *Arena) getKey(offset uint32, size uint16) []byte {
return s.buf[offset : offset+uint32(size)]
}
// getVal returns byte slice at offset. The given size should be just the value
// size and should NOT include the meta bytes.
func (s *Arena) getVal(offset uint32, size uint32) (ret y.ValueStruct) {
ret.Decode(s.buf[offset : offset+size])
return
}
// getNodeOffset returns the offset of node in the arena. If the node pointer is
// nil, then the zero offset is returned.
func (s *Arena) getNodeOffset(nd *node) uint32 {
if nd == nil {
return 0
}
return uint32(uintptr(unsafe.Pointer(nd)) - uintptr(unsafe.Pointer(&s.buf[0])))
}
================================================
FILE: skl/skl.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
/*
Adapted from RocksDB inline skiplist.
Key differences:
- No optimization for sequential inserts (no "prev").
- No custom comparator.
- Support overwrites. This requires care when we see the same key when inserting.
For RocksDB or LevelDB, overwrites are implemented as a newer sequence number in the key, so
there is no need for values. We don't intend to support versioning. In-place updates of values
would be more efficient.
- We discard all non-concurrent code.
- We do not support Splices. This simplifies the code a lot.
- No AllocateNode or other pointer arithmetic.
- We combine the findLessThan, findGreaterOrEqual, etc into one function.
*/
package skl
import (
"math"
"sync/atomic"
"unsafe"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2/z"
)
const (
maxHeight = 20
heightIncrease = math.MaxUint32 / 3
)
// MaxNodeSize is the memory footprint of a node of maximum height.
const MaxNodeSize = int(unsafe.Sizeof(node{}))
type node struct {
// Multiple parts of the value are encoded as a single uint64 so that it
// can be atomically loaded and stored:
// value offset: uint32 (bits 0-31)
// value size : uint32 (bits 32-63)
value atomic.Uint64
// A byte slice is 24 bytes. We are trying to save space here.
keyOffset uint32 // Immutable. No need to lock to access key.
keySize uint16 // Immutable. No need to lock to access key.
// Height of the tower.
height uint16
// Most nodes do not need to use the full height of the tower, since the
// probability of each successive level decreases exponentially. Because
// these elements are never accessed, they do not need to be allocated.
// Therefore, when a node is allocated in the arena, its memory footprint
// is deliberately truncated to not include unneeded tower elements.
//
// All accesses to elements should use CAS operations, with no need to lock.
tower [maxHeight]atomic.Uint32
}
type Skiplist struct {
height atomic.Int32 // Current height. 1 <= height <= kMaxHeight. CAS.
head *node
ref atomic.Int32
arena *Arena
OnClose func()
}
// IncrRef increases the refcount
func (s *Skiplist) IncrRef() {
s.ref.Add(1)
}
// DecrRef decrements the refcount, deallocating the Skiplist when done using it
func (s *Skiplist) DecrRef() {
newRef := s.ref.Add(-1)
if newRef > 0 {
return
}
if s.OnClose != nil {
s.OnClose()
}
// Indicate we are closed. Good for testing. Also, lets GC reclaim memory. Race condition
// here would suggest we are accessing skiplist when we are supposed to have no reference!
s.arena = nil
// Since the head references the arena's buf, as long as the head is kept around
// GC can't release the buf.
s.head = nil
}
func newNode(arena *Arena, key []byte, v y.ValueStruct, height int) *node {
// The base level is already allocated in the node struct.
offset := arena.putNode(height)
node := arena.getNode(offset)
node.keyOffset = arena.putKey(key)
node.keySize = uint16(len(key))
node.height = uint16(height)
node.value.Store(encodeValue(arena.putVal(v), v.EncodedSize()))
return node
}
func encodeValue(valOffset uint32, valSize uint32) uint64 {
return uint64(valSize)<<32 | uint64(valOffset)
}
func decodeValue(value uint64) (valOffset uint32, valSize uint32) {
valOffset = uint32(value)
valSize = uint32(value >> 32)
return
}
// NewSkiplist makes a new empty skiplist, with a given arena size
func NewSkiplist(arenaSize int64) *Skiplist {
arena := newArena(arenaSize)
head := newNode(arena, nil, y.ValueStruct{}, maxHeight)
s := &Skiplist{head: head, arena: arena}
s.height.Store(1)
s.ref.Store(1)
return s
}
func (s *node) getValueOffset() (uint32, uint32) {
value := s.value.Load()
return decodeValue(value)
}
func (s *node) key(arena *Arena) []byte {
return arena.getKey(s.keyOffset, s.keySize)
}
func (s *node) setValue(arena *Arena, v y.ValueStruct) {
valOffset := arena.putVal(v)
value := encodeValue(valOffset, v.EncodedSize())
s.value.Store(value)
}
func (s *node) getNextOffset(h int) uint32 {
return s.tower[h].Load()
}
func (s *node) casNextOffset(h int, old, val uint32) bool {
return s.tower[h].CompareAndSwap(old, val)
}
// Returns true if key is strictly > n.key.
// If n is nil, this is an "end" marker and we return false.
//func (s *Skiplist) keyIsAfterNode(key []byte, n *node) bool {
// y.AssertTrue(n != s.head)
// return n != nil && y.CompareKeys(key, n.key) > 0
//}
func (s *Skiplist) randomHeight() int {
h := 1
for h < maxHeight && z.FastRand() <= heightIncrease {
h++
}
return h
}
func (s *Skiplist) getNext(nd *node, height int) *node {
return s.arena.getNode(nd.getNextOffset(height))
}
// findNear finds the node near to key.
// If less=true, it finds rightmost node such that node.key < key (if allowEqual=false) or
// node.key <= key (if allowEqual=true).
// If less=false, it finds leftmost node such that node.key > key (if allowEqual=false) or
// node.key >= key (if allowEqual=true).
// Returns the node found. The bool returned is true if the node has key equal to given key.
func (s *Skiplist) findNear(key []byte, less bool, allowEqual bool) (*node, bool) {
x := s.head
level := int(s.getHeight() - 1)
for {
// Assume x.key < key.
next := s.getNext(x, level)
if next == nil {
// x.key < key < END OF LIST
if level > 0 {
// Can descend further to iterate closer to the end.
level--
continue
}
// Level=0. Cannot descend further. Let's return something that makes sense.
if !less {
return nil, false
}
// Try to return x. Make sure it is not a head node.
if x == s.head {
return nil, false
}
return x, false
}
nextKey := next.key(s.arena)
cmp := y.CompareKeys(key, nextKey)
if cmp > 0 {
// x.key < next.key < key. We can continue to move right.
x = next
continue
}
if cmp == 0 {
// x.key < key == next.key.
if allowEqual {
return next, true
}
if !less {
// We want >, so go to base level to grab the next bigger note.
return s.getNext(next, 0), false
}
// We want <. If not base level, we should go closer in the next level.
if level > 0 {
level--
continue
}
// On base level. Return x.
if x == s.head {
return nil, false
}
return x, false
}
// cmp < 0. In other words, x.key < key < next.
if level > 0 {
level--
continue
}
// At base level. Need to return something.
if !less {
return next, false
}
// Try to return x. Make sure it is not a head node.
if x == s.head {
return nil, false
}
return x, false
}
}
// findSpliceForLevel returns (outBefore, outAfter) with outBefore.key <= key <= outAfter.key.
// The input "before" tells us where to start looking.
// If we found a node with the same key, then we return outBefore = outAfter.
// Otherwise, outBefore.key < key < outAfter.key.
func (s *Skiplist) findSpliceForLevel(key []byte, before *node, level int) (*node, *node) {
for {
// Assume before.key < key.
next := s.getNext(before, level)
if next == nil {
return before, next
}
nextKey := next.key(s.arena)
cmp := y.CompareKeys(key, nextKey)
if cmp == 0 {
// Equality case.
return next, next
}
if cmp < 0 {
// before.key < key < next.key. We are done for this level.
return before, next
}
before = next // Keep moving right on this level.
}
}
func (s *Skiplist) getHeight() int32 {
return s.height.Load()
}
// Put inserts the key-value pair.
func (s *Skiplist) Put(key []byte, v y.ValueStruct) {
// Since we allow overwrite, we may not need to create a new node. We might not even need to
// increase the height. Let's defer these actions.
listHeight := s.getHeight()
var prev [maxHeight + 1]*node
var next [maxHeight + 1]*node
prev[listHeight] = s.head
next[listHeight] = nil
for i := int(listHeight) - 1; i >= 0; i-- {
// Use higher level to speed up for current level.
prev[i], next[i] = s.findSpliceForLevel(key, prev[i+1], i)
if prev[i] == next[i] {
prev[i].setValue(s.arena, v)
return
}
}
// We do need to create a new node.
height := s.randomHeight()
x := newNode(s.arena, key, v, height)
// Try to increase s.height via CAS.
listHeight = s.getHeight()
for height > int(listHeight) {
if s.height.CompareAndSwap(listHeight, int32(height)) {
// Successfully increased skiplist.height.
break
}
listHeight = s.getHeight()
}
// We always insert from the base level and up. After you add a node in base level, we cannot
// create a node in the level above because it would have discovered the node in the base level.
for i := 0; i < height; i++ {
for {
if prev[i] == nil {
y.AssertTrue(i > 1) // This cannot happen in base level.
// We haven't computed prev, next for this level because height exceeds old listHeight.
// For these levels, we expect the lists to be sparse, so we can just search from head.
prev[i], next[i] = s.findSpliceForLevel(key, s.head, i)
// Someone adds the exact same key before we are able to do so. This can only happen on
// the base level. But we know we are not on the base level.
y.AssertTrue(prev[i] != next[i])
}
nextOffset := s.arena.getNodeOffset(next[i])
x.tower[i].Store(nextOffset)
if prev[i].casNextOffset(i, nextOffset, s.arena.getNodeOffset(x)) {
// Managed to insert x between prev[i] and next[i]. Go to the next level.
break
}
// CAS failed. We need to recompute prev and next.
// It is unlikely to be helpful to try to use a different level as we redo the search,
// because it is unlikely that lots of nodes are inserted between prev[i] and next[i].
prev[i], next[i] = s.findSpliceForLevel(key, prev[i], i)
if prev[i] == next[i] {
y.AssertTruef(i == 0, "Equality can happen only on base level: %d", i)
prev[i].setValue(s.arena, v)
return
}
}
}
}
// Empty returns if the Skiplist is empty.
func (s *Skiplist) Empty() bool {
return s.findLast() == nil
}
// findLast returns the last element. If head (empty list), we return nil. All the find functions
// will NEVER return the head nodes.
func (s *Skiplist) findLast() *node {
n := s.head
level := int(s.getHeight()) - 1
for {
next := s.getNext(n, level)
if next != nil {
n = next
continue
}
if level == 0 {
if n == s.head {
return nil
}
return n
}
level--
}
}
// Get gets the value associated with the key. It returns a valid value if it finds equal or earlier
// version of the same key.
func (s *Skiplist) Get(key []byte) y.ValueStruct {
n, _ := s.findNear(key, false, true) // findGreaterOrEqual.
if n == nil {
return y.ValueStruct{}
}
nextKey := s.arena.getKey(n.keyOffset, n.keySize)
if !y.SameKey(key, nextKey) {
return y.ValueStruct{}
}
valOffset, valSize := n.getValueOffset()
vs := s.arena.getVal(valOffset, valSize)
vs.Version = y.ParseTs(nextKey)
return vs
}
// NewIterator returns a skiplist iterator. You have to Close() the iterator.
func (s *Skiplist) NewIterator() *Iterator {
s.IncrRef()
return &Iterator{list: s}
}
// MemSize returns the size of the Skiplist in terms of how much memory is used within its internal
// arena.
func (s *Skiplist) MemSize() int64 { return s.arena.size() }
// Iterator is an iterator over skiplist object. For new objects, you just
// need to initialize Iterator.list.
type Iterator struct {
list *Skiplist
n *node
}
// Close frees the resources held by the iterator
func (s *Iterator) Close() error {
s.list.DecrRef()
return nil
}
// Valid returns true iff the iterator is positioned at a valid node.
func (s *Iterator) Valid() bool { return s.n != nil }
// Key returns the key at the current position.
func (s *Iterator) Key() []byte {
return s.list.arena.getKey(s.n.keyOffset, s.n.keySize)
}
// Value returns value.
func (s *Iterator) Value() y.ValueStruct {
valOffset, valSize := s.n.getValueOffset()
return s.list.arena.getVal(valOffset, valSize)
}
// ValueUint64 returns the uint64 value of the current node.
func (s *Iterator) ValueUint64() uint64 {
return s.n.value.Load()
}
// Next advances to the next position.
func (s *Iterator) Next() {
y.AssertTrue(s.Valid())
s.n = s.list.getNext(s.n, 0)
}
// Prev advances to the previous position.
func (s *Iterator) Prev() {
y.AssertTrue(s.Valid())
s.n, _ = s.list.findNear(s.Key(), true, false) // find <. No equality allowed.
}
// Seek advances to the first entry with a key >= target.
func (s *Iterator) Seek(target []byte) {
s.n, _ = s.list.findNear(target, false, true) // find >=.
}
// SeekForPrev finds an entry with key <= target.
func (s *Iterator) SeekForPrev(target []byte) {
s.n, _ = s.list.findNear(target, true, true) // find <=.
}
// SeekToFirst seeks position at the first entry in list.
// Final state of iterator is Valid() iff list is not empty.
func (s *Iterator) SeekToFirst() {
s.n = s.list.getNext(s.list.head, 0)
}
// SeekToLast seeks position at the last entry in list.
// Final state of iterator is Valid() iff list is not empty.
func (s *Iterator) SeekToLast() {
s.n = s.list.findLast()
}
// UniIterator is a unidirectional memtable iterator. It is a thin wrapper around
// Iterator. We like to keep Iterator as before, because it is more powerful and
// we might support bidirectional iterators in the future.
type UniIterator struct {
iter *Iterator
reversed bool
}
// NewUniIterator returns a UniIterator.
func (s *Skiplist) NewUniIterator(reversed bool) *UniIterator {
return &UniIterator{
iter: s.NewIterator(),
reversed: reversed,
}
}
// Next implements y.Interface
func (s *UniIterator) Next() {
if !s.reversed {
s.iter.Next()
} else {
s.iter.Prev()
}
}
// Rewind implements y.Interface
func (s *UniIterator) Rewind() {
if !s.reversed {
s.iter.SeekToFirst()
} else {
s.iter.SeekToLast()
}
}
// Seek implements y.Interface
func (s *UniIterator) Seek(key []byte) {
if !s.reversed {
s.iter.Seek(key)
} else {
s.iter.SeekForPrev(key)
}
}
// Key implements y.Interface
func (s *UniIterator) Key() []byte { return s.iter.Key() }
// Value implements y.Interface
func (s *UniIterator) Value() y.ValueStruct { return s.iter.Value() }
// Valid implements y.Interface
func (s *UniIterator) Valid() bool { return s.iter.Valid() }
// Close implements y.Interface (and frees up the iter's resources)
func (s *UniIterator) Close() error { return s.iter.Close() }
================================================
FILE: skl/skl_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package skl
import (
"encoding/binary"
"fmt"
"math/rand"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/dgraph-io/badger/v4/y"
)
const arenaSize = 1 << 20
func (s *Skiplist) valid() bool { return s.arena != nil }
func newValue(v int) []byte {
return []byte(fmt.Sprintf("%05d", v))
}
// length iterates over skiplist to give exact size.
func length(s *Skiplist) int {
x := s.getNext(s.head, 0)
count := 0
for x != nil {
count++
x = s.getNext(x, 0)
}
return count
}
func TestEmpty(t *testing.T) {
key := []byte("aaa")
l := NewSkiplist(arenaSize)
v := l.Get(key)
require.True(t, v.Value == nil) // Cannot use require.Nil for unsafe.Pointer nil.
for _, less := range []bool{true, false} {
for _, allowEqual := range []bool{true, false} {
n, found := l.findNear(key, less, allowEqual)
require.Nil(t, n)
require.False(t, found)
}
}
it := l.NewIterator()
require.False(t, it.Valid())
it.SeekToFirst()
require.False(t, it.Valid())
it.SeekToLast()
require.False(t, it.Valid())
it.Seek(key)
require.False(t, it.Valid())
l.DecrRef()
require.True(t, l.valid()) // Check the reference counting.
it.Close()
require.False(t, l.valid()) // Check the reference counting.
}
// TestBasic tests single-threaded inserts and updates and gets.
func TestBasic(t *testing.T) {
l := NewSkiplist(arenaSize)
val1 := newValue(42)
val2 := newValue(52)
val3 := newValue(62)
val4 := newValue(72)
val5 := []byte(fmt.Sprintf("%0102400d", 1)) // Have size 100 KB which is > math.MaxUint16.
// Try inserting values.
// Somehow require.Nil doesn't work when checking for unsafe.Pointer(nil).
l.Put(y.KeyWithTs([]byte("key1"), 0), y.ValueStruct{Value: val1, Meta: 55, UserMeta: 0})
l.Put(y.KeyWithTs([]byte("key2"), 2), y.ValueStruct{Value: val2, Meta: 56, UserMeta: 0})
l.Put(y.KeyWithTs([]byte("key3"), 0), y.ValueStruct{Value: val3, Meta: 57, UserMeta: 0})
v := l.Get(y.KeyWithTs([]byte("key"), 0))
require.True(t, v.Value == nil)
v = l.Get(y.KeyWithTs([]byte("key1"), 0))
require.True(t, v.Value != nil)
require.EqualValues(t, "00042", string(v.Value))
require.EqualValues(t, 55, v.Meta)
v = l.Get(y.KeyWithTs([]byte("key2"), 0))
require.True(t, v.Value == nil)
v = l.Get(y.KeyWithTs([]byte("key3"), 0))
require.True(t, v.Value != nil)
require.EqualValues(t, "00062", string(v.Value))
require.EqualValues(t, 57, v.Meta)
l.Put(y.KeyWithTs([]byte("key3"), 1), y.ValueStruct{Value: val4, Meta: 12, UserMeta: 0})
v = l.Get(y.KeyWithTs([]byte("key3"), 1))
require.True(t, v.Value != nil)
require.EqualValues(t, "00072", string(v.Value))
require.EqualValues(t, 12, v.Meta)
l.Put(y.KeyWithTs([]byte("key4"), 1), y.ValueStruct{Value: val5, Meta: 60, UserMeta: 0})
v = l.Get(y.KeyWithTs([]byte("key4"), 1))
require.NotNil(t, v.Value)
require.EqualValues(t, val5, v.Value)
require.EqualValues(t, 60, v.Meta)
}
// TestConcurrentBasic tests concurrent writes followed by concurrent reads.
func TestConcurrentBasic(t *testing.T) {
const n = 1000
l := NewSkiplist(arenaSize)
var wg sync.WaitGroup
key := func(i int) []byte {
return y.KeyWithTs([]byte(fmt.Sprintf("%05d", i)), 0)
}
for i := 0; i < n; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
l.Put(key(i),
y.ValueStruct{Value: newValue(i), Meta: 0, UserMeta: 0})
}(i)
}
wg.Wait()
// Check values. Concurrent reads.
for i := 0; i < n; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
v := l.Get(key(i))
require.True(t, v.Value != nil)
require.EqualValues(t, newValue(i), v.Value)
}(i)
}
wg.Wait()
require.EqualValues(t, n, length(l))
}
func TestConcurrentBasicBigValues(t *testing.T) {
const n = 100
arenaSize := int64(120 << 20) // 120 MB
l := NewSkiplist(arenaSize)
var wg sync.WaitGroup
key := func(i int) []byte {
return y.KeyWithTs([]byte(fmt.Sprintf("%05d", i)), 0)
}
BigValue := func(i int) []byte {
return []byte(fmt.Sprintf("%01048576d", i)) // Have 1 MB value which is > math.MaxUint16.
}
for i := 0; i < n; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
l.Put(key(i),
y.ValueStruct{Value: BigValue(i), Meta: 0, UserMeta: 0})
}(i)
}
wg.Wait()
// Check values. Concurrent reads.
for i := 0; i < n; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
v := l.Get(key(i))
require.NotNil(t, v.Value)
require.EqualValues(t, BigValue(i), v.Value)
}(i)
}
wg.Wait()
require.EqualValues(t, n, length(l))
}
// TestOneKey will read while writing to one single key.
func TestOneKey(t *testing.T) {
const n = 100
key := y.KeyWithTs([]byte("thekey"), 0)
l := NewSkiplist(arenaSize)
defer l.DecrRef()
var wg sync.WaitGroup
for i := 0; i < n; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
l.Put(key, y.ValueStruct{Value: newValue(i), Meta: 0, UserMeta: 0})
}(i)
}
// We expect that at least some write made it such that some read returns a value.
var sawValue atomic.Int32
for i := 0; i < n; i++ {
wg.Add(1)
go func() {
defer wg.Done()
p := l.Get(key)
if p.Value == nil {
return
}
sawValue.Add(1)
v, err := strconv.Atoi(string(p.Value))
require.NoError(t, err)
require.True(t, 0 <= v && v < n, fmt.Sprintf("invalid value %d", v))
}()
}
wg.Wait()
require.True(t, sawValue.Load() > 0)
require.EqualValues(t, 1, length(l))
}
func TestFindNear(t *testing.T) {
l := NewSkiplist(arenaSize)
defer l.DecrRef()
for i := 0; i < 1000; i++ {
key := fmt.Sprintf("%05d", i*10+5)
l.Put(y.KeyWithTs([]byte(key), 0), y.ValueStruct{Value: newValue(i), Meta: 0, UserMeta: 0})
}
n, eq := l.findNear(y.KeyWithTs([]byte("00001"), 0), false, false)
require.NotNil(t, n)
require.EqualValues(t, y.KeyWithTs([]byte("00005"), 0), string(n.key(l.arena)))
require.False(t, eq)
n, eq = l.findNear(y.KeyWithTs([]byte("00001"), 0), false, true)
require.NotNil(t, n)
require.EqualValues(t, y.KeyWithTs([]byte("00005"), 0), string(n.key(l.arena)))
require.False(t, eq)
n, eq = l.findNear(y.KeyWithTs([]byte("00001"), 0), true, false)
require.Nil(t, n)
require.False(t, eq)
n, eq = l.findNear(y.KeyWithTs([]byte("00001"), 0), true, true)
require.Nil(t, n)
require.False(t, eq)
n, eq = l.findNear(y.KeyWithTs([]byte("00005"), 0), false, false)
require.NotNil(t, n)
require.EqualValues(t, y.KeyWithTs([]byte("00015"), 0), string(n.key(l.arena)))
require.False(t, eq)
n, eq = l.findNear(y.KeyWithTs([]byte("00005"), 0), false, true)
require.NotNil(t, n)
require.EqualValues(t, y.KeyWithTs([]byte("00005"), 0), string(n.key(l.arena)))
require.True(t, eq)
n, eq = l.findNear(y.KeyWithTs([]byte("00005"), 0), true, false)
require.Nil(t, n)
require.False(t, eq)
n, eq = l.findNear(y.KeyWithTs([]byte("00005"), 0), true, true)
require.NotNil(t, n)
require.EqualValues(t, y.KeyWithTs([]byte("00005"), 0), string(n.key(l.arena)))
require.True(t, eq)
n, eq = l.findNear(y.KeyWithTs([]byte("05555"), 0), false, false)
require.NotNil(t, n)
require.EqualValues(t, y.KeyWithTs([]byte("05565"), 0), string(n.key(l.arena)))
require.False(t, eq)
n, eq = l.findNear(y.KeyWithTs([]byte("05555"), 0), false, true)
require.NotNil(t, n)
require.EqualValues(t, y.KeyWithTs([]byte("05555"), 0), string(n.key(l.arena)))
require.True(t, eq)
n, eq = l.findNear(y.KeyWithTs([]byte("05555"), 0), true, false)
require.NotNil(t, n)
require.EqualValues(t, y.KeyWithTs([]byte("05545"), 0), string(n.key(l.arena)))
require.False(t, eq)
n, eq = l.findNear(y.KeyWithTs([]byte("05555"), 0), true, true)
require.NotNil(t, n)
require.EqualValues(t, y.KeyWithTs([]byte("05555"), 0), string(n.key(l.arena)))
require.True(t, eq)
n, eq = l.findNear(y.KeyWithTs([]byte("05558"), 0), false, false)
require.NotNil(t, n)
require.EqualValues(t, y.KeyWithTs([]byte("05565"), 0), string(n.key(l.arena)))
require.False(t, eq)
n, eq = l.findNear(y.KeyWithTs([]byte("05558"), 0), false, true)
require.NotNil(t, n)
require.EqualValues(t, y.KeyWithTs([]byte("05565"), 0), string(n.key(l.arena)))
require.False(t, eq)
n, eq = l.findNear(y.KeyWithTs([]byte("05558"), 0), true, false)
require.NotNil(t, n)
require.EqualValues(t, y.KeyWithTs([]byte("05555"), 0), string(n.key(l.arena)))
require.False(t, eq)
n, eq = l.findNear(y.KeyWithTs([]byte("05558"), 0), true, true)
require.NotNil(t, n)
require.EqualValues(t, y.KeyWithTs([]byte("05555"), 0), string(n.key(l.arena)))
require.False(t, eq)
n, eq = l.findNear(y.KeyWithTs([]byte("09995"), 0), false, false)
require.Nil(t, n)
require.False(t, eq)
n, eq = l.findNear(y.KeyWithTs([]byte("09995"), 0), false, true)
require.NotNil(t, n)
require.EqualValues(t, y.KeyWithTs([]byte("09995"), 0), string(n.key(l.arena)))
require.True(t, eq)
n, eq = l.findNear(y.KeyWithTs([]byte("09995"), 0), true, false)
require.NotNil(t, n)
require.EqualValues(t, y.KeyWithTs([]byte("09985"), 0), string(n.key(l.arena)))
require.False(t, eq)
n, eq = l.findNear(y.KeyWithTs([]byte("09995"), 0), true, true)
require.NotNil(t, n)
require.EqualValues(t, y.KeyWithTs([]byte("09995"), 0), string(n.key(l.arena)))
require.True(t, eq)
n, eq = l.findNear(y.KeyWithTs([]byte("59995"), 0), false, false)
require.Nil(t, n)
require.False(t, eq)
n, eq = l.findNear(y.KeyWithTs([]byte("59995"), 0), false, true)
require.Nil(t, n)
require.False(t, eq)
n, eq = l.findNear(y.KeyWithTs([]byte("59995"), 0), true, false)
require.NotNil(t, n)
require.EqualValues(t, y.KeyWithTs([]byte("09995"), 0), string(n.key(l.arena)))
require.False(t, eq)
n, eq = l.findNear(y.KeyWithTs([]byte("59995"), 0), true, true)
require.NotNil(t, n)
require.EqualValues(t, y.KeyWithTs([]byte("09995"), 0), string(n.key(l.arena)))
require.False(t, eq)
}
// TestIteratorNext tests a basic iteration over all nodes from the beginning.
func TestIteratorNext(t *testing.T) {
const n = 100
l := NewSkiplist(arenaSize)
defer l.DecrRef()
it := l.NewIterator()
defer it.Close()
require.False(t, it.Valid())
it.SeekToFirst()
require.False(t, it.Valid())
for i := n - 1; i >= 0; i-- {
l.Put(y.KeyWithTs([]byte(fmt.Sprintf("%05d", i)), 0),
y.ValueStruct{Value: newValue(i), Meta: 0, UserMeta: 0})
}
it.SeekToFirst()
for i := 0; i < n; i++ {
require.True(t, it.Valid())
v := it.Value()
require.EqualValues(t, newValue(i), v.Value)
it.Next()
}
require.False(t, it.Valid())
}
// TestIteratorPrev tests a basic iteration over all nodes from the end.
func TestIteratorPrev(t *testing.T) {
const n = 100
l := NewSkiplist(arenaSize)
defer l.DecrRef()
it := l.NewIterator()
defer it.Close()
require.False(t, it.Valid())
it.SeekToFirst()
require.False(t, it.Valid())
for i := 0; i < n; i++ {
l.Put(y.KeyWithTs([]byte(fmt.Sprintf("%05d", i)), 0),
y.ValueStruct{Value: newValue(i), Meta: 0, UserMeta: 0})
}
it.SeekToLast()
for i := n - 1; i >= 0; i-- {
require.True(t, it.Valid())
v := it.Value()
require.EqualValues(t, newValue(i), v.Value)
it.Prev()
}
require.False(t, it.Valid())
}
// TestIteratorSeek tests Seek and SeekForPrev.
func TestIteratorSeek(t *testing.T) {
const n = 100
l := NewSkiplist(arenaSize)
defer l.DecrRef()
it := l.NewIterator()
defer it.Close()
require.False(t, it.Valid())
it.SeekToFirst()
require.False(t, it.Valid())
// 1000, 1010, 1020, ..., 1990.
for i := n - 1; i >= 0; i-- {
v := i*10 + 1000
l.Put(y.KeyWithTs([]byte(fmt.Sprintf("%05d", i*10+1000)), 0),
y.ValueStruct{Value: newValue(v), Meta: 0, UserMeta: 0})
}
it.SeekToFirst()
require.True(t, it.Valid())
v := it.Value()
require.EqualValues(t, "01000", v.Value)
it.Seek(y.KeyWithTs([]byte("01000"), 0))
require.True(t, it.Valid())
v = it.Value()
require.EqualValues(t, "01000", v.Value)
it.Seek(y.KeyWithTs([]byte("01005"), 0))
require.True(t, it.Valid())
v = it.Value()
require.EqualValues(t, "01010", v.Value)
it.Seek(y.KeyWithTs([]byte("01010"), 0))
require.True(t, it.Valid())
v = it.Value()
require.EqualValues(t, "01010", v.Value)
it.Seek(y.KeyWithTs([]byte("99999"), 0))
require.False(t, it.Valid())
// Try SeekForPrev.
it.SeekForPrev(y.KeyWithTs([]byte("00"), 0))
require.False(t, it.Valid())
it.SeekForPrev(y.KeyWithTs([]byte("01000"), 0))
require.True(t, it.Valid())
v = it.Value()
require.EqualValues(t, "01000", v.Value)
it.SeekForPrev(y.KeyWithTs([]byte("01005"), 0))
require.True(t, it.Valid())
v = it.Value()
require.EqualValues(t, "01000", v.Value)
it.SeekForPrev(y.KeyWithTs([]byte("01010"), 0))
require.True(t, it.Valid())
v = it.Value()
require.EqualValues(t, "01010", v.Value)
it.SeekForPrev(y.KeyWithTs([]byte("99999"), 0))
require.True(t, it.Valid())
v = it.Value()
require.EqualValues(t, "01990", v.Value)
}
func randomKey(rng *rand.Rand) []byte {
b := make([]byte, 8)
key := rng.Uint32()
key2 := rng.Uint32()
binary.LittleEndian.PutUint32(b, key)
binary.LittleEndian.PutUint32(b[4:], key2)
return y.KeyWithTs(b, 0)
}
// Standard test. Some fraction is read. Some fraction is write. Writes have
// to go through mutex lock.
func BenchmarkReadWrite(b *testing.B) {
value := newValue(123)
for i := 0; i <= 10; i++ {
readFrac := float32(i) / 10.0
b.Run(fmt.Sprintf("frac_%d", i), func(b *testing.B) {
l := NewSkiplist(int64((b.N + 1) * MaxNodeSize))
defer l.DecrRef()
b.ResetTimer()
var count int
b.RunParallel(func(pb *testing.PB) {
rng := rand.New(rand.NewSource(time.Now().UnixNano()))
for pb.Next() {
if rng.Float32() < readFrac {
v := l.Get(randomKey(rng))
if v.Value != nil {
count++
}
} else {
l.Put(randomKey(rng), y.ValueStruct{Value: value, Meta: 0, UserMeta: 0})
}
}
})
})
}
}
// Standard test. Some fraction is read. Some fraction is write. Writes have
// to go through mutex lock.
func BenchmarkReadWriteMap(b *testing.B) {
value := newValue(123)
for i := 0; i <= 10; i++ {
readFrac := float32(i) / 10.0
b.Run(fmt.Sprintf("frac_%d", i), func(b *testing.B) {
m := make(map[string][]byte)
var mutex sync.RWMutex
b.ResetTimer()
var count int
b.RunParallel(func(pb *testing.PB) {
rng := rand.New(rand.NewSource(time.Now().UnixNano()))
for pb.Next() {
if rng.Float32() < readFrac {
mutex.RLock()
_, ok := m[string(randomKey(rng))]
mutex.RUnlock()
if ok {
count++
}
} else {
mutex.Lock()
m[string(randomKey(rng))] = value
mutex.Unlock()
}
}
})
})
}
}
func BenchmarkWrite(b *testing.B) {
value := newValue(123)
l := NewSkiplist(int64((b.N + 1) * MaxNodeSize))
defer l.DecrRef()
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
rng := rand.New(rand.NewSource(time.Now().UnixNano()))
for pb.Next() {
l.Put(randomKey(rng), y.ValueStruct{Value: value, Meta: 0, UserMeta: 0})
}
})
}
================================================
FILE: stream.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"bytes"
"context"
"sort"
"sync"
"sync/atomic"
"time"
humanize "github.com/dustin/go-humanize"
"google.golang.org/protobuf/proto"
"github.com/dgraph-io/badger/v4/pb"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2/z"
)
const batchSize = 16 << 20 // 16 MB
// maxStreamSize is the maximum allowed size of a stream batch. This is a soft limit
// as a single list that is still over the limit will have to be sent as is since it
// cannot be split further. This limit prevents the framework from creating batches
// so big that sending them causes issues (e.g running into the max size gRPC limit).
var maxStreamSize = uint64(100 << 20) // 100MB
// Stream provides a framework to concurrently iterate over a snapshot of Badger, pick up
// key-values, batch them up and call Send. Stream does concurrent iteration over many smaller key
// ranges. It does NOT send keys in lexicographical sorted order. To get keys in sorted
// order, use Iterator.
type Stream struct {
// Prefix to only iterate over certain range of keys. If set to nil (default), Stream would
// iterate over the entire DB.
Prefix []byte
// Number of goroutines to use for iterating over key ranges. Defaults to 8.
NumGo int
// Badger would produce log entries in Infof to indicate the progress of Stream. LogPrefix can
// be used to help differentiate them from other activities. Default is "Badger.Stream".
LogPrefix string
// ChooseKey is invoked each time a new key is encountered. Note that this is not called
// on every version of the value, only the first encountered version (i.e. the highest version
// of the value a key has). ChooseKey can be left nil to select all keys.
//
// Note: Calls to ChooseKey are concurrent.
ChooseKey func(item *Item) bool
// MaxSize is the maximum allowed size of a stream batch. This is a soft limit
// as a single list that is still over the limit will have to be sent as is since it
// cannot be split further. This limit prevents the framework from creating batches
// so big that sending them causes issues (e.g running into the max size gRPC limit).
// If necessary, set it up before the Stream starts synchronisation
// This is not a concurrency-safe setting
MaxSize uint64
// KeyToList, similar to ChooseKey, is only invoked on the highest version of the value. It
// is upto the caller to iterate over the versions and generate zero, one or more KVs. It
// is expected that the user would advance the iterator to go through the versions of the
// values. However, the user MUST immediately return from this function on the first encounter
// with a mismatching key. See example usage in ToList function. Can be left nil to use ToList
// function by default.
//
// KeyToList has access to z.Allocator accessible via stream.Allocator(itr.ThreadId). This
// allocator can be used to allocate KVs, to decrease the memory pressure on Go GC. Stream
// framework takes care of releasing those resources after calling Send. AllocRef does
// NOT need to be set in the returned KVList, as Stream framework would ignore that field,
// instead using the allocator assigned to that thread id.
//
// Note: Calls to KeyToList are concurrent.
KeyToList func(key []byte, itr *Iterator) (*pb.KVList, error)
// UseKeyToListWithThreadId is used to indicate that KeyToListWithThreadId should be used
// instead of KeyToList. This is a new api that can be used to figure out parallelism
// of the stream. Each threadId would be run serially. KeyToList being concurrent makes you
// take care of concurrency in KeyToList. Here threadId could be used to do some things serially.
// Once a thread finishes FinishThread() would be called.
UseKeyToListWithThreadId bool
KeyToListWithThreadId func(key []byte, itr *Iterator, threadId int) (*pb.KVList, error)
FinishThread func(threadId int) (*pb.KVList, error)
// This is the method where Stream sends the final output. All calls to Send are done by a
// single goroutine, i.e. logic within Send method can expect single threaded execution.
Send func(buf *z.Buffer) error
// Read data above the sinceTs. All keys with version =< sinceTs will be ignored.
SinceTs uint64
readTs uint64
db *DB
rangeCh chan keyRange
kvChan chan *z.Buffer
nextStreamId atomic.Uint32
doneMarkers bool
scanned atomic.Uint64 // used to estimate the ETA for data scan.
numProducers atomic.Int32
}
// SendDoneMarkers when true would send out done markers on the stream. False by default.
func (st *Stream) SendDoneMarkers(done bool) {
st.doneMarkers = done
}
// ToList is a default implementation of KeyToList. It picks up all valid versions of the key,
// skipping over deleted or expired keys.
func (st *Stream) ToList(key []byte, itr *Iterator) (*pb.KVList, error) {
a := itr.Alloc
ka := a.Copy(key)
list := &pb.KVList{}
for ; itr.Valid(); itr.Next() {
item := itr.Item()
if item.IsDeletedOrExpired() {
break
}
if !bytes.Equal(key, item.Key()) {
// Break out on the first encounter with another key.
break
}
kv := y.NewKV(a)
kv.Key = ka
if err := item.Value(func(val []byte) error {
kv.Value = a.Copy(val)
return nil
}); err != nil {
return nil, err
}
kv.Version = item.Version()
kv.ExpiresAt = item.ExpiresAt()
kv.UserMeta = a.Copy([]byte{item.UserMeta()})
list.Kv = append(list.Kv, kv)
if st.db.opt.NumVersionsToKeep == 1 {
break
}
if item.DiscardEarlierVersions() {
break
}
}
return list, nil
}
// keyRange is [start, end), including start, excluding end. Do ensure that the start,
// end byte slices are owned by keyRange struct.
func (st *Stream) produceRanges(ctx context.Context) {
ranges := st.db.Ranges(st.Prefix, st.NumGo)
y.AssertTrue(len(ranges) > 0)
y.AssertTrue(ranges[0].left == nil)
y.AssertTrue(ranges[len(ranges)-1].right == nil)
st.db.opt.Infof("Number of ranges found: %d\n", len(ranges))
// Sort in descending order of size.
sort.Slice(ranges, func(i, j int) bool {
return ranges[i].size > ranges[j].size
})
for i, r := range ranges {
st.rangeCh <- *r
st.db.opt.Infof("Sent range %d for iteration: [%x, %x) of size: %s\n",
i, r.left, r.right, humanize.IBytes(uint64(r.size)))
}
close(st.rangeCh)
}
// produceKVs picks up ranges from rangeCh, generates KV lists and sends them to kvChan.
func (st *Stream) produceKVs(ctx context.Context, threadId int) error {
st.numProducers.Add(1)
defer st.numProducers.Add(-1)
var txn *Txn
if st.readTs > 0 {
txn = st.db.NewTransactionAt(st.readTs, false)
} else {
txn = st.db.NewTransaction(false)
}
defer txn.Discard()
// produceKVs is running iterate serially. So, we can define the outList here.
outList := z.NewBuffer(2*batchSize, "Stream.ProduceKVs")
defer func() {
// The outList variable changes. So, we need to evaluate the variable in the defer. DO NOT
// call `defer outList.Release()`.
_ = outList.Release()
}()
iterate := func(kr keyRange) error {
iterOpts := DefaultIteratorOptions
iterOpts.AllVersions = true
iterOpts.Prefix = st.Prefix
iterOpts.PrefetchValues = true
iterOpts.SinceTs = st.SinceTs
itr := txn.NewIterator(iterOpts)
itr.ThreadId = threadId
defer itr.Close()
itr.Alloc = z.NewAllocator(1<<20, "Stream.Iterate")
defer itr.Alloc.Release()
// This unique stream id is used to identify all the keys from this iteration.
streamId := st.nextStreamId.Add(1)
var scanned int
sendIt := func() error {
select {
case st.kvChan <- outList:
outList = z.NewBuffer(2*batchSize, "Stream.ProduceKVs")
st.scanned.Add(uint64(itr.scanned - scanned))
scanned = itr.scanned
case <-ctx.Done():
return ctx.Err()
}
return nil
}
var prevKey []byte
for itr.Seek(kr.left); itr.Valid(); {
// it.Valid would only return true for keys with the provided Prefix in iterOpts.
item := itr.Item()
if bytes.Equal(item.Key(), prevKey) {
itr.Next()
continue
}
prevKey = append(prevKey[:0], item.Key()...)
// Check if we reached the end of the key range.
if len(kr.right) > 0 && bytes.Compare(item.Key(), kr.right) >= 0 {
break
}
// Check if we should pick this key.
if st.ChooseKey != nil && !st.ChooseKey(item) {
continue
}
// Now convert to key value.
itr.Alloc.Reset()
var list *pb.KVList
var err error
if st.UseKeyToListWithThreadId {
list, err = st.KeyToListWithThreadId(item.KeyCopy(nil), itr, threadId)
} else {
list, err = st.KeyToList(item.KeyCopy(nil), itr)
}
if err != nil {
st.db.opt.Warningf("While reading key: %x, got error: %v", item.Key(), err)
continue
}
if list == nil || len(list.Kv) == 0 {
continue
}
for _, kv := range list.Kv {
kv.StreamId = streamId
KVToBuffer(kv, outList)
if outList.LenNoPadding() < batchSize {
continue
}
if err := sendIt(); err != nil {
return err
}
}
}
if st.UseKeyToListWithThreadId {
if kvs, err := st.FinishThread(threadId); err != nil {
return err
} else {
for _, kv := range kvs.Kv {
kv.StreamId = streamId
KVToBuffer(kv, outList)
if outList.LenNoPadding() < batchSize {
continue
}
if err := sendIt(); err != nil {
return err
}
}
}
}
// Mark the stream as done.
if st.doneMarkers {
kv := &pb.KV{
StreamId: streamId,
StreamDone: true,
}
KVToBuffer(kv, outList)
}
return sendIt()
}
for {
select {
case kr, ok := <-st.rangeCh:
if !ok {
// Done with the keys.
return nil
}
if err := iterate(kr); err != nil {
return err
}
case <-ctx.Done():
return ctx.Err()
}
}
}
func (st *Stream) streamKVs(ctx context.Context) error {
onDiskSize, uncompressedSize := st.db.EstimateSize(st.Prefix)
// Manish has seen uncompressed size to be in 20% error margin.
uncompressedSize = uint64(float64(uncompressedSize) * 1.2)
st.db.opt.Infof("%s Streaming about %s of uncompressed data (%s on disk)\n",
st.LogPrefix, humanize.IBytes(uncompressedSize), humanize.IBytes(onDiskSize))
tickerDur := 5 * time.Second
var bytesSent uint64
t := time.NewTicker(tickerDur)
defer t.Stop()
now := time.Now()
sendBatch := func(batch *z.Buffer) error {
defer func() { _ = batch.Release() }()
sz := uint64(batch.LenNoPadding())
if sz == 0 {
return nil
}
bytesSent += sz
// st.db.opt.Infof("%s Sending batch of size: %s.\n", st.LogPrefix, humanize.IBytes(sz))
if err := st.Send(batch); err != nil {
st.db.opt.Warningf("Error while sending: %v\n", err)
return err
}
return nil
}
slurp := func(batch *z.Buffer) error {
loop:
for {
// Send the batch immediately if it already exceeds the maximum allowed size.
// If the size of the batch exceeds maxStreamSize, break from the loop to
// avoid creating a batch that is so big that certain limits are reached.
if uint64(batch.LenNoPadding()) > st.MaxSize {
break loop
}
select {
case kvs, ok := <-st.kvChan:
if !ok {
break loop
}
y.AssertTrue(kvs != nil)
y.Check2(batch.Write(kvs.Bytes()))
y.Check(kvs.Release())
default:
break loop
}
}
return sendBatch(batch)
} // end of slurp.
writeRate := y.NewRateMonitor(20)
scanRate := y.NewRateMonitor(20)
outer:
for {
var batch *z.Buffer
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
// Instead of calculating speed over the entire lifetime, we average the speed over
// ticker duration.
writeRate.Capture(bytesSent)
scanned := st.scanned.Load()
scanRate.Capture(scanned)
numProducers := st.numProducers.Load()
st.db.opt.Infof("%s [%s] Scan (%d): ~%s/%s at %s/sec. Sent: %s at %s/sec."+
" jemalloc: %s\n",
st.LogPrefix, y.FixedDuration(time.Since(now)), numProducers,
y.IBytesToString(scanned, 1), humanize.IBytes(uncompressedSize),
humanize.IBytes(scanRate.Rate()),
y.IBytesToString(bytesSent, 1), humanize.IBytes(writeRate.Rate()),
humanize.IBytes(uint64(z.NumAllocBytes())))
case kvs, ok := <-st.kvChan:
if !ok {
break outer
}
y.AssertTrue(kvs != nil)
batch = kvs
// Otherwise, slurp more keys into this batch.
if err := slurp(batch); err != nil {
return err
}
}
}
st.db.opt.Infof("%s Sent data of size %s\n", st.LogPrefix, humanize.IBytes(bytesSent))
return nil
}
// Orchestrate runs Stream. It picks up ranges from the SSTables, then runs NumGo number of
// goroutines to iterate over these ranges and batch up KVs in lists. It concurrently runs a single
// goroutine to pick these lists, batch them up further and send to Output.Send. Orchestrate also
// spits logs out to Infof, using provided LogPrefix. Note that all calls to Output.Send
// are serial. In case any of these steps encounter an error, Orchestrate would stop execution and
// return that error. Orchestrate can be called multiple times, but in serial order.
func (st *Stream) Orchestrate(ctx context.Context) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
st.rangeCh = make(chan keyRange, 3) // Contains keys for posting lists.
// kvChan should only have a small capacity to ensure that we don't buffer up too much data if
// sending is slow. Page size is set to 4MB, which is used to lazily cap the size of each
// KVList. To get 128MB buffer, we can set the channel size to 32.
st.kvChan = make(chan *z.Buffer, 32)
if st.KeyToList == nil {
st.KeyToList = st.ToList
}
// Picks up ranges from Badger, and sends them to rangeCh.
go st.produceRanges(ctx)
errCh := make(chan error, st.NumGo) // Stores error by consumeKeys.
var wg sync.WaitGroup
for i := 0; i < st.NumGo; i++ {
wg.Add(1)
go func(threadId int) {
defer wg.Done()
// Picks up ranges from rangeCh, generates KV lists, and sends them to kvChan.
if err := st.produceKVs(ctx, threadId); err != nil {
select {
case errCh <- err:
default:
}
}
}(i)
}
// Pick up key-values from kvChan and send to stream.
kvErr := make(chan error, 1)
go func() {
// Picks up KV lists from kvChan, and sends them to Output.
err := st.streamKVs(ctx)
if err != nil {
cancel() // Stop all the go routines.
}
kvErr <- err
}()
wg.Wait() // Wait for produceKVs to be over.
close(st.kvChan) // Now we can close kvChan.
defer func() {
// If due to some error, we have buffers left in kvChan, we should release them.
for buf := range st.kvChan {
_ = buf.Release()
}
}()
select {
case err := <-errCh: // Check error from produceKVs.
return err
default:
}
// Wait for key streaming to be over.
err := <-kvErr
return err
}
func (db *DB) newStream() *Stream {
return &Stream{
db: db,
NumGo: db.opt.NumGoroutines,
LogPrefix: "Badger.Stream",
MaxSize: maxStreamSize,
}
}
// NewStream creates a new Stream.
func (db *DB) NewStream() *Stream {
if db.opt.managedTxns {
panic("This API can not be called in managed mode.")
}
return db.newStream()
}
// NewStreamAt creates a new Stream at a particular timestamp. Should only be used with managed DB.
func (db *DB) NewStreamAt(readTs uint64) *Stream {
if !db.opt.managedTxns {
panic("This API can only be called in managed mode.")
}
stream := db.newStream()
stream.readTs = readTs
return stream
}
func BufferToKVList(buf *z.Buffer) (*pb.KVList, error) {
var list pb.KVList
err := buf.SliceIterate(func(s []byte) error {
kv := new(pb.KV)
if err := proto.Unmarshal(s, kv); err != nil {
return err
}
list.Kv = append(list.Kv, kv)
return nil
})
return &list, err
}
func KVToBuffer(kv *pb.KV, buf *z.Buffer) {
in := buf.SliceAllocate(proto.Size(kv))[:0]
_, err := proto.MarshalOptions{}.MarshalAppend(in, kv)
y.AssertTrue(err == nil)
}
================================================
FILE: stream_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"context"
"fmt"
"math"
"os"
"strconv"
"strings"
"testing"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto"
bpb "github.com/dgraph-io/badger/v4/pb"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2/z"
)
func keyWithPrefix(prefix string, k int) []byte {
return []byte(fmt.Sprintf("%s-%d", prefix, k))
}
func keyToInt(k []byte) (string, int) {
splits := strings.Split(string(k), "-")
key, err := strconv.Atoi(splits[1])
y.Check(err)
return splits[0], key
}
func value(k int) []byte {
return []byte(fmt.Sprintf("%08d", k))
}
type collector struct {
kv []*bpb.KV
}
func (c *collector) Send(buf *z.Buffer) error {
list, err := BufferToKVList(buf)
if err != nil {
return err
}
for _, kv := range list.Kv {
if kv.StreamDone == true {
return nil
}
cp := proto.Clone(kv).(*bpb.KV)
c.kv = append(c.kv, cp)
}
return err
}
var ctxb = context.Background()
func TestStream(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
db, err := OpenManaged(DefaultOptions(dir))
require.NoError(t, err)
var count int
for _, prefix := range []string{"p0", "p1", "p2"} {
txn := db.NewTransactionAt(math.MaxUint64, true)
for i := 1; i <= 100; i++ {
require.NoError(t, txn.SetEntry(NewEntry(keyWithPrefix(prefix, i), value(i))))
count++
}
require.NoError(t, txn.CommitAt(5, nil))
}
stream := db.NewStreamAt(math.MaxUint64)
stream.LogPrefix = "Testing"
c := &collector{}
stream.Send = c.Send
// Test case 1. Retrieve everything.
err = stream.Orchestrate(ctxb)
require.NoError(t, err)
require.Equal(t, 300, len(c.kv), "Expected 300. Got: %d", len(c.kv))
m := make(map[string]int)
for _, kv := range c.kv {
prefix, ki := keyToInt(kv.Key)
expected := value(ki)
require.Equal(t, expected, kv.Value)
m[prefix]++
}
require.Equal(t, 3, len(m))
for pred, count := range m {
require.Equal(t, 100, count, "Count mismatch for pred: %s", pred)
}
// Test case 2. Retrieve only 1 predicate.
stream.Prefix = []byte("p1")
c.kv = c.kv[:0]
err = stream.Orchestrate(ctxb)
require.NoError(t, err)
require.Equal(t, 100, len(c.kv), "Expected 100. Got: %d", len(c.kv))
m = make(map[string]int)
for _, kv := range c.kv {
prefix, ki := keyToInt(kv.Key)
expected := value(ki)
require.Equal(t, expected, kv.Value)
m[prefix]++
}
require.Equal(t, 1, len(m))
for pred, count := range m {
require.Equal(t, 100, count, "Count mismatch for pred: %s", pred)
}
// Test case 3. Retrieve select keys within the predicate.
c.kv = c.kv[:0]
stream.ChooseKey = func(item *Item) bool {
_, k := keyToInt(item.Key())
return k%2 == 0
}
err = stream.Orchestrate(ctxb)
require.NoError(t, err)
require.Equal(t, 50, len(c.kv), "Expected 50. Got: %d", len(c.kv))
m = make(map[string]int)
for _, kv := range c.kv {
prefix, ki := keyToInt(kv.Key)
expected := value(ki)
require.Equal(t, expected, kv.Value)
m[prefix]++
}
require.Equal(t, 1, len(m))
for pred, count := range m {
require.Equal(t, 50, count, "Count mismatch for pred: %s", pred)
}
// Test case 4. Retrieve select keys from all predicates.
c.kv = c.kv[:0]
stream.Prefix = []byte{}
err = stream.Orchestrate(ctxb)
require.NoError(t, err)
require.Equal(t, 150, len(c.kv), "Expected 150. Got: %d", len(c.kv))
m = make(map[string]int)
for _, kv := range c.kv {
prefix, ki := keyToInt(kv.Key)
expected := value(ki)
require.Equal(t, expected, kv.Value)
m[prefix]++
}
require.Equal(t, 3, len(m))
for pred, count := range m {
require.Equal(t, 50, count, "Count mismatch for pred: %s", pred)
}
require.NoError(t, db.Close())
}
func TestStreamMaxSize(t *testing.T) {
if !*manual {
t.Skip("Skipping test meant to be run manually.")
return
}
// Set the maxStreamSize to 1MB for the duration of the test so that the it can use a smaller
// dataset than it would otherwise need.
originalMaxStreamSize := maxStreamSize
maxStreamSize = 1 << 20
defer func() {
maxStreamSize = originalMaxStreamSize
}()
testSize := int(1e6)
dir, err := os.MkdirTemp("", "badger-big-test")
require.NoError(t, err)
defer removeDir(dir)
db, err := OpenManaged(DefaultOptions(dir))
require.NoError(t, err)
var count int
wb := db.NewWriteBatchAt(5)
for _, prefix := range []string{"p0", "p1", "p2"} {
for i := 1; i <= testSize; i++ {
require.NoError(t, wb.SetEntry(NewEntry(keyWithPrefix(prefix, i), value(i))))
count++
}
}
require.NoError(t, wb.Flush())
stream := db.NewStreamAt(math.MaxUint64)
stream.LogPrefix = "Testing"
c := &collector{}
stream.Send = c.Send
// default value
require.Equal(t, stream.MaxSize, maxStreamSize)
// reset maxsize
stream.MaxSize = 1024 * 1024 * 50
// Test case 1. Retrieve everything.
err = stream.Orchestrate(ctxb)
require.NoError(t, err)
require.Equal(t, 3*testSize, len(c.kv), "Expected 30000. Got: %d", len(c.kv))
m := make(map[string]int)
for _, kv := range c.kv {
prefix, ki := keyToInt(kv.Key)
expected := value(ki)
require.Equal(t, expected, kv.Value)
m[prefix]++
}
require.Equal(t, 3, len(m))
for pred, count := range m {
require.Equal(t, testSize, count, "Count mismatch for pred: %s", pred)
}
require.NoError(t, db.Close())
}
func TestStreamWithThreadId(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
db, err := OpenManaged(DefaultOptions(dir))
require.NoError(t, err)
var count int
for _, prefix := range []string{"p0", "p1", "p2"} {
txn := db.NewTransactionAt(math.MaxUint64, true)
for i := 1; i <= 100; i++ {
require.NoError(t, txn.SetEntry(NewEntry(keyWithPrefix(prefix, i), value(i))))
count++
}
require.NoError(t, txn.CommitAt(5, nil))
}
stream := db.NewStreamAt(math.MaxUint64)
stream.LogPrefix = "Testing"
stream.KeyToList = func(key []byte, itr *Iterator) (
*bpb.KVList, error) {
require.Less(t, itr.ThreadId, stream.NumGo)
return stream.ToList(key, itr)
}
c := &collector{}
stream.Send = c.Send
err = stream.Orchestrate(ctxb)
require.NoError(t, err)
require.Equal(t, 300, len(c.kv), "Expected 300. Got: %d", len(c.kv))
m := make(map[string]int)
for _, kv := range c.kv {
prefix, ki := keyToInt(kv.Key)
expected := value(ki)
require.Equal(t, expected, kv.Value)
m[prefix]++
}
require.Equal(t, 3, len(m))
for pred, count := range m {
require.Equal(t, 100, count, "Count mismatch for pred: %s", pred)
}
require.NoError(t, db.Close())
}
func TestBigStream(t *testing.T) {
if !*manual {
t.Skip("Skipping test meant to be run manually.")
return
}
// Set the maxStreamSize to 1MB for the duration of the test so that the it can use a smaller
// dataset than it would otherwise need.
originalMaxStreamSize := maxStreamSize
maxStreamSize = 1 << 20
defer func() {
maxStreamSize = originalMaxStreamSize
}()
testSize := int(1e6)
dir, err := os.MkdirTemp("", "badger-big-test")
require.NoError(t, err)
defer removeDir(dir)
db, err := OpenManaged(DefaultOptions(dir))
require.NoError(t, err)
var count int
wb := db.NewWriteBatchAt(5)
for _, prefix := range []string{"p0", "p1", "p2"} {
for i := 1; i <= testSize; i++ {
require.NoError(t, wb.SetEntry(NewEntry(keyWithPrefix(prefix, i), value(i))))
count++
}
}
require.NoError(t, wb.Flush())
stream := db.NewStreamAt(math.MaxUint64)
stream.LogPrefix = "Testing"
c := &collector{}
stream.Send = c.Send
// Test case 1. Retrieve everything.
err = stream.Orchestrate(ctxb)
require.NoError(t, err)
require.Equal(t, 3*testSize, len(c.kv), "Expected 30000. Got: %d", len(c.kv))
m := make(map[string]int)
for _, kv := range c.kv {
prefix, ki := keyToInt(kv.Key)
expected := value(ki)
require.Equal(t, expected, kv.Value)
m[prefix]++
}
require.Equal(t, 3, len(m))
for pred, count := range m {
require.Equal(t, testSize, count, "Count mismatch for pred: %s", pred)
}
require.NoError(t, db.Close())
}
// There was a bug in the stream writer code which would cause allocators to be
// freed up twice if the default keyToList was not used. This test verifies that issue.
func TestStreamCustomKeyToList(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
db, err := OpenManaged(DefaultOptions(dir))
require.NoError(t, err)
var count int
for _, key := range []string{"p0", "p1", "p2"} {
for i := 1; i <= 100; i++ {
txn := db.NewTransactionAt(math.MaxUint64, true)
require.NoError(t, txn.SetEntry(NewEntry([]byte(key), value(i))))
count++
require.NoError(t, txn.CommitAt(uint64(i), nil))
}
}
stream := db.NewStreamAt(math.MaxUint64)
stream.LogPrefix = "Testing"
stream.KeyToList = func(key []byte, itr *Iterator) (*bpb.KVList, error) {
item := itr.Item()
val, err := item.ValueCopy(nil)
if err != nil {
return nil, err
}
kv := &bpb.KV{
Key: y.Copy(item.Key()),
Value: val,
}
return &bpb.KVList{
Kv: []*bpb.KV{kv},
}, nil
}
res := map[string]struct{}{"p0": {}, "p1": {}, "p2": {}}
stream.Send = func(buf *z.Buffer) error {
list, err := BufferToKVList(buf)
require.NoError(t, err)
for _, kv := range list.Kv {
key := string(kv.Key)
if _, ok := res[key]; !ok {
panic(fmt.Sprintf("%s key not found", key))
}
delete(res, key)
}
return nil
}
require.NoError(t, stream.Orchestrate(ctxb))
require.Zero(t, len(res))
}
================================================
FILE: stream_writer.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"encoding/hex"
"fmt"
"sync"
"github.com/dustin/go-humanize"
"google.golang.org/protobuf/proto"
"github.com/dgraph-io/badger/v4/pb"
"github.com/dgraph-io/badger/v4/table"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2/z"
)
// StreamWriter is used to write data coming from multiple streams. The streams must not have any
// overlapping key ranges. Within each stream, the keys must be sorted. Badger Stream framework is
// capable of generating such an output. So, this StreamWriter can be used at the other end to build
// BadgerDB at a much faster pace by writing SSTables (and value logs) directly to LSM tree levels
// without causing any compactions at all. This is way faster than using batched writer or using
// transactions, but only applicable in situations where the keys are pre-sorted and the DB is being
// bootstrapped. Existing data would get deleted when using this writer. So, this is only useful
// when restoring from backup or replicating DB across servers.
//
// StreamWriter should not be called on in-use DB instances. It is designed only to bootstrap new
// DBs.
type StreamWriter struct {
writeLock sync.Mutex
db *DB
done func()
throttle *y.Throttle
maxVersion uint64
writers map[uint32]*sortedWriter
prevLevel int
}
// NewStreamWriter creates a StreamWriter. Right after creating StreamWriter, Prepare must be
// called. The memory usage of a StreamWriter is directly proportional to the number of streams
// possible. So, efforts must be made to keep the number of streams low. Stream framework would
// typically use 16 goroutines and hence create 16 streams.
func (db *DB) NewStreamWriter() *StreamWriter {
return &StreamWriter{
db: db,
// throttle shouldn't make much difference. Memory consumption is based on the number of
// concurrent streams being processed.
throttle: y.NewThrottle(16),
writers: make(map[uint32]*sortedWriter),
}
}
// Prepare should be called before writing any entry to StreamWriter. It deletes all data present in
// existing DB, stops compactions and any writes being done by other means. Be very careful when
// calling Prepare, because it could result in permanent data loss. Not calling Prepare would result
// in a corrupt Badger instance. Use PrepareIncremental to do incremental stream write.
func (sw *StreamWriter) Prepare() error {
sw.writeLock.Lock()
defer sw.writeLock.Unlock()
done, err := sw.db.dropAll()
// Ensure that done() is never called more than once.
var once sync.Once
sw.done = func() { once.Do(done) }
return err
}
// PrepareIncremental should be called before writing any entry to StreamWriter incrementally.
// In incremental stream write, the tables are written at one level above the current base level.
func (sw *StreamWriter) PrepareIncremental() error {
sw.writeLock.Lock()
defer sw.writeLock.Unlock()
// Ensure that done() is never called more than once.
var once sync.Once
// prepareToDrop will stop all the incoming writes and process any pending flush tasks.
// Before we start writing, we'll stop the compactions because no one else should be writing to
// the same level as the stream writer is writing to.
f, err := sw.db.prepareToDrop()
if err != nil {
sw.done = func() { once.Do(f) }
return err
}
sw.db.stopCompactions()
done := func() {
sw.db.startCompactions()
f()
}
sw.done = func() { once.Do(done) }
mts, decr := sw.db.getMemTables()
defer decr()
for _, m := range mts {
if !m.sl.Empty() {
return fmt.Errorf("Unable to do incremental writes because MemTable has data")
}
}
isEmptyDB := true
for _, level := range sw.db.Levels() {
if level.NumTables > 0 {
sw.prevLevel = level.Level
isEmptyDB = false
break
}
}
if isEmptyDB {
// If DB is empty, we should allow doing incremental stream write.
return nil
}
if sw.prevLevel == 0 {
// It seems that data is present in all levels from Lmax to L0. If we call flatten
// on the tree, all the data will go to Lmax. All the levels above will be empty
// after flatten call. Now, we should be able to use incremental stream writer again.
if err := sw.db.Flatten(3); err != nil {
return fmt.Errorf("error during flatten in StreamWriter: %w", err)
}
sw.prevLevel = len(sw.db.Levels()) - 1
}
return nil
}
// Write writes KVList to DB. Each KV within the list contains the stream id which StreamWriter
// would use to demux the writes. Write is thread safe and can be called concurrently by multiple
// goroutines.
func (sw *StreamWriter) Write(buf *z.Buffer) error {
if buf.LenNoPadding() == 0 {
return nil
}
// closedStreams keeps track of all streams which are going to be marked as done. We are
// keeping track of all streams so that we can close them at the end, after inserting all
// the valid kvs.
closedStreams := make(map[uint32]struct{})
streamReqs := make(map[uint32]*request)
err := buf.SliceIterate(func(s []byte) error {
var kv pb.KV
if err := proto.Unmarshal(s, &kv); err != nil {
return err
}
if kv.StreamDone {
closedStreams[kv.StreamId] = struct{}{}
return nil
}
// Panic if some kv comes after stream has been marked as closed.
if _, ok := closedStreams[kv.StreamId]; ok {
panic(fmt.Sprintf("write performed on closed stream: %d", kv.StreamId))
}
sw.writeLock.Lock()
if sw.maxVersion < kv.Version {
sw.maxVersion = kv.Version
}
if sw.prevLevel == 0 {
// If prevLevel is 0, that means that we have not written anything yet.
// So, we can write to the maxLevel. newWriter writes to prevLevel - 1,
// so we can set prevLevel to len(levels).
sw.prevLevel = len(sw.db.lc.levels)
}
sw.writeLock.Unlock()
var meta, userMeta byte
if len(kv.Meta) > 0 {
meta = kv.Meta[0]
}
if len(kv.UserMeta) > 0 {
userMeta = kv.UserMeta[0]
}
e := &Entry{
Key: y.KeyWithTs(kv.Key, kv.Version),
Value: y.Copy(kv.Value),
UserMeta: userMeta,
ExpiresAt: kv.ExpiresAt,
meta: meta,
}
// If the value can be collocated with the key in LSM tree, we can skip
// writing the value to value log.
req := streamReqs[kv.StreamId]
if req == nil {
req = &request{}
streamReqs[kv.StreamId] = req
}
req.Entries = append(req.Entries, e)
return nil
})
if err != nil {
return err
}
all := make([]*request, 0, len(streamReqs))
for _, req := range streamReqs {
all = append(all, req)
}
sw.writeLock.Lock()
defer sw.writeLock.Unlock()
// We are writing all requests to vlog even if some request belongs to already closed stream.
// It is safe to do because we are panicking while writing to sorted writer, which will be nil
// for closed stream. At restart, stream writer will drop all the data in Prepare function.
if err := sw.db.vlog.write(all); err != nil {
return err
}
for streamID, req := range streamReqs {
writer, ok := sw.writers[streamID]
if !ok {
var err error
writer, err = sw.newWriter(streamID)
if err != nil {
return y.Wrapf(err, "failed to create writer with ID %d", streamID)
}
sw.writers[streamID] = writer
}
if writer == nil {
panic(fmt.Sprintf("write performed on closed stream: %d", streamID))
}
writer.reqCh <- req
}
// Now we can close any streams if required. We will make writer for
// the closed streams as nil.
for streamId := range closedStreams {
writer, ok := sw.writers[streamId]
if !ok {
sw.db.opt.Warningf("Trying to close stream: %d, but no sorted "+
"writer found for it", streamId)
continue
}
writer.closer.SignalAndWait()
if err := writer.Done(); err != nil {
return err
}
sw.writers[streamId] = nil
}
return nil
}
// Flush is called once we are done writing all the entries. It syncs DB directories. It also
// updates Oracle with maxVersion found in all entries (if DB is not managed).
func (sw *StreamWriter) Flush() error {
sw.writeLock.Lock()
defer sw.writeLock.Unlock()
defer sw.done()
for _, writer := range sw.writers {
if writer != nil {
writer.closer.SignalAndWait()
}
}
for _, writer := range sw.writers {
if writer == nil {
continue
}
if err := writer.Done(); err != nil {
return err
}
}
if !sw.db.opt.managedTxns {
if sw.db.orc != nil {
sw.db.orc.Stop()
}
if curMax := sw.db.orc.readTs(); curMax >= sw.maxVersion {
sw.maxVersion = curMax
}
sw.db.orc = newOracle(sw.db.opt)
sw.db.orc.nextTxnTs = sw.maxVersion
sw.db.orc.txnMark.Done(sw.maxVersion)
sw.db.orc.readMark.Done(sw.maxVersion)
sw.db.orc.incrementNextTs()
}
// Wait for all files to be written.
if err := sw.throttle.Finish(); err != nil {
return err
}
// Sort tables at the end.
for _, l := range sw.db.lc.levels {
l.sortTables()
}
// Now sync the directories, so all the files are registered.
if sw.db.opt.ValueDir != sw.db.opt.Dir {
if err := sw.db.syncDir(sw.db.opt.ValueDir); err != nil {
return err
}
}
if err := sw.db.syncDir(sw.db.opt.Dir); err != nil {
return err
}
return sw.db.lc.validate()
}
// Cancel signals all goroutines to exit. Calling defer sw.Cancel() immediately after creating a new StreamWriter
// ensures that writes are unblocked even upon early return. Note that dropAll() is not called here, so any
// partially written data will not be erased until a new StreamWriter is initialized.
func (sw *StreamWriter) Cancel() {
sw.writeLock.Lock()
defer sw.writeLock.Unlock()
for _, writer := range sw.writers {
if writer != nil {
writer.closer.Signal()
}
}
for _, writer := range sw.writers {
if writer != nil {
writer.closer.Wait()
}
}
if err := sw.throttle.Finish(); err != nil {
sw.db.opt.Errorf("error in throttle.Finish: %+v", err)
}
// Handle Cancel() being called before Prepare().
if sw.done != nil {
sw.done()
}
}
type sortedWriter struct {
db *DB
throttle *y.Throttle
opts table.Options
builder *table.Builder
lastKey []byte
level int
streamID uint32
reqCh chan *request
// Have separate closer for each writer, as it can be closed at any time.
closer *z.Closer
}
func (sw *StreamWriter) newWriter(streamID uint32) (*sortedWriter, error) {
bopts := buildTableOptions(sw.db)
for i := 2; i < sw.db.opt.MaxLevels; i++ {
bopts.TableSize *= uint64(sw.db.opt.TableSizeMultiplier)
}
w := &sortedWriter{
db: sw.db,
opts: bopts,
streamID: streamID,
throttle: sw.throttle,
builder: table.NewTableBuilder(bopts),
reqCh: make(chan *request, 3),
closer: z.NewCloser(1),
level: sw.prevLevel - 1, // Write at the level just above the one we were writing to.
}
go w.handleRequests()
return w, nil
}
func (w *sortedWriter) handleRequests() {
defer w.closer.Done()
process := func(req *request) {
for i, e := range req.Entries {
// If badger is running in InMemory mode, len(req.Ptrs) == 0.
var vs y.ValueStruct
if e.skipVlogAndSetThreshold(w.db.valueThreshold()) {
vs = y.ValueStruct{
Value: e.Value,
Meta: e.meta,
UserMeta: e.UserMeta,
ExpiresAt: e.ExpiresAt,
}
} else {
vptr := req.Ptrs[i]
vs = y.ValueStruct{
Value: vptr.Encode(),
Meta: e.meta | bitValuePointer,
UserMeta: e.UserMeta,
ExpiresAt: e.ExpiresAt,
}
}
if err := w.Add(e.Key, vs); err != nil {
panic(err)
}
}
}
for {
select {
case req := <-w.reqCh:
process(req)
case <-w.closer.HasBeenClosed():
close(w.reqCh)
for req := range w.reqCh {
process(req)
}
return
}
}
}
// Add adds key and vs to sortedWriter.
func (w *sortedWriter) Add(key []byte, vs y.ValueStruct) error {
if len(w.lastKey) > 0 && y.CompareKeys(key, w.lastKey) <= 0 {
return fmt.Errorf("keys not in sorted order (last key: %s, key: %s)",
hex.Dump(w.lastKey), hex.Dump(key))
}
sameKey := y.SameKey(key, w.lastKey)
// Same keys should go into the same SSTable.
if !sameKey && w.builder.ReachedCapacity() {
if err := w.send(false); err != nil {
return err
}
}
w.lastKey = y.SafeCopy(w.lastKey, key)
var vp valuePointer
if vs.Meta&bitValuePointer > 0 {
vp.Decode(vs.Value)
}
w.builder.Add(key, vs, vp.Len)
return nil
}
func (w *sortedWriter) send(done bool) error {
if err := w.throttle.Do(); err != nil {
return err
}
go func(builder *table.Builder) {
err := w.createTable(builder)
w.throttle.Done(err)
}(w.builder)
// If done is true, this indicates we can close the writer.
// No need to allocate underlying TableBuilder now.
if done {
w.builder = nil
return nil
}
w.builder = table.NewTableBuilder(w.opts)
return nil
}
// Done is called once we are done writing all keys and valueStructs
// to sortedWriter. It completes writing current SST to disk.
func (w *sortedWriter) Done() error {
if w.builder.Empty() {
w.builder.Close()
// Assign builder as nil, so that underlying memory can be garbage collected.
w.builder = nil
return nil
}
return w.send(true)
}
func (w *sortedWriter) createTable(builder *table.Builder) error {
defer builder.Close()
if builder.Empty() {
builder.Finish()
return nil
}
fileID := w.db.lc.reserveFileID()
var tbl *table.Table
if w.db.opt.InMemory {
data := builder.Finish()
var err error
if tbl, err = table.OpenInMemoryTable(data, fileID, builder.Opts()); err != nil {
return err
}
} else {
var err error
fname := table.NewFilename(fileID, w.db.opt.Dir)
if tbl, err = table.CreateTable(fname, builder); err != nil {
return err
}
}
lc := w.db.lc
lhandler := lc.levels[w.level]
// Now that table can be opened successfully, let's add this to the MANIFEST.
change := &pb.ManifestChange{
Id: tbl.ID(),
KeyId: tbl.KeyID(),
Op: pb.ManifestChange_CREATE,
Level: uint32(lhandler.level),
Compression: uint32(tbl.CompressionType()),
}
if err := w.db.manifest.addChanges([]*pb.ManifestChange{change}, w.db.opt); err != nil {
return err
}
// We are not calling lhandler.replaceTables() here, as it sorts tables on every addition.
// We can sort all tables only once during Flush() call.
lhandler.addTable(tbl)
// Release the ref held by OpenTable.
_ = tbl.DecrRef()
w.db.opt.Infof("Table created: %d at level: %d for stream: %d. Size: %s\n",
fileID, lhandler.level, w.streamID, humanize.IBytes(uint64(tbl.Size())))
return nil
}
================================================
FILE: stream_writer_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"bytes"
"encoding/binary"
"fmt"
"math"
"math/rand"
"os"
"testing"
"github.com/stretchr/testify/require"
"github.com/dgraph-io/badger/v4/pb"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2/z"
)
func getSortedKVList(valueSize, listSize int) *z.Buffer {
value := make([]byte, valueSize)
y.Check2(rand.Read(value))
buf := z.NewBuffer(10<<20, "test")
for i := 0; i < listSize; i++ {
key := make([]byte, 8)
binary.BigEndian.PutUint64(key, uint64(i))
KVToBuffer(&pb.KV{
Key: key,
Value: value,
Version: 20,
}, buf)
}
return buf
}
// check if we can read values after writing using stream writer
func TestStreamWriter1(t *testing.T) {
test := func(t *testing.T, opts *Options) {
runBadgerTest(t, opts, func(t *testing.T, db *DB) {
// write entries using stream writer
noOfKeys := 10
valueSize := 128
list := getSortedKVList(valueSize, noOfKeys)
sw := db.NewStreamWriter()
require.NoError(t, sw.Prepare(), "sw.Prepare() failed")
require.NoError(t, sw.Write(list), "sw.Write() failed")
require.NoError(t, sw.Flush(), "sw.Flush() failed")
err := db.View(func(txn *Txn) error {
// read any random key from inserted keys
keybyte := make([]byte, 8)
keyNo := uint64(rand.Int63n(int64(noOfKeys)))
binary.BigEndian.PutUint64(keybyte, keyNo)
_, err := txn.Get(keybyte)
require.Nil(t, err, "key should be found")
// count all keys written using stream writer
keysCount := 0
itrOps := DefaultIteratorOptions
it := txn.NewIterator(itrOps)
defer it.Close()
for it.Rewind(); it.Valid(); it.Next() {
keysCount++
}
require.True(t, keysCount == noOfKeys, "count of keys should be matched")
return nil
})
require.NoError(t, err, "error while retrieving key")
})
}
t.Run("Normal mode", func(t *testing.T) {
normalModeOpts := getTestOptions("")
test(t, &normalModeOpts)
})
t.Run("Managed mode", func(t *testing.T) {
managedModeOpts := getTestOptions("")
managedModeOpts.managedTxns = true
test(t, &managedModeOpts)
})
t.Run("InMemory mode", func(t *testing.T) {
diskLessModeOpts := getTestOptions("")
diskLessModeOpts.InMemory = true
test(t, &diskLessModeOpts)
})
}
// write more keys to db after writing keys using stream writer
func TestStreamWriter2(t *testing.T) {
test := func(t *testing.T, opts *Options) {
runBadgerTest(t, opts, func(t *testing.T, db *DB) {
// write entries using stream writer
noOfKeys := 1000
valueSize := 128
list := getSortedKVList(valueSize, noOfKeys)
sw := db.NewStreamWriter()
require.NoError(t, sw.Prepare(), "sw.Prepare() failed")
require.NoError(t, sw.Write(list), "sw.Write() failed")
// get max version of sw, will be used in transactions for managed mode
maxVs := sw.maxVersion
require.NoError(t, sw.Flush(), "sw.Flush() failed")
// delete all the inserted keys
val := make([]byte, valueSize)
y.Check2(rand.Read(val))
for i := 0; i < noOfKeys; i++ {
txn := db.newTransaction(true, opts.managedTxns)
if opts.managedTxns {
txn.readTs = math.MaxUint64
txn.commitTs = maxVs
}
keybyte := make([]byte, 8)
keyNo := uint64(i)
binary.BigEndian.PutUint64(keybyte, keyNo)
require.NoError(t, txn.Delete(keybyte), "error while deleting keys")
require.NoError(t, txn.Commit(), "error while commit")
}
// verify while iteration count of keys should be 0
err := db.View(func(txn *Txn) error {
keysCount := 0
itrOps := DefaultIteratorOptions
it := txn.NewIterator(itrOps)
defer it.Close()
for it.Rewind(); it.Valid(); it.Next() {
keysCount++
}
require.Zero(t, keysCount, "count of keys should be 0")
return nil
})
require.Nil(t, err, "error should be nil while iterating")
})
}
t.Run("Normal mode", func(t *testing.T) {
normalModeOpts := getTestOptions("")
test(t, &normalModeOpts)
})
t.Run("Managed mode", func(t *testing.T) {
managedModeOpts := getTestOptions("")
managedModeOpts.managedTxns = true
test(t, &managedModeOpts)
})
t.Run("InMemory mode", func(t *testing.T) {
diskLessModeOpts := getTestOptions("")
diskLessModeOpts.InMemory = true
test(t, &diskLessModeOpts)
})
}
func TestStreamWriter3(t *testing.T) {
test := func(t *testing.T, opts *Options) {
runBadgerTest(t, opts, func(t *testing.T, db *DB) {
// write entries using stream writer
noOfKeys := 1000
valueSize := 128
// insert keys which are even
value := make([]byte, valueSize)
y.Check2(rand.Read(value))
counter := 0
buf := z.NewBuffer(10<<20, "test")
defer func() { require.NoError(t, buf.Release()) }()
for i := 0; i < noOfKeys; i++ {
key := make([]byte, 8)
binary.BigEndian.PutUint64(key, uint64(counter))
KVToBuffer(&pb.KV{
Key: key,
Value: value,
Version: 20,
}, buf)
counter = counter + 2
}
sw := db.NewStreamWriter()
require.NoError(t, sw.Prepare(), "sw.Prepare() failed")
require.NoError(t, sw.Write(buf), "sw.Write() failed")
// get max version of sw, will be used in transactions for managed mode
maxVs := sw.maxVersion
require.NoError(t, sw.Flush(), "sw.Flush() failed")
// insert keys which are odd
val := make([]byte, valueSize)
y.Check2(rand.Read(val))
counter = 1
for i := 0; i < noOfKeys; i++ {
txn := db.newTransaction(true, opts.managedTxns)
if opts.managedTxns {
txn.readTs = math.MaxUint64
txn.commitTs = maxVs
}
keybyte := make([]byte, 8)
keyNo := uint64(counter)
binary.BigEndian.PutUint64(keybyte, keyNo)
require.NoError(t, txn.SetEntry(NewEntry(keybyte, val)),
"error while inserting entries")
require.NoError(t, txn.Commit(), "error while commit")
counter = counter + 2
}
// verify while iteration keys are in sorted order
err := db.View(func(txn *Txn) error {
keysCount := 0
itrOps := DefaultIteratorOptions
it := txn.NewIterator(itrOps)
defer it.Close()
prev := uint64(0)
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
key := item.Key()
current := binary.BigEndian.Uint64(key)
if prev != 0 && current != (prev+uint64(1)) {
t.Fatal("keys should be in increasing order")
}
keysCount++
prev = current
}
require.True(t, keysCount == 2*noOfKeys, "count of keys is not matching")
return nil
})
require.Nil(t, err, "error should be nil while iterating")
})
}
t.Run("Normal mode", func(t *testing.T) {
normalModeOpts := getTestOptions("")
test(t, &normalModeOpts)
})
t.Run("Managed mode", func(t *testing.T) {
managedModeOpts := getTestOptions("")
managedModeOpts.managedTxns = true
test(t, &managedModeOpts)
})
t.Run("InMemory mode", func(t *testing.T) {
diskLessModeOpts := getTestOptions("")
diskLessModeOpts.InMemory = true
test(t, &diskLessModeOpts)
})
}
// After inserting all data from streams, StreamWriter reinitializes Oracle and updates its nextTs
// to maxVersion found in all entries inserted(if db is running in non managed mode). It also
// updates Oracle's txnMark and readMark. If Oracle is not reinitialized, it might cause issue
// while updating readMark and txnMark when its nextTs is ahead of maxVersion. This tests verifies
// Oracle reinitialization is happening. Try commenting line 171 in stream_writer.go with code
// (sw.db.orc = newOracle(sw.db.opt), this test should fail.
func TestStreamWriter4(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
// first insert some entries in db
for i := 0; i < 10; i++ {
err := db.Update(func(txn *Txn) error {
key := []byte(fmt.Sprintf("key-%d", i))
value := []byte(fmt.Sprintf("val-%d", i))
return txn.Set(key, value)
})
require.NoError(t, err, "error while updating db")
}
buf := z.NewBuffer(10<<20, "test")
defer func() { require.NoError(t, buf.Release()) }()
KVToBuffer(&pb.KV{
Key: []byte("key-1"),
Value: []byte("value-1"),
Version: 1,
}, buf)
sw := db.NewStreamWriter()
require.NoError(t, sw.Prepare(), "sw.Prepare() failed")
require.NoError(t, sw.Write(buf), "sw.Write() failed")
require.NoError(t, sw.Flush(), "sw.Flush() failed")
})
}
func TestStreamWriter5(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
left := make([]byte, 6)
left[0] = 0x00
copy(left[1:], []byte("break"))
right := make([]byte, 6)
right[0] = 0xff
copy(right[1:], []byte("break"))
buf := z.NewBuffer(10<<20, "test")
defer func() { require.NoError(t, buf.Release()) }()
KVToBuffer(&pb.KV{
Key: left,
Value: []byte("val"),
Version: 1,
}, buf)
KVToBuffer(&pb.KV{
Key: right,
Value: []byte("val"),
Version: 1,
}, buf)
sw := db.NewStreamWriter()
require.NoError(t, sw.Prepare(), "sw.Prepare() failed")
require.NoError(t, sw.Write(buf), "sw.Write() failed")
require.NoError(t, sw.Flush(), "sw.Flush() failed")
require.NoError(t, db.Close())
var err error
db, err = Open(db.opt)
require.NoError(t, err)
require.NoError(t, db.Close())
})
}
// This test tries to insert multiple equal keys(without version) and verifies
// if those are going to same table.
func TestStreamWriter6(t *testing.T) {
opt := getTestOptions("")
opt.BaseTableSize = 1 << 15
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
str := []string{"a", "b", "c"}
ver := uint64(0)
// The baseTable size is 32 KB (1<<15) and the max table size for level
// 6 table is 1 mb (look at newWrite function). Since all the tables
// will be written to level 6, we need to insert at least 1 mb of data.
// Setting keycount below 32 would cause this test to fail.
keyCount := 40
buf := z.NewBuffer(10<<20, "test")
defer func() { require.NoError(t, buf.Release()) }()
for i := range str {
for j := 0; j < keyCount; j++ {
ver++
kv := &pb.KV{
Key: bytes.Repeat([]byte(str[i]), int(db.opt.BaseTableSize)),
Value: []byte("val"),
Version: uint64(keyCount - j),
}
KVToBuffer(kv, buf)
}
}
// list has 3 pairs for equal keys. Since each Key has size equal to BaseTableSize
// we would have 6 tables, if keys are not equal. Here we should have 3 tables.
sw := db.NewStreamWriter()
require.NoError(t, sw.Prepare(), "sw.Prepare() failed")
require.NoError(t, sw.Write(buf), "sw.Write() failed")
require.NoError(t, sw.Flush(), "sw.Flush() failed")
tables := db.Tables()
require.Equal(t, 3, len(tables), "Count of tables not matching")
for _, tab := range tables {
require.Equal(t, keyCount, int(tab.KeyCount),
fmt.Sprintf("failed for level: %d", tab.Level))
}
require.NoError(t, db.Close())
db, err := Open(db.opt)
require.NoError(t, err)
require.NoError(t, db.Close())
})
}
// This test uses a StreamWriter without calling Flush() at the end.
func TestStreamWriterCancel(t *testing.T) {
opt := getTestOptions("")
opt.BaseTableSize = 1 << 15
runBadgerTest(t, &opt, func(t *testing.T, db *DB) {
str := []string{"a", "a", "b", "b", "c", "c"}
ver := 1
buf := z.NewBuffer(10<<20, "test")
defer func() { require.NoError(t, buf.Release()) }()
for i := range str {
kv := &pb.KV{
Key: bytes.Repeat([]byte(str[i]), int(db.opt.BaseTableSize)),
Value: []byte("val"),
Version: uint64(ver),
}
KVToBuffer(kv, buf)
ver = (ver + 1) % 2
}
sw := db.NewStreamWriter()
require.NoError(t, sw.Prepare(), "sw.Prepare() failed")
require.NoError(t, sw.Write(buf), "sw.Write() failed")
sw.Cancel()
// Use the API incorrectly.
sw1 := db.NewStreamWriter()
defer sw1.Cancel()
require.NoError(t, sw1.Prepare())
defer sw1.Cancel()
sw1.Flush()
})
}
func TestStreamDone(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
sw := db.NewStreamWriter()
require.NoError(t, sw.Prepare(), "sw.Prepare() failed")
var val [10]byte
rand.Read(val[:])
for i := 0; i < 10; i++ {
buf := z.NewBuffer(10<<20, "test")
defer func() { require.NoError(t, buf.Release()) }()
kv1 := &pb.KV{
Key: []byte(fmt.Sprintf("%d", i)),
Value: val[:],
Version: 1,
StreamId: uint32(i),
}
kv2 := &pb.KV{
StreamId: uint32(i),
StreamDone: true,
}
KVToBuffer(kv1, buf)
KVToBuffer(kv2, buf)
require.NoError(t, sw.Write(buf), "sw.Write() failed")
}
require.NoError(t, sw.Flush(), "sw.Flush() failed")
require.NoError(t, db.Close())
var err error
db, err = Open(db.opt)
require.NoError(t, err)
require.NoError(t, db.Close())
})
}
func TestSendOnClosedStream(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer func() {
require.NoError(t, os.RemoveAll(dir))
}()
opts := getTestOptions(dir)
db, err := Open(opts)
require.NoError(t, err)
sw := db.NewStreamWriter()
require.NoError(t, sw.Prepare(), "sw.Prepare() failed")
var val [10]byte
rand.Read(val[:])
buf := z.NewBuffer(10<<20, "test")
defer func() { require.NoError(t, buf.Release()) }()
kv1 := &pb.KV{
Key: []byte(fmt.Sprintf("%d", 1)),
Value: val[:],
Version: 1,
StreamId: uint32(1),
}
kv2 := &pb.KV{
StreamId: uint32(1),
StreamDone: true,
}
KVToBuffer(kv1, buf)
KVToBuffer(kv2, buf)
require.NoError(t, sw.Write(buf), "sw.Write() failed")
// Defer for panic.
defer func() {
require.NotNil(t, recover(), "should have panicked")
require.NoError(t, sw.Flush())
require.NoError(t, db.Close())
}()
// Send once stream is closed.
buf1 := z.NewBuffer(10<<20, "test")
defer func() { require.NoError(t, buf1.Release()) }()
kv1 = &pb.KV{
Key: []byte(fmt.Sprintf("%d", 2)),
Value: val[:],
Version: 1,
StreamId: uint32(1),
}
KVToBuffer(kv1, buf1)
require.NoError(t, sw.Write(buf1))
}
func TestSendOnClosedStream2(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer func() {
require.NoError(t, os.RemoveAll(dir))
}()
opts := getTestOptions(dir)
db, err := Open(opts)
require.NoError(t, err)
sw := db.NewStreamWriter()
require.NoError(t, sw.Prepare(), "sw.Prepare() failed")
var val [10]byte
rand.Read(val[:])
buf := z.NewBuffer(10<<20, "test")
defer func() { require.NoError(t, buf.Release()) }()
kv1 := &pb.KV{
Key: []byte(fmt.Sprintf("%d", 1)),
Value: val[:],
Version: 1,
StreamId: uint32(1),
}
kv2 := &pb.KV{
StreamId: uint32(1),
StreamDone: true,
}
kv3 := &pb.KV{
Key: []byte(fmt.Sprintf("%d", 2)),
Value: val[:],
Version: 1,
StreamId: uint32(1),
}
KVToBuffer(kv1, buf)
KVToBuffer(kv2, buf)
KVToBuffer(kv3, buf)
// Defer for panic.
defer func() {
require.NotNil(t, recover(), "should have panicked")
require.NoError(t, sw.Flush())
require.NoError(t, db.Close())
}()
require.NoError(t, sw.Write(buf), "sw.Write() failed")
}
func TestStreamWriterEncrypted(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
opts := DefaultOptions(dir)
defer removeDir(dir)
opts = opts.WithEncryptionKey([]byte("badgerkey16bytes"))
opts.BlockCacheSize = 100 << 20
opts.IndexCacheSize = 100 << 20
db, err := Open(opts)
require.NoError(t, err)
key := []byte("mykey")
value := []byte("myvalue")
buf := z.NewBuffer(10<<20, "test")
defer func() { require.NoError(t, buf.Release()) }()
KVToBuffer(&pb.KV{
Key: key,
Value: value,
Version: 20,
}, buf)
sw := db.NewStreamWriter()
require.NoError(t, sw.Prepare(), "Prepare failed")
require.NoError(t, sw.Write(buf), "Write failed")
require.NoError(t, sw.Flush(), "Flush failed")
err = db.View(func(txn *Txn) error {
item, err := txn.Get(key)
require.NoError(t, err)
val, err := item.ValueCopy(nil)
require.Equal(t, value, val)
require.NoError(t, err)
return nil
})
require.NoError(t, err, "Error while retrieving key")
require.NoError(t, db.Close())
db, err = Open(opts)
require.NoError(t, err)
require.NoError(t, db.Close())
}
// Test that stream writer does not crashes with large values in managed mode.
func TestStreamWriterWithLargeValue(t *testing.T) {
opts := DefaultOptions("")
opts.managedTxns = true
runBadgerTest(t, &opts, func(t *testing.T, db *DB) {
buf := z.NewBuffer(10<<20, "test")
defer func() { require.NoError(t, buf.Release()) }()
val := make([]byte, 10<<20)
_, err := rand.Read(val)
require.NoError(t, err)
KVToBuffer(&pb.KV{
Key: []byte("key"),
Value: val,
Version: 1,
}, buf)
sw := db.NewStreamWriter()
require.NoError(t, sw.Prepare(), "sw.Prepare() failed")
require.NoError(t, sw.Write(buf), "sw.Write() failed")
require.NoError(t, sw.Flush(), "sw.Flush() failed")
})
}
func TestStreamWriterIncremental(t *testing.T) {
addIncremental := func(t *testing.T, db *DB, keys [][]byte) {
buf := z.NewBuffer(10<<20, "test")
defer func() { require.NoError(t, buf.Release()) }()
for _, key := range keys {
KVToBuffer(&pb.KV{
Key: key,
Value: []byte("val"),
Version: 1,
}, buf)
}
// Now do an incremental stream write.
sw := db.NewStreamWriter()
require.NoError(t, sw.PrepareIncremental(), "sw.PrepareIncremental() failed")
require.NoError(t, sw.Write(buf), "sw.Write() failed")
require.NoError(t, sw.Flush(), "sw.Flush() failed")
}
t.Run("incremental on non-empty DB", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
buf := z.NewBuffer(10<<20, "test")
defer func() { require.NoError(t, buf.Release()) }()
KVToBuffer(&pb.KV{
Key: []byte("key-1"),
Value: []byte("val"),
Version: 1,
}, buf)
sw := db.NewStreamWriter()
require.NoError(t, sw.Prepare(), "sw.Prepare() failed")
require.NoError(t, sw.Write(buf), "sw.Write() failed")
require.NoError(t, sw.Flush(), "sw.Flush() failed")
addIncremental(t, db, [][]byte{[]byte("key-2")})
txn := db.NewTransaction(false)
defer txn.Discard()
_, err := txn.Get([]byte("key-1"))
require.NoError(t, err)
_, err = txn.Get([]byte("key-2"))
require.NoError(t, err)
})
})
t.Run("incremental on empty DB", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
addIncremental(t, db, [][]byte{[]byte("key-1")})
txn := db.NewTransaction(false)
defer txn.Discard()
_, err := txn.Get([]byte("key-1"))
require.NoError(t, err)
})
})
t.Run("multiple incremental", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
addIncremental(t, db, [][]byte{[]byte("a1"), []byte("c1")})
addIncremental(t, db, [][]byte{[]byte("a2"), []byte("c2")})
addIncremental(t, db, [][]byte{[]byte("a3"), []byte("c3")})
txn := db.NewTransaction(false)
defer txn.Discard()
_, err := txn.Get([]byte("a1"))
require.NoError(t, err)
_, err = txn.Get([]byte("c1"))
require.NoError(t, err)
_, err = txn.Get([]byte("a2"))
require.NoError(t, err)
_, err = txn.Get([]byte("c2"))
require.NoError(t, err)
_, err = txn.Get([]byte("a3"))
require.NoError(t, err)
_, err = txn.Get([]byte("c3"))
require.NoError(t, err)
})
})
t.Run("write between incremental writes", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
addIncremental(t, db, [][]byte{[]byte("a1"), []byte("c1")})
require.NoError(t, db.Update(func(txn *Txn) error {
return txn.Set([]byte("a3"), []byte("c3"))
}))
sw := db.NewStreamWriter()
defer sw.Cancel()
require.EqualError(t, sw.PrepareIncremental(), "Unable to do incremental writes because MemTable has data")
txn := db.NewTransaction(false)
defer txn.Discard()
_, err := txn.Get([]byte("a1"))
require.NoError(t, err)
_, err = txn.Get([]byte("c1"))
require.NoError(t, err)
_, err = txn.Get([]byte("a3"))
require.NoError(t, err)
})
})
t.Run("incremental writes > #levels", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
addIncremental(t, db, [][]byte{[]byte("a1"), []byte("c1")})
addIncremental(t, db, [][]byte{[]byte("a2"), []byte("c2")})
addIncremental(t, db, [][]byte{[]byte("a3"), []byte("c3")})
addIncremental(t, db, [][]byte{[]byte("a4"), []byte("c4")})
addIncremental(t, db, [][]byte{[]byte("a5"), []byte("c5")})
addIncremental(t, db, [][]byte{[]byte("a6"), []byte("c6")})
addIncremental(t, db, [][]byte{[]byte("a7"), []byte("c7")})
addIncremental(t, db, [][]byte{[]byte("a8"), []byte("c8")})
addIncremental(t, db, [][]byte{[]byte("a9"), []byte("c9")})
txn := db.NewTransaction(false)
defer txn.Discard()
_, err := txn.Get([]byte("a1"))
require.NoError(t, err)
_, err = txn.Get([]byte("c1"))
require.NoError(t, err)
_, err = txn.Get([]byte("a2"))
require.NoError(t, err)
_, err = txn.Get([]byte("c2"))
require.NoError(t, err)
_, err = txn.Get([]byte("a3"))
require.NoError(t, err)
_, err = txn.Get([]byte("c3"))
require.NoError(t, err)
_, err = txn.Get([]byte("a4"))
require.NoError(t, err)
_, err = txn.Get([]byte("c4"))
require.NoError(t, err)
_, err = txn.Get([]byte("a5"))
require.NoError(t, err)
_, err = txn.Get([]byte("c5"))
require.NoError(t, err)
_, err = txn.Get([]byte("a6"))
require.NoError(t, err)
_, err = txn.Get([]byte("c6"))
require.NoError(t, err)
_, err = txn.Get([]byte("a7"))
require.NoError(t, err)
_, err = txn.Get([]byte("c7"))
require.NoError(t, err)
_, err = txn.Get([]byte("a8"))
require.NoError(t, err)
_, err = txn.Get([]byte("c8"))
require.NoError(t, err)
_, err = txn.Get([]byte("a9"))
require.NoError(t, err)
_, err = txn.Get([]byte("c9"))
require.NoError(t, err)
})
})
t.Run("multiple incremental with older data first", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
buf := z.NewBuffer(10<<20, "test")
defer func() { require.NoError(t, buf.Release()) }()
KVToBuffer(&pb.KV{
Key: []byte("a1"),
Value: []byte("val1"),
Version: 11,
}, buf)
sw := db.NewStreamWriter()
require.NoError(t, sw.PrepareIncremental(), "sw.PrepareIncremental() failed")
require.NoError(t, sw.Write(buf), "sw.Write() failed")
require.NoError(t, sw.Flush(), "sw.Flush() failed")
buf2 := z.NewBuffer(10<<20, "test")
defer func() { require.NoError(t, buf2.Release()) }()
KVToBuffer(&pb.KV{
Key: []byte("a2"),
Value: []byte("val2"),
Version: 9,
}, buf2)
sw = db.NewStreamWriter()
require.NoError(t, sw.PrepareIncremental(), "sw.PrepareIncremental() failed")
require.NoError(t, sw.Write(buf2), "sw.Write() failed")
require.NoError(t, sw.Flush(), "sw.Flush() failed")
// This will move the maxTs to 10 (earlier, without the fix)
require.NoError(t, db.Update(func(txn *Txn) error {
return txn.Set([]byte("a1"), []byte("val3"))
}))
// This will move the maxTs to 11 (earliler, without the fix)
require.NoError(t, db.Update(func(txn *Txn) error {
return txn.Set([]byte("a3"), []byte("val4"))
}))
// And now, the first write with val1 will resurface (without the fix)
require.NoError(t, db.View(func(txn *Txn) error {
item, err := txn.Get([]byte("a1"))
require.NoError(t, err)
val, err := item.ValueCopy(nil)
require.NoError(t, err)
require.Equal(t, "val3", string(val))
return nil
}))
})
})
}
================================================
FILE: structs.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"encoding/binary"
"fmt"
"time"
"unsafe"
)
type valuePointer struct {
Fid uint32
Len uint32
Offset uint32
}
const vptrSize = unsafe.Sizeof(valuePointer{})
func (p valuePointer) Less(o valuePointer) bool {
if p.Fid != o.Fid {
return p.Fid < o.Fid
}
if p.Offset != o.Offset {
return p.Offset < o.Offset
}
return p.Len < o.Len
}
func (p valuePointer) IsZero() bool {
return p.Fid == 0 && p.Offset == 0 && p.Len == 0
}
// Encode encodes Pointer into byte buffer.
func (p valuePointer) Encode() []byte {
b := make([]byte, vptrSize)
// Copy over the content from p to b.
*(*valuePointer)(unsafe.Pointer(&b[0])) = p
return b
}
// Decode decodes the value pointer into the provided byte buffer.
func (p *valuePointer) Decode(b []byte) {
// Copy over data from b into p. Using *p=unsafe.pointer(...) leads to
// pointer alignment issues. See https://github.com/dgraph-io/badger/issues/1096
// and comment https://github.com/dgraph-io/badger/pull/1097#pullrequestreview-307361714
copy(((*[vptrSize]byte)(unsafe.Pointer(p))[:]), b[:vptrSize])
}
// header is used in value log as a header before Entry.
type header struct {
klen uint32
vlen uint32
expiresAt uint64
meta byte
userMeta byte
}
const (
// Maximum possible size of the header. The maximum size of header struct will be 18 but the
// maximum size of varint encoded header will be 22.
maxHeaderSize = 22
)
// Encode encodes the header into []byte. The provided []byte should be at least 5 bytes. The
// function will panic if out []byte isn't large enough to hold all the values.
// The encoded header looks like
// +------+----------+------------+--------------+-----------+
// | Meta | UserMeta | Key Length | Value Length | ExpiresAt |
// +------+----------+------------+--------------+-----------+
func (h header) Encode(out []byte) int {
out[0], out[1] = h.meta, h.userMeta
index := 2
index += binary.PutUvarint(out[index:], uint64(h.klen))
index += binary.PutUvarint(out[index:], uint64(h.vlen))
index += binary.PutUvarint(out[index:], h.expiresAt)
return index
}
// Decode decodes the given header from the provided byte slice.
// Returns the number of bytes read.
func (h *header) Decode(buf []byte) int {
h.meta, h.userMeta = buf[0], buf[1]
index := 2
klen, count := binary.Uvarint(buf[index:])
h.klen = uint32(klen)
index += count
vlen, count := binary.Uvarint(buf[index:])
h.vlen = uint32(vlen)
index += count
h.expiresAt, count = binary.Uvarint(buf[index:])
return index + count
}
// DecodeFrom reads the header from the hashReader.
// Returns the number of bytes read.
func (h *header) DecodeFrom(reader *hashReader) (int, error) {
var err error
h.meta, err = reader.ReadByte()
if err != nil {
return 0, err
}
h.userMeta, err = reader.ReadByte()
if err != nil {
return 0, err
}
klen, err := binary.ReadUvarint(reader)
if err != nil {
return 0, err
}
h.klen = uint32(klen)
vlen, err := binary.ReadUvarint(reader)
if err != nil {
return 0, err
}
h.vlen = uint32(vlen)
h.expiresAt, err = binary.ReadUvarint(reader)
if err != nil {
return 0, err
}
return reader.bytesRead, nil
}
// Entry provides Key, Value, UserMeta and ExpiresAt. This struct can be used by
// the user to set data.
type Entry struct {
Key []byte
Value []byte
ExpiresAt uint64 // time.Unix
version uint64
offset uint32 // offset is an internal field.
UserMeta byte
meta byte
// Fields maintained internally.
hlen int // Length of the header.
valThreshold int64
}
func (e *Entry) isZero() bool {
return len(e.Key) == 0
}
func (e *Entry) estimateSizeAndSetThreshold(threshold int64) int64 {
if e.valThreshold == 0 {
e.valThreshold = threshold
}
k := int64(len(e.Key))
v := int64(len(e.Value))
if v < e.valThreshold {
return k + v + 2 // Meta, UserMeta
}
return k + 12 + 2 // 12 for ValuePointer, 2 for metas.
}
func (e *Entry) skipVlogAndSetThreshold(threshold int64) bool {
if e.valThreshold == 0 {
e.valThreshold = threshold
}
return int64(len(e.Value)) < e.valThreshold
}
//nolint:unused
func (e Entry) print(prefix string) {
fmt.Printf("%s Key: %s Meta: %d UserMeta: %d Offset: %d len(val)=%d",
prefix, e.Key, e.meta, e.UserMeta, e.offset, len(e.Value))
}
// NewEntry creates a new entry with key and value passed in args. This newly created entry can be
// set in a transaction by calling txn.SetEntry(). All other properties of Entry can be set by
// calling WithMeta, WithDiscard, WithTTL methods on it.
// This function uses key and value reference, hence users must
// not modify key and value until the end of transaction.
func NewEntry(key, value []byte) *Entry {
return &Entry{
Key: key,
Value: value,
}
}
// WithMeta adds meta data to Entry e. This byte is stored alongside the key
// and can be used as an aid to interpret the value or store other contextual
// bits corresponding to the key-value pair of entry.
func (e *Entry) WithMeta(meta byte) *Entry {
e.UserMeta = meta
return e
}
// WithDiscard adds a marker to Entry e. This means all the previous versions of the key (of the
// Entry) will be eligible for garbage collection.
// This method is only useful if you have set a higher limit for options.NumVersionsToKeep. The
// default setting is 1, in which case, this function doesn't add any more benefit. If however, you
// have a higher setting for NumVersionsToKeep (in Dgraph, we set it to infinity), you can use this
// method to indicate that all the older versions can be discarded and removed during compactions.
func (e *Entry) WithDiscard() *Entry {
e.meta = bitDiscardEarlierVersions
return e
}
// WithTTL adds time to live duration to Entry e. Entry stored with a TTL would automatically expire
// after the time has elapsed, and will be eligible for garbage collection.
func (e *Entry) WithTTL(dur time.Duration) *Entry {
e.ExpiresAt = uint64(time.Now().Add(dur).Unix())
return e
}
// withMergeBit sets merge bit in entry's metadata. This
// function is called by MergeOperator's Add method.
func (e *Entry) withMergeBit() *Entry {
e.meta = bitMergeEntry
return e
}
================================================
FILE: structs_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"math"
"reflect"
"testing"
"github.com/stretchr/testify/require"
)
// Regression test for github.com/dgraph-io/badger/pull/1800
func TestLargeEncode(t *testing.T) {
var headerEnc [maxHeaderSize]byte
h := header{math.MaxUint32, math.MaxUint32, math.MaxUint64, math.MaxUint8, math.MaxUint8}
require.NotPanics(t, func() { _ = h.Encode(headerEnc[:]) })
}
func TestNumFieldsHeader(t *testing.T) {
// maxHeaderSize must correspond with any changes made to header
require.Equal(t, 5, reflect.TypeOf(header{}).NumField())
}
================================================
FILE: table/README.md
================================================
Size of table is 123,217,667 bytes for all benchmarks.
# BenchmarkRead
```sh
$ go test -bench ^BenchmarkRead$ -run ^$ -count 3
goos: linux
goarch: amd64
pkg: github.com/dgraph-io/badger/table
BenchmarkRead-16 10 154074944 ns/op
BenchmarkRead-16 10 154340411 ns/op
BenchmarkRead-16 10 151914489 ns/op
PASS
ok github.com/dgraph-io/badger/table 22.467s
```
Size of table is 123,217,667 bytes, which is ~118MB.
The rate is ~762MB/s using LoadToRAM (when table is in RAM).
To read a 64MB table, this would take ~0.084s, which is negligible.
# BenchmarkReadAndBuild
```sh
$ go test -bench BenchmarkReadAndBuild -run ^$ -count 3
goos: linux
goarch: amd64
pkg: github.com/dgraph-io/badger/table
BenchmarkReadAndBuild-16 1 1026755231 ns/op
BenchmarkReadAndBuild-16 1 1009543316 ns/op
BenchmarkReadAndBuild-16 1 1039920546 ns/op
PASS
ok github.com/dgraph-io/badger/table 12.081s
```
The rate is ~123MB/s. To build a 64MB table, this would take ~0.56s. Note that this does NOT include
the flushing of the table to disk. All we are doing above is reading one table (which is in RAM) and
write one table in memory.
The table building takes 0.56-0.084s ~ 0.4823s.
# BenchmarkReadMerged
Below, we merge 5 tables. The total size remains unchanged at ~122M.
```sh
$ go test -bench ReadMerged -run ^$ -count 3
goos: linux
goarch: amd64
pkg: github.com/dgraph-io/badger/table
BenchmarkReadMerged-16 2 977588975 ns/op
BenchmarkReadMerged-16 2 982140738 ns/op
BenchmarkReadMerged-16 2 962046017 ns/op
PASS
ok github.com/dgraph-io/badger/table 27.433s
```
The rate is ~120MB/s. To read a 64MB table using merge iterator, this would take ~0.53s.
# BenchmarkRandomRead
```sh
go test -bench BenchmarkRandomRead$ -run ^$ -count 3
goos: linux
goarch: amd64
pkg: github.com/dgraph-io/badger/table
BenchmarkRandomRead-16 500000 2645 ns/op
BenchmarkRandomRead-16 500000 2648 ns/op
BenchmarkRandomRead-16 500000 2614 ns/op
PASS
ok github.com/dgraph-io/badger/table 50.850s
```
For random read benchmarking, we are randomly reading a key and verifying its value.
# DB Open benchmark
1. Create badger DB with 2 billion key-value pairs (about 380GB of data)
```sh
badger fill -m 2000 --dir="/tmp/data" --sorted
```
2. Clear buffers and swap memory
```sh
free -mh && sync && echo 3 | sudo tee /proc/sys/vm/drop_caches && sudo swapoff -a && sudo swapon -a && free -mh
```
Also flush disk buffers
```sh
blockdev --flushbufs /dev/nvme0n1p4
```
3. Run the benchmark
```sh
go test -run=^$ github.com/dgraph-io/badger -bench ^BenchmarkDBOpen$ -benchdir="/tmp/data" -v
badger 2019/06/04 17:15:56 INFO: 126 tables out of 1028 opened in 3.017s
badger 2019/06/04 17:15:59 INFO: 257 tables out of 1028 opened in 6.014s
badger 2019/06/04 17:16:02 INFO: 387 tables out of 1028 opened in 9.017s
badger 2019/06/04 17:16:05 INFO: 516 tables out of 1028 opened in 12.025s
badger 2019/06/04 17:16:08 INFO: 645 tables out of 1028 opened in 15.013s
badger 2019/06/04 17:16:11 INFO: 775 tables out of 1028 opened in 18.008s
badger 2019/06/04 17:16:14 INFO: 906 tables out of 1028 opened in 21.003s
badger 2019/06/04 17:16:17 INFO: All 1028 tables opened in 23.851s
badger 2019/06/04 17:16:17 INFO: Replaying file id: 1998 at offset: 332000
badger 2019/06/04 17:16:17 INFO: Replay took: 9.81µs
goos: linux
goarch: amd64
pkg: github.com/dgraph-io/badger
BenchmarkDBOpen-16 1 23930082140 ns/op
PASS
ok github.com/dgraph-io/badger 24.076s
```
It takes about 23.851s to open a DB with 2 billion sorted key-value entries.
================================================
FILE: table/builder.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package table
import (
"crypto/aes"
"errors"
"math"
"runtime"
"sync"
"sync/atomic"
"unsafe"
fbs "github.com/google/flatbuffers/go"
"github.com/klauspost/compress/s2"
"google.golang.org/protobuf/proto"
"github.com/dgraph-io/badger/v4/fb"
"github.com/dgraph-io/badger/v4/options"
"github.com/dgraph-io/badger/v4/pb"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2/z"
)
const (
KB = 1024
MB = KB * 1024
// When a block is encrypted, it's length increases. We add 256 bytes of padding to
// handle cases when block size increases. This is an approximate number.
padding = 256
)
type header struct {
overlap uint16 // Overlap with base key.
diff uint16 // Length of the diff.
}
const headerSize = uint16(unsafe.Sizeof(header{}))
// Encode encodes the header.
func (h header) Encode() []byte {
var b [4]byte
*(*header)(unsafe.Pointer(&b[0])) = h
return b[:]
}
// Decode decodes the header.
func (h *header) Decode(buf []byte) {
// Copy over data from buf into h. Using *h=unsafe.pointer(...) leads to
// pointer alignment issues. See https://github.com/dgraph-io/badger/issues/1096
// and comment https://github.com/dgraph-io/badger/pull/1097#pullrequestreview-307361714
copy(((*[headerSize]byte)(unsafe.Pointer(h))[:]), buf[:headerSize])
}
// bblock represents a block that is being compressed/encrypted in the background.
type bblock struct {
data []byte
baseKey []byte // Base key for the current block.
entryOffsets []uint32 // Offsets of entries present in current block.
end int // Points to the end offset of the block.
}
// Builder is used in building a table.
type Builder struct {
// Typically tens or hundreds of meg. This is for one single file.
alloc *z.Allocator
curBlock *bblock
compressedSize atomic.Uint32
uncompressedSize atomic.Uint32
lenOffsets uint32
keyHashes []uint32 // Used for building the bloomfilter.
opts *Options
maxVersion uint64
onDiskSize uint32
staleDataSize int
// Used to concurrently compress/encrypt blocks.
wg sync.WaitGroup
blockChan chan *bblock
blockList []*bblock
}
func (b *Builder) allocate(need int) []byte {
bb := b.curBlock
if len(bb.data[bb.end:]) < need {
// We need to reallocate. 1GB is the max size that the allocator can allocate.
// While reallocating, if doubling exceeds that limit, then put the upper bound on it.
sz := 2 * len(bb.data)
if sz > (1 << 30) {
sz = 1 << 30
}
if bb.end+need > sz {
sz = bb.end + need
}
tmp := b.alloc.Allocate(sz)
copy(tmp, bb.data)
bb.data = tmp
}
bb.end += need
return bb.data[bb.end-need : bb.end]
}
// append appends to curBlock.data
func (b *Builder) append(data []byte) {
dst := b.allocate(len(data))
y.AssertTrue(len(data) == copy(dst, data))
}
const maxAllocatorInitialSz = 256 << 20
// NewTableBuilder makes a new TableBuilder.
func NewTableBuilder(opts Options) *Builder {
sz := 2 * int(opts.TableSize)
if sz > maxAllocatorInitialSz {
sz = maxAllocatorInitialSz
}
b := &Builder{
alloc: opts.AllocPool.Get(sz, "TableBuilder"),
opts: &opts,
}
b.alloc.Tag = "Builder"
b.curBlock = &bblock{
data: b.alloc.Allocate(opts.BlockSize + padding),
}
b.opts.tableCapacity = uint64(float64(b.opts.TableSize) * 0.95)
// If encryption or compression is not enabled, do not start compression/encryption goroutines
// and write directly to the buffer.
if b.opts.Compression == options.None && b.opts.DataKey == nil {
return b
}
count := 2 * runtime.NumCPU()
b.blockChan = make(chan *bblock, count*2)
b.wg.Add(count)
for i := 0; i < count; i++ {
go b.handleBlock()
}
return b
}
func maxEncodedLen(ctype options.CompressionType, sz int) int {
switch ctype {
case options.Snappy:
return s2.MaxEncodedLen(sz)
case options.ZSTD:
return y.ZSTDCompressBound(sz)
}
return sz
}
func (b *Builder) handleBlock() {
defer b.wg.Done()
doCompress := b.opts.Compression != options.None
for item := range b.blockChan {
// Extract the block.
blockBuf := item.data[:item.end]
// Compress the block.
if doCompress {
out, err := b.compressData(blockBuf)
y.Check(err)
blockBuf = out
}
if b.shouldEncrypt() {
out, err := b.encrypt(blockBuf)
y.Check(y.Wrapf(err, "Error while encrypting block in table builder."))
blockBuf = out
}
// BlockBuf should always less than or equal to allocated space. If the blockBuf is greater
// than allocated space that means the data from this block cannot be stored in its
// existing location.
allocatedSpace := maxEncodedLen(b.opts.Compression, (item.end)) + padding + 1
y.AssertTrue(len(blockBuf) <= allocatedSpace)
// blockBuf was allocated on allocator. So, we don't need to copy it over.
item.data = blockBuf
item.end = len(blockBuf)
b.compressedSize.Add(uint32(len(blockBuf)))
}
}
// Close closes the TableBuilder.
func (b *Builder) Close() {
b.opts.AllocPool.Return(b.alloc)
}
// Empty returns whether it's empty.
func (b *Builder) Empty() bool { return len(b.keyHashes) == 0 }
// keyDiff returns a suffix of newKey that is different from b.baseKey.
func (b *Builder) keyDiff(newKey []byte) []byte {
var i int
for i = 0; i < len(newKey) && i < len(b.curBlock.baseKey); i++ {
if newKey[i] != b.curBlock.baseKey[i] {
break
}
}
return newKey[i:]
}
func (b *Builder) addHelper(key []byte, v y.ValueStruct, vpLen uint32) {
b.keyHashes = append(b.keyHashes, y.Hash(y.ParseKey(key)))
if version := y.ParseTs(key); version > b.maxVersion {
b.maxVersion = version
}
// diffKey stores the difference of key with baseKey.
var diffKey []byte
if len(b.curBlock.baseKey) == 0 {
// Make a copy. Builder should not keep references. Otherwise, caller has to be very careful
// and will have to make copies of keys every time they add to builder, which is even worse.
b.curBlock.baseKey = append(b.curBlock.baseKey[:0], key...)
diffKey = key
} else {
diffKey = b.keyDiff(key)
}
y.AssertTrue(len(key)-len(diffKey) <= math.MaxUint16)
y.AssertTrue(len(diffKey) <= math.MaxUint16)
h := header{
overlap: uint16(len(key) - len(diffKey)),
diff: uint16(len(diffKey)),
}
// store current entry's offset
b.curBlock.entryOffsets = append(b.curBlock.entryOffsets, uint32(b.curBlock.end))
// Layout: header, diffKey, value.
b.append(h.Encode())
b.append(diffKey)
dst := b.allocate(int(v.EncodedSize()))
v.Encode(dst)
// Add the vpLen to the onDisk size. We'll add the size of the block to
// onDisk size in Finish() function.
b.onDiskSize += vpLen
}
/*
Structure of Block.
+-------------------+---------------------+--------------------+--------------+------------------+
| Entry1 | Entry2 | Entry3 | Entry4 | Entry5 |
+-------------------+---------------------+--------------------+--------------+------------------+
| Entry6 | ... | ... | ... | EntryN |
+-------------------+---------------------+--------------------+--------------+------------------+
| Block Meta(contains list of offsets used| Block Meta Size | Block | Checksum Size |
| to perform binary search in the block) | (4 Bytes) | Checksum | (4 Bytes) |
+-----------------------------------------+--------------------+--------------+------------------+
*/
// In case the data is encrypted, the "IV" is added to the end of the block.
func (b *Builder) finishBlock() {
if len(b.curBlock.entryOffsets) == 0 {
return
}
// Append the entryOffsets and its length.
b.append(y.U32SliceToBytes(b.curBlock.entryOffsets))
b.append(y.U32ToBytes(uint32(len(b.curBlock.entryOffsets))))
checksum := b.calculateChecksum(b.curBlock.data[:b.curBlock.end])
// Append the block checksum and its length.
b.append(checksum)
b.append(y.U32ToBytes(uint32(len(checksum))))
b.blockList = append(b.blockList, b.curBlock)
b.uncompressedSize.Add(uint32(b.curBlock.end))
// Add length of baseKey (rounded to next multiple of 4 because of alignment).
// Add another 40 Bytes, these additional 40 bytes consists of
// 12 bytes of metadata of flatbuffer
// 8 bytes for Key in flat buffer
// 8 bytes for offset
// 8 bytes for the len
// 4 bytes for the size of slice while SliceAllocate
b.lenOffsets += uint32(int(math.Ceil(float64(len(b.curBlock.baseKey))/4))*4) + 40
// If compression/encryption is enabled, we need to send the block to the blockChan.
if b.blockChan != nil {
b.blockChan <- b.curBlock
}
}
func (b *Builder) shouldFinishBlock(key []byte, value y.ValueStruct) bool {
// If there is no entry till now, we will return false.
if len(b.curBlock.entryOffsets) <= 0 {
return false
}
// Integer overflow check for statements below.
y.AssertTrue((uint32(len(b.curBlock.entryOffsets))+1)*4+4+8+4 < math.MaxUint32)
// We should include current entry also in size, that's why +1 to len(b.entryOffsets).
entriesOffsetsSize := uint32((len(b.curBlock.entryOffsets)+1)*4 +
4 + // size of list
8 + // Sum64 in checksum proto
4) // checksum length
estimatedSize := uint32(b.curBlock.end) + uint32(6 /*header size for entry*/) +
uint32(len(key)) + value.EncodedSize() + entriesOffsetsSize
if b.shouldEncrypt() {
// IV is added at the end of the block, while encrypting.
// So, size of IV is added to estimatedSize.
estimatedSize += aes.BlockSize
}
// Integer overflow check for table size.
y.AssertTrue(uint64(b.curBlock.end)+uint64(estimatedSize) < math.MaxUint32)
return estimatedSize > uint32(b.opts.BlockSize)
}
// AddStaleKey is same is Add function but it also increments the internal
// staleDataSize counter. This value will be used to prioritize this table for
// compaction.
func (b *Builder) AddStaleKey(key []byte, v y.ValueStruct, valueLen uint32) {
// Rough estimate based on how much space it will occupy in the SST.
b.staleDataSize += len(key) + len(v.Value) + 4 /* entry offset */ + 4 /* header size */
b.addInternal(key, v, valueLen, true)
}
// Add adds a key-value pair to the block.
func (b *Builder) Add(key []byte, value y.ValueStruct, valueLen uint32) {
b.addInternal(key, value, valueLen, false)
}
func (b *Builder) addInternal(key []byte, value y.ValueStruct, valueLen uint32, isStale bool) {
if b.shouldFinishBlock(key, value) {
if isStale {
// This key will be added to tableIndex and it is stale.
b.staleDataSize += len(key) + 4 /* len */ + 4 /* offset */
}
b.finishBlock()
// Create a new block and start writing.
b.curBlock = &bblock{
data: b.alloc.Allocate(b.opts.BlockSize + padding),
}
}
b.addHelper(key, value, valueLen)
}
// TODO: vvv this was the comment on ReachedCapacity.
// FinalSize returns the *rough* final size of the array, counting the header which is
// not yet written.
// TODO: Look into why there is a discrepancy. I suspect it is because of Write(empty, empty)
// at the end. The diff can vary.
// ReachedCapacity returns true if we... roughly (?) reached capacity?
func (b *Builder) ReachedCapacity() bool {
// If encryption/compression is enabled then use the compressed size.
sumBlockSizes := b.compressedSize.Load()
if b.opts.Compression == options.None && b.opts.DataKey == nil {
sumBlockSizes = b.uncompressedSize.Load()
}
blocksSize := sumBlockSizes + // actual length of current buffer
uint32(len(b.curBlock.entryOffsets)*4) + // all entry offsets size
4 + // count of all entry offsets
8 + // checksum bytes
4 // checksum length
estimateSz := blocksSize +
4 + // Index length
b.lenOffsets
return uint64(estimateSz) > b.opts.tableCapacity
}
// Finish finishes the table by appending the index.
/*
The table structure looks like
+---------+------------+-----------+---------------+
| Block 1 | Block 2 | Block 3 | Block 4 |
+---------+------------+-----------+---------------+
| Block 5 | Block 6 | Block ... | Block N |
+---------+------------+-----------+---------------+
| Index | Index Size | Checksum | Checksum Size |
+---------+------------+-----------+---------------+
*/
// In case the data is encrypted, the "IV" is added to the end of the index.
func (b *Builder) Finish() []byte {
bd := b.Done()
buf := make([]byte, bd.Size)
written := bd.Copy(buf)
y.AssertTrue(written == len(buf))
return buf
}
type buildData struct {
blockList []*bblock
index []byte
checksum []byte
Size int
alloc *z.Allocator
}
func (bd *buildData) Copy(dst []byte) int {
var written int
for _, bl := range bd.blockList {
written += copy(dst[written:], bl.data[:bl.end])
}
written += copy(dst[written:], bd.index)
written += copy(dst[written:], y.U32ToBytes(uint32(len(bd.index))))
written += copy(dst[written:], bd.checksum)
written += copy(dst[written:], y.U32ToBytes(uint32(len(bd.checksum))))
return written
}
func (b *Builder) Done() buildData {
b.finishBlock() // This will never start a new block.
if b.blockChan != nil {
close(b.blockChan)
}
// Wait for block handler to finish.
b.wg.Wait()
if len(b.blockList) == 0 {
return buildData{}
}
bd := buildData{
blockList: b.blockList,
alloc: b.alloc,
}
var f y.Filter
if b.opts.BloomFalsePositive > 0 {
bits := y.BloomBitsPerKey(len(b.keyHashes), b.opts.BloomFalsePositive)
f = y.NewFilter(b.keyHashes, bits)
}
index, dataSize := b.buildIndex(f)
var err error
if b.shouldEncrypt() {
index, err = b.encrypt(index)
y.Check(err)
}
checksum := b.calculateChecksum(index)
bd.index = index
bd.checksum = checksum
bd.Size = int(dataSize) + len(index) + len(checksum) + 4 + 4
return bd
}
func (b *Builder) calculateChecksum(data []byte) []byte {
// Build checksum for the index.
checksum := pb.Checksum{
// TODO: The checksum type should be configurable from the
// options.
// We chose to use CRC32 as the default option because
// it performed better compared to xxHash64.
// See the BenchmarkChecksum in table_test.go file
// Size => 1024 B 2048 B
// CRC32 => 63.7 ns/op 112 ns/op
// xxHash64 => 87.5 ns/op 158 ns/op
Sum: y.CalculateChecksum(data, pb.Checksum_CRC32C),
Algo: pb.Checksum_CRC32C,
}
// Write checksum to the file.
chksum, err := proto.Marshal(&checksum)
y.Check(err)
// Write checksum size.
return chksum
}
// DataKey returns datakey of the builder.
func (b *Builder) DataKey() *pb.DataKey {
return b.opts.DataKey
}
func (b *Builder) Opts() *Options {
return b.opts
}
// encrypt will encrypt the given data and appends IV to the end of the encrypted data.
// This should be only called only after checking shouldEncrypt method.
func (b *Builder) encrypt(data []byte) ([]byte, error) {
iv, err := y.GenerateIV()
if err != nil {
return data, y.Wrapf(err, "Error while generating IV in Builder.encrypt")
}
needSz := len(data) + len(iv)
dst := b.alloc.Allocate(needSz)
if err = y.XORBlock(dst[:len(data)], data, b.DataKey().Data, iv); err != nil {
return data, y.Wrapf(err, "Error while encrypting in Builder.encrypt")
}
y.AssertTrue(len(iv) == copy(dst[len(data):], iv))
return dst, nil
}
// shouldEncrypt tells us whether to encrypt the data or not.
// We encrypt only if the data key exist. Otherwise, not.
func (b *Builder) shouldEncrypt() bool {
return b.opts.DataKey != nil
}
// compressData compresses the given data.
func (b *Builder) compressData(data []byte) ([]byte, error) {
switch b.opts.Compression {
case options.None:
return data, nil
case options.Snappy:
sz := s2.MaxEncodedLen(len(data))
dst := b.alloc.Allocate(sz)
return s2.EncodeSnappy(dst, data), nil
case options.ZSTD:
sz := y.ZSTDCompressBound(len(data))
dst := b.alloc.Allocate(sz)
return y.ZSTDCompress(dst, data, b.opts.ZSTDCompressionLevel)
}
return nil, errors.New("Unsupported compression type")
}
func (b *Builder) buildIndex(bloom []byte) ([]byte, uint32) {
builder := fbs.NewBuilder(3 << 20)
boList, dataSize := b.writeBlockOffsets(builder)
// Write block offset vector the the idxBuilder.
fb.TableIndexStartOffsetsVector(builder, len(boList))
// Write individual block offsets in reverse order to work around how Flatbuffers expects it.
for i := len(boList) - 1; i >= 0; i-- {
builder.PrependUOffsetT(boList[i])
}
boEnd := builder.EndVector(len(boList))
var bfoff fbs.UOffsetT
// Write the bloom filter.
if len(bloom) > 0 {
bfoff = builder.CreateByteVector(bloom)
}
b.onDiskSize += dataSize
fb.TableIndexStart(builder)
fb.TableIndexAddOffsets(builder, boEnd)
fb.TableIndexAddBloomFilter(builder, bfoff)
fb.TableIndexAddMaxVersion(builder, b.maxVersion)
fb.TableIndexAddUncompressedSize(builder, b.uncompressedSize.Load())
fb.TableIndexAddKeyCount(builder, uint32(len(b.keyHashes)))
fb.TableIndexAddOnDiskSize(builder, b.onDiskSize)
fb.TableIndexAddStaleDataSize(builder, uint32(b.staleDataSize))
builder.Finish(fb.TableIndexEnd(builder))
buf := builder.FinishedBytes()
index := fb.GetRootAsTableIndex(buf, 0)
// Mutate the ondisk size to include the size of the index as well.
y.AssertTrue(index.MutateOnDiskSize(index.OnDiskSize() + uint32(len(buf))))
return buf, dataSize
}
// writeBlockOffsets writes all the blockOffets in b.offsets and returns the
// offsets for the newly written items.
func (b *Builder) writeBlockOffsets(builder *fbs.Builder) ([]fbs.UOffsetT, uint32) {
var startOffset uint32
var uoffs []fbs.UOffsetT
for _, bl := range b.blockList {
uoff := b.writeBlockOffset(builder, bl, startOffset)
uoffs = append(uoffs, uoff)
startOffset += uint32(bl.end)
}
return uoffs, startOffset
}
// writeBlockOffset writes the given key,offset,len triple to the indexBuilder.
// It returns the offset of the newly written blockoffset.
func (b *Builder) writeBlockOffset(
builder *fbs.Builder, bl *bblock, startOffset uint32) fbs.UOffsetT {
// Write the key to the buffer.
k := builder.CreateByteVector(bl.baseKey)
// Build the blockOffset.
fb.BlockOffsetStart(builder)
fb.BlockOffsetAddKey(builder, k)
fb.BlockOffsetAddOffset(builder, startOffset)
fb.BlockOffsetAddLen(builder, uint32(bl.end))
return fb.BlockOffsetEnd(builder)
}
================================================
FILE: table/builder_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package table
import (
"fmt"
"math/rand"
"os"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/dgraph-io/badger/v4/fb"
"github.com/dgraph-io/badger/v4/options"
"github.com/dgraph-io/badger/v4/pb"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2"
)
func TestTableIndex(t *testing.T) {
rand.Seed(time.Now().Unix())
keysCount := 100000
key := make([]byte, 32)
_, err := rand.Read(key)
require.NoError(t, err)
cache, err := ristretto.NewCache[uint64, *fb.TableIndex](&ristretto.Config[uint64, *fb.TableIndex]{
NumCounters: 1000,
MaxCost: 1 << 20,
BufferItems: 64,
})
require.NoError(t, err)
subTest := []struct {
name string
opts Options
}{
{
name: "No encryption/compression",
opts: Options{
BlockSize: 4 * 1024,
BloomFalsePositive: 0.01,
TableSize: 30 << 20,
},
},
{
// Encryption mode.
name: "Only encryption",
opts: Options{
BlockSize: 4 * 1024,
BloomFalsePositive: 0.01,
TableSize: 30 << 20,
DataKey: &pb.DataKey{Data: key},
IndexCache: cache,
},
},
{
// Compression mode.
name: "Only compression",
opts: Options{
BlockSize: 4 * 1024,
BloomFalsePositive: 0.01,
TableSize: 30 << 20,
Compression: options.ZSTD,
ZSTDCompressionLevel: 3,
},
},
{
// Compression mode and encryption.
name: "Compression and encryption",
opts: Options{
BlockSize: 4 * 1024,
BloomFalsePositive: 0.01,
TableSize: 30 << 20,
Compression: options.ZSTD,
ZSTDCompressionLevel: 3,
DataKey: &pb.DataKey{Data: key},
IndexCache: cache,
},
},
}
for _, tt := range subTest {
t.Run(tt.name, func(t *testing.T) {
opt := tt.opts
builder := NewTableBuilder(opt)
defer builder.Close()
filename := fmt.Sprintf("%s%c%d.sst", os.TempDir(), os.PathSeparator, rand.Uint32())
blockFirstKeys := make([][]byte, 0)
blockCount := 0
for i := 0; i < keysCount; i++ {
k := y.KeyWithTs([]byte(fmt.Sprintf("%016x", i)), uint64(i+1))
v := fmt.Sprintf("%d", i)
vs := y.ValueStruct{Value: []byte(v)}
if i == 0 { // This is first key for first block.
blockFirstKeys = append(blockFirstKeys, k)
blockCount = 1
} else if builder.shouldFinishBlock(k, vs) {
blockCount++
blockFirstKeys = append(blockFirstKeys, k)
}
builder.Add(k, vs, 0)
}
tbl, err := CreateTable(filename, builder)
require.NoError(t, err, "unable to open table")
if opt.DataKey == nil {
// key id is zero if there is no datakey.
require.Equal(t, tbl.KeyID(), uint64(0))
}
// Ensure index is built correctly
require.Equal(t, blockCount, tbl.offsetsLength())
idx, err := tbl.readTableIndex()
require.NoError(t, err)
for i := 0; i < idx.OffsetsLength(); i++ {
var bo fb.BlockOffset
require.True(t, idx.Offsets(&bo, i))
require.Equal(t, blockFirstKeys[i], bo.KeyBytes())
}
require.Equal(t, keysCount, int(tbl.MaxVersion()))
tbl.Close(-1)
require.NoError(t, os.RemoveAll(filename))
})
}
}
func TestInvalidCompression(t *testing.T) {
keyPrefix := "key"
opts := Options{BlockSize: 4 << 10, Compression: options.ZSTD}
tbl := buildTestTable(t, keyPrefix, 1000, opts)
defer func() { require.NoError(t, tbl.DecrRef()) }()
mf := tbl.MmapFile
t.Run("with correct decompression algo", func(t *testing.T) {
_, err := OpenTable(mf, opts)
require.NoError(t, err)
})
t.Run("with incorrect decompression algo", func(t *testing.T) {
// Set incorrect compression algorithm.
opts.Compression = options.Snappy
_, err := OpenTable(mf, opts)
require.Error(t, err)
})
}
func BenchmarkBuilder(b *testing.B) {
rand.Seed(time.Now().Unix())
key := func(i int) []byte {
return []byte(fmt.Sprintf("%032d", i))
}
val := make([]byte, 32)
rand.Read(val)
vs := y.ValueStruct{Value: val}
keysCount := 1300000 // This number of entries consumes ~64MB of memory.
var keyList [][]byte
for i := 0; i < keysCount; i++ {
keyList = append(keyList, key(i))
}
bench := func(b *testing.B, opt *Options) {
b.SetBytes(int64(keysCount) * (32 + 32))
opt.BlockSize = 4 * 1024
opt.BloomFalsePositive = 0.01
opt.TableSize = 5 << 20
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
builder := NewTableBuilder(*opt)
for j := 0; j < keysCount; j++ {
builder.Add(keyList[j], vs, 0)
}
_ = builder.Finish()
builder.Close()
}
}
b.Run("no compression", func(b *testing.B) {
var opt Options
opt.Compression = options.None
bench(b, &opt)
})
b.Run("encryption", func(b *testing.B) {
var opt Options
cache, err := ristretto.NewCache(&ristretto.Config[uint64, *fb.TableIndex]{
NumCounters: 1000,
MaxCost: 1 << 20,
BufferItems: 64,
})
require.NoError(b, err)
opt.IndexCache = cache
key := make([]byte, 32)
rand.Read(key)
opt.DataKey = &pb.DataKey{Data: key}
bench(b, &opt)
})
b.Run("snappy compression", func(b *testing.B) {
var opt Options
opt.Compression = options.Snappy
bench(b, &opt)
})
b.Run("zstd compression", func(b *testing.B) {
var opt Options
opt.Compression = options.ZSTD
b.Run("level 1", func(b *testing.B) {
opt.ZSTDCompressionLevel = 1
bench(b, &opt)
})
b.Run("level 3", func(b *testing.B) {
opt.ZSTDCompressionLevel = 3
bench(b, &opt)
})
b.Run("level 15", func(b *testing.B) {
opt.ZSTDCompressionLevel = 15
bench(b, &opt)
})
})
}
func TestBloomfilter(t *testing.T) {
keyPrefix := "p"
keyCount := 1000
createAndTest := func(t *testing.T, withBlooms bool) {
opts := Options{
BloomFalsePositive: 0.0,
}
if withBlooms {
opts.BloomFalsePositive = 0.01
}
tab := buildTestTable(t, keyPrefix, keyCount, opts)
defer func() { require.NoError(t, tab.DecrRef()) }()
require.Equal(t, withBlooms, tab.hasBloomFilter)
// Forward iteration
it := tab.NewIterator(0)
c := 0
for it.Rewind(); it.Valid(); it.Next() {
c++
hash := y.Hash(y.ParseKey(it.Key()))
require.False(t, tab.DoesNotHave(hash))
}
require.Equal(t, keyCount, c)
// Backward iteration
it = tab.NewIterator(REVERSED)
c = 0
for it.Rewind(); it.Valid(); it.Next() {
c++
hash := y.Hash(y.ParseKey(it.Key()))
require.False(t, tab.DoesNotHave(hash))
}
require.Equal(t, keyCount, c)
// Ensure tab.DoesNotHave works
hash := y.Hash([]byte("foo"))
require.Equal(t, withBlooms, tab.DoesNotHave(hash))
}
t.Run("build with bloom filter", func(t *testing.T) {
createAndTest(t, true)
})
t.Run("build without bloom filter", func(t *testing.T) {
createAndTest(t, false)
})
}
func TestEmptyBuilder(t *testing.T) {
opts := Options{BloomFalsePositive: 0.1}
b := NewTableBuilder(opts)
defer b.Close()
require.Equal(t, []byte{}, b.Finish())
}
================================================
FILE: table/iterator.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package table
import (
"bytes"
"fmt"
"io"
"sort"
"github.com/dgraph-io/badger/v4/fb"
"github.com/dgraph-io/badger/v4/y"
)
type blockIterator struct {
data []byte
idx int // Idx of the entry inside a block
err error
baseKey []byte
key []byte
val []byte
entryOffsets []uint32
block *Block
tableID uint64
blockID int
// prevOverlap stores the overlap of the previous key with the base key.
// This avoids unnecessary copy of base key when the overlap is same for multiple keys.
prevOverlap uint16
}
func (itr *blockIterator) setBlock(b *Block) {
// Decrement the ref for the old block. If the old block was compressed, we
// might be able to reuse it.
itr.block.decrRef()
itr.block = b
itr.err = nil
itr.idx = 0
itr.baseKey = itr.baseKey[:0]
itr.prevOverlap = 0
itr.key = itr.key[:0]
itr.val = itr.val[:0]
// Drop the index from the block. We don't need it anymore.
itr.data = b.data[:b.entriesIndexStart]
itr.entryOffsets = b.entryOffsets
}
// setIdx sets the iterator to the entry at index i and set it's key and value.
func (itr *blockIterator) setIdx(i int) {
itr.idx = i
if i >= len(itr.entryOffsets) || i < 0 {
itr.err = io.EOF
return
}
itr.err = nil
startOffset := int(itr.entryOffsets[i])
// Set base key.
if len(itr.baseKey) == 0 {
var baseHeader header
baseHeader.Decode(itr.data)
itr.baseKey = itr.data[headerSize : headerSize+baseHeader.diff]
}
var endOffset int
// idx points to the last entry in the block.
if itr.idx+1 == len(itr.entryOffsets) {
endOffset = len(itr.data)
} else {
// idx point to some entry other than the last one in the block.
// EndOffset of the current entry is the start offset of the next entry.
endOffset = int(itr.entryOffsets[itr.idx+1])
}
defer func() {
if r := recover(); r != nil {
var debugBuf bytes.Buffer
fmt.Fprintf(&debugBuf, "==== Recovered====\n")
fmt.Fprintf(&debugBuf, "Table ID: %d\nBlock ID: %d\nEntry Idx: %d\nData len: %d\n"+
"StartOffset: %d\nEndOffset: %d\nEntryOffsets len: %d\nEntryOffsets: %v\n",
itr.tableID, itr.blockID, itr.idx, len(itr.data), startOffset, endOffset,
len(itr.entryOffsets), itr.entryOffsets)
panic(debugBuf.String())
}
}()
entryData := itr.data[startOffset:endOffset]
var h header
h.Decode(entryData)
// Header contains the length of key overlap and difference compared to the base key. If the key
// before this one had the same or better key overlap, we can avoid copying that part into
// itr.key. But, if the overlap was lesser, we could copy over just that portion.
if h.overlap > itr.prevOverlap {
itr.key = append(itr.key[:itr.prevOverlap], itr.baseKey[itr.prevOverlap:h.overlap]...)
}
itr.prevOverlap = h.overlap
valueOff := headerSize + h.diff
diffKey := entryData[headerSize:valueOff]
itr.key = append(itr.key[:h.overlap], diffKey...)
itr.val = entryData[valueOff:]
}
func (itr *blockIterator) Valid() bool {
return itr != nil && itr.err == nil
}
func (itr *blockIterator) Error() error {
return itr.err
}
func (itr *blockIterator) Close() {
itr.block.decrRef()
}
var (
origin = 0
current = 1
)
// seek brings us to the first block element that is >= input key.
func (itr *blockIterator) seek(key []byte, whence int) {
itr.err = nil
startIndex := 0 // This tells from which index we should start binary search.
switch whence {
case origin:
// We don't need to do anything. startIndex is already at 0
case current:
startIndex = itr.idx
}
foundEntryIdx := sort.Search(len(itr.entryOffsets), func(idx int) bool {
// If idx is less than start index then just return false.
if idx < startIndex {
return false
}
itr.setIdx(idx)
return y.CompareKeys(itr.key, key) >= 0
})
itr.setIdx(foundEntryIdx)
}
// seekToFirst brings us to the first element.
func (itr *blockIterator) seekToFirst() {
itr.setIdx(0)
}
// seekToLast brings us to the last element.
func (itr *blockIterator) seekToLast() {
itr.setIdx(len(itr.entryOffsets) - 1)
}
func (itr *blockIterator) next() {
itr.setIdx(itr.idx + 1)
}
func (itr *blockIterator) prev() {
itr.setIdx(itr.idx - 1)
}
// Iterator is an iterator for a Table.
type Iterator struct {
t *Table
bpos int
bi blockIterator
err error
// Internally, Iterator is bidirectional. However, we only expose the
// unidirectional functionality for now.
opt int // Valid options are REVERSED and NOCACHE.
}
// NewIterator returns a new iterator of the Table
func (t *Table) NewIterator(opt int) *Iterator {
t.IncrRef() // Important.
ti := &Iterator{t: t, opt: opt}
return ti
}
// Close closes the iterator (and it must be called).
func (itr *Iterator) Close() error {
itr.bi.Close()
return itr.t.DecrRef()
}
func (itr *Iterator) reset() {
itr.bpos = 0
itr.err = nil
}
// Valid follows the y.Iterator interface
func (itr *Iterator) Valid() bool {
return itr.err == nil
}
func (itr *Iterator) useCache() bool {
return itr.opt&NOCACHE == 0
}
func (itr *Iterator) seekToFirst() {
numBlocks := itr.t.offsetsLength()
if numBlocks == 0 {
itr.err = io.EOF
return
}
itr.bpos = 0
block, err := itr.t.block(itr.bpos, itr.useCache())
if err != nil {
itr.err = err
return
}
itr.bi.tableID = itr.t.id
itr.bi.blockID = itr.bpos
itr.bi.setBlock(block)
itr.bi.seekToFirst()
itr.err = itr.bi.Error()
}
func (itr *Iterator) seekToLast() {
numBlocks := itr.t.offsetsLength()
if numBlocks == 0 {
itr.err = io.EOF
return
}
itr.bpos = numBlocks - 1
block, err := itr.t.block(itr.bpos, itr.useCache())
if err != nil {
itr.err = err
return
}
itr.bi.tableID = itr.t.id
itr.bi.blockID = itr.bpos
itr.bi.setBlock(block)
itr.bi.seekToLast()
itr.err = itr.bi.Error()
}
func (itr *Iterator) seekHelper(blockIdx int, key []byte) {
itr.bpos = blockIdx
block, err := itr.t.block(blockIdx, itr.useCache())
if err != nil {
itr.err = err
return
}
itr.bi.tableID = itr.t.id
itr.bi.blockID = itr.bpos
itr.bi.setBlock(block)
itr.bi.seek(key, origin)
itr.err = itr.bi.Error()
}
// seekFrom brings us to a key that is >= input key.
func (itr *Iterator) seekFrom(key []byte, whence int) {
itr.err = nil
switch whence {
case origin:
itr.reset()
case current:
}
var ko fb.BlockOffset
idx := sort.Search(itr.t.offsetsLength(), func(idx int) bool {
// Offsets should never return false since we're iterating within the OffsetsLength.
y.AssertTrue(itr.t.offsets(&ko, idx))
return y.CompareKeys(ko.KeyBytes(), key) > 0
})
if idx == 0 {
// The smallest key in our table is already strictly > key. We can return that.
// This is like a SeekToFirst.
itr.seekHelper(0, key)
return
}
// block[idx].smallest is > key.
// Since idx>0, we know block[idx-1].smallest is <= key.
// There are two cases.
// 1) Everything in block[idx-1] is strictly < key. In this case, we should go to the first
// element of block[idx].
// 2) Some element in block[idx-1] is >= key. We should go to that element.
itr.seekHelper(idx-1, key)
if itr.err == io.EOF {
// Case 1. Need to visit block[idx].
if idx == itr.t.offsetsLength() {
// If idx == len(itr.t.blockIndex), then input key is greater than ANY element of table.
// There's nothing we can do. Valid() should return false as we seek to end of table.
return
}
// Since block[idx].smallest is > key. This is essentially a block[idx].SeekToFirst.
itr.seekHelper(idx, key)
}
// Case 2: No need to do anything. We already did the seek in block[idx-1].
}
// seek will reset iterator and seek to >= key.
func (itr *Iterator) seek(key []byte) {
itr.seekFrom(key, origin)
}
// seekForPrev will reset iterator and seek to <= key.
func (itr *Iterator) seekForPrev(key []byte) {
// TODO: Optimize this. We shouldn't have to take a Prev step.
itr.seekFrom(key, origin)
if !bytes.Equal(itr.Key(), key) {
itr.prev()
}
}
func (itr *Iterator) next() {
itr.err = nil
if itr.bpos >= itr.t.offsetsLength() {
itr.err = io.EOF
return
}
if len(itr.bi.data) == 0 {
block, err := itr.t.block(itr.bpos, itr.useCache())
if err != nil {
itr.err = err
return
}
itr.bi.tableID = itr.t.id
itr.bi.blockID = itr.bpos
itr.bi.setBlock(block)
itr.bi.seekToFirst()
itr.err = itr.bi.Error()
return
}
itr.bi.next()
if !itr.bi.Valid() {
itr.bpos++
itr.bi.data = nil
itr.next()
return
}
}
func (itr *Iterator) prev() {
itr.err = nil
if itr.bpos < 0 {
itr.err = io.EOF
return
}
if len(itr.bi.data) == 0 {
block, err := itr.t.block(itr.bpos, itr.useCache())
if err != nil {
itr.err = err
return
}
itr.bi.tableID = itr.t.id
itr.bi.blockID = itr.bpos
itr.bi.setBlock(block)
itr.bi.seekToLast()
itr.err = itr.bi.Error()
return
}
itr.bi.prev()
if !itr.bi.Valid() {
itr.bpos--
itr.bi.data = nil
itr.prev()
return
}
}
// Key follows the y.Iterator interface.
// Returns the key with timestamp.
func (itr *Iterator) Key() []byte {
return itr.bi.key
}
// Value follows the y.Iterator interface
func (itr *Iterator) Value() (ret y.ValueStruct) {
ret.Decode(itr.bi.val)
return
}
// ValueCopy copies the current value and returns it as decoded
// ValueStruct.
func (itr *Iterator) ValueCopy() (ret y.ValueStruct) {
dst := y.Copy(itr.bi.val)
ret.Decode(dst)
return
}
// Next follows the y.Iterator interface
func (itr *Iterator) Next() {
if itr.opt&REVERSED == 0 {
itr.next()
} else {
itr.prev()
}
}
// Rewind follows the y.Iterator interface
func (itr *Iterator) Rewind() {
if itr.opt&REVERSED == 0 {
itr.seekToFirst()
} else {
itr.seekToLast()
}
}
// Seek follows the y.Iterator interface
func (itr *Iterator) Seek(key []byte) {
if itr.opt&REVERSED == 0 {
itr.seek(key)
} else {
itr.seekForPrev(key)
}
}
var (
REVERSED int = 2
NOCACHE int = 4
)
// ConcatIterator concatenates the sequences defined by several iterators. (It only works with
// TableIterators, probably just because it's faster to not be so generic.)
type ConcatIterator struct {
idx int // Which iterator is active now.
cur *Iterator
iters []*Iterator // Corresponds to tables.
tables []*Table // Disregarding reversed, this is in ascending order.
options int // Valid options are REVERSED and NOCACHE.
}
// NewConcatIterator creates a new concatenated iterator
func NewConcatIterator(tbls []*Table, opt int) *ConcatIterator {
iters := make([]*Iterator, len(tbls))
for i := 0; i < len(tbls); i++ {
// Increment the reference count. Since, we're not creating the iterator right now.
// Here, We'll hold the reference of the tables, till the lifecycle of the iterator.
tbls[i].IncrRef()
// Save cycles by not initializing the iterators until needed.
// iters[i] = tbls[i].NewIterator(reversed)
}
return &ConcatIterator{
options: opt,
iters: iters,
tables: tbls,
idx: -1, // Not really necessary because s.it.Valid()=false, but good to have.
}
}
func (s *ConcatIterator) setIdx(idx int) {
s.idx = idx
if idx < 0 || idx >= len(s.iters) {
s.cur = nil
return
}
if s.iters[idx] == nil {
s.iters[idx] = s.tables[idx].NewIterator(s.options)
}
s.cur = s.iters[s.idx]
}
// Rewind implements y.Interface
func (s *ConcatIterator) Rewind() {
if len(s.iters) == 0 {
return
}
if s.options&REVERSED == 0 {
s.setIdx(0)
} else {
s.setIdx(len(s.iters) - 1)
}
s.cur.Rewind()
}
// Valid implements y.Interface
func (s *ConcatIterator) Valid() bool {
return s.cur != nil && s.cur.Valid()
}
// Key implements y.Interface
func (s *ConcatIterator) Key() []byte {
return s.cur.Key()
}
// Value implements y.Interface
func (s *ConcatIterator) Value() y.ValueStruct {
return s.cur.Value()
}
// Seek brings us to element >= key if reversed is false. Otherwise, <= key.
func (s *ConcatIterator) Seek(key []byte) {
var idx int
if s.options&REVERSED == 0 {
idx = sort.Search(len(s.tables), func(i int) bool {
return y.CompareKeys(s.tables[i].Biggest(), key) >= 0
})
} else {
n := len(s.tables)
idx = n - 1 - sort.Search(n, func(i int) bool {
return y.CompareKeys(s.tables[n-1-i].Smallest(), key) <= 0
})
}
if idx >= len(s.tables) || idx < 0 {
s.setIdx(-1)
return
}
// For reversed=false, we know s.tables[i-1].Biggest() < key. Thus, the
// previous table cannot possibly contain key.
s.setIdx(idx)
s.cur.Seek(key)
}
// Next advances our concat iterator.
func (s *ConcatIterator) Next() {
s.cur.Next()
if s.cur.Valid() {
// Nothing to do. Just stay with the current table.
return
}
for { // In case there are empty tables.
if s.options&REVERSED == 0 {
s.setIdx(s.idx + 1)
} else {
s.setIdx(s.idx - 1)
}
if s.cur == nil {
// End of list. Valid will become false.
return
}
s.cur.Rewind()
if s.cur.Valid() {
break
}
}
}
// Close implements y.Interface.
func (s *ConcatIterator) Close() error {
for _, t := range s.tables {
// DeReference the tables while closing the iterator.
if err := t.DecrRef(); err != nil {
return err
}
}
for _, it := range s.iters {
if it == nil {
continue
}
if err := it.Close(); err != nil {
return y.Wrap(err, "ConcatIterator")
}
}
return nil
}
================================================
FILE: table/merge_iterator.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package table
import (
"bytes"
"github.com/dgraph-io/badger/v4/y"
)
// MergeIterator merges multiple iterators.
// NOTE: MergeIterator owns the array of iterators and is responsible for closing them.
type MergeIterator struct {
left node
right node
small *node
curKey []byte
reverse bool
}
type node struct {
valid bool
key []byte
iter y.Iterator
// The two iterators are type asserted from `y.Iterator`, used to inline more function calls.
// Calling functions on concrete types is much faster (about 25-30%) than calling the
// interface's function.
merge *MergeIterator
concat *ConcatIterator
}
func (n *node) setIterator(iter y.Iterator) {
n.iter = iter
// It's okay if the type assertion below fails and n.merge/n.concat are set to nil.
// We handle the nil values of merge and concat in all the methods.
n.merge, _ = iter.(*MergeIterator)
n.concat, _ = iter.(*ConcatIterator)
}
func (n *node) setKey() {
switch {
case n.merge != nil:
n.valid = n.merge.small.valid
if n.valid {
n.key = n.merge.small.key
}
case n.concat != nil:
n.valid = n.concat.Valid()
if n.valid {
n.key = n.concat.Key()
}
default:
n.valid = n.iter.Valid()
if n.valid {
n.key = n.iter.Key()
}
}
}
func (n *node) next() {
switch {
case n.merge != nil:
n.merge.Next()
case n.concat != nil:
n.concat.Next()
default:
n.iter.Next()
}
n.setKey()
}
func (n *node) rewind() {
n.iter.Rewind()
n.setKey()
}
func (n *node) seek(key []byte) {
n.iter.Seek(key)
n.setKey()
}
func (mi *MergeIterator) fix() {
if !mi.bigger().valid {
return
}
if !mi.small.valid {
mi.swapSmall()
return
}
cmp := y.CompareKeys(mi.small.key, mi.bigger().key)
switch {
case cmp == 0: // Both the keys are equal.
// In case of same keys, move the right iterator ahead.
mi.right.next()
if &mi.right == mi.small {
mi.swapSmall()
}
return
case cmp < 0: // Small is less than bigger().
if mi.reverse {
mi.swapSmall()
} else { //nolint:staticcheck
// we don't need to do anything. Small already points to the smallest.
}
return
default: // bigger() is less than small.
if mi.reverse {
// Do nothing since we're iterating in reverse. Small currently points to
// the bigger key and that's okay in reverse iteration.
} else {
mi.swapSmall()
}
return
}
}
func (mi *MergeIterator) bigger() *node {
if mi.small == &mi.left {
return &mi.right
}
return &mi.left
}
func (mi *MergeIterator) swapSmall() {
if mi.small == &mi.left {
mi.small = &mi.right
return
}
if mi.small == &mi.right {
mi.small = &mi.left
return
}
}
// Next returns the next element. If it is the same as the current key, ignore it.
func (mi *MergeIterator) Next() {
for mi.Valid() {
if !bytes.Equal(mi.small.key, mi.curKey) {
break
}
mi.small.next()
mi.fix()
}
mi.setCurrent()
}
func (mi *MergeIterator) setCurrent() {
mi.curKey = append(mi.curKey[:0], mi.small.key...)
}
// Rewind seeks to first element (or last element for reverse iterator).
func (mi *MergeIterator) Rewind() {
mi.left.rewind()
mi.right.rewind()
mi.fix()
mi.setCurrent()
}
// Seek brings us to element with key >= given key.
func (mi *MergeIterator) Seek(key []byte) {
mi.left.seek(key)
mi.right.seek(key)
mi.fix()
mi.setCurrent()
}
// Valid returns whether the MergeIterator is at a valid element.
func (mi *MergeIterator) Valid() bool {
return mi.small.valid
}
// Key returns the key associated with the current iterator.
func (mi *MergeIterator) Key() []byte {
return mi.small.key
}
// Value returns the value associated with the iterator.
func (mi *MergeIterator) Value() y.ValueStruct {
return mi.small.iter.Value()
}
// Close implements y.Iterator.
func (mi *MergeIterator) Close() error {
err1 := mi.left.iter.Close()
err2 := mi.right.iter.Close()
if err1 != nil {
return y.Wrap(err1, "MergeIterator")
}
return y.Wrap(err2, "MergeIterator")
}
// NewMergeIterator creates a merge iterator.
func NewMergeIterator(iters []y.Iterator, reverse bool) y.Iterator {
switch len(iters) {
case 0:
return nil
case 1:
return iters[0]
case 2:
mi := &MergeIterator{
reverse: reverse,
}
mi.left.setIterator(iters[0])
mi.right.setIterator(iters[1])
// Assign left iterator randomly. This will be fixed when user calls rewind/seek.
mi.small = &mi.left
return mi
}
mid := len(iters) / 2
return NewMergeIterator(
[]y.Iterator{
NewMergeIterator(iters[:mid], reverse),
NewMergeIterator(iters[mid:], reverse),
}, reverse)
}
================================================
FILE: table/merge_iterator_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package table
import (
"sort"
"testing"
"github.com/stretchr/testify/require"
"github.com/dgraph-io/badger/v4/y"
)
type SimpleIterator struct {
keys [][]byte
vals [][]byte
idx int
reversed bool
}
var (
closeCount int
)
func (s *SimpleIterator) Close() error { closeCount++; return nil }
func (s *SimpleIterator) Next() {
if !s.reversed {
s.idx++
} else {
s.idx--
}
}
func (s *SimpleIterator) Rewind() {
if !s.reversed {
s.idx = 0
} else {
s.idx = len(s.keys) - 1
}
}
func (s *SimpleIterator) Seek(key []byte) {
key = y.KeyWithTs(key, 0)
if !s.reversed {
s.idx = sort.Search(len(s.keys), func(i int) bool {
return y.CompareKeys(s.keys[i], key) >= 0
})
} else {
n := len(s.keys)
s.idx = n - 1 - sort.Search(n, func(i int) bool {
return y.CompareKeys(s.keys[n-1-i], key) <= 0
})
}
}
func (s *SimpleIterator) Key() []byte { return s.keys[s.idx] }
func (s *SimpleIterator) Value() y.ValueStruct {
return y.ValueStruct{
Value: s.vals[s.idx],
UserMeta: 55,
Meta: 0,
}
}
func (s *SimpleIterator) Valid() bool {
return s.idx >= 0 && s.idx < len(s.keys)
}
var _ y.Iterator = &SimpleIterator{}
func newSimpleIterator(keys []string, vals []string, reversed bool) *SimpleIterator {
k := make([][]byte, len(keys))
v := make([][]byte, len(vals))
y.AssertTrue(len(keys) == len(vals))
for i := 0; i < len(keys); i++ {
k[i] = y.KeyWithTs([]byte(keys[i]), 0)
v[i] = []byte(vals[i])
}
return &SimpleIterator{
keys: k,
vals: v,
idx: -1,
reversed: reversed,
}
}
func getAll(it y.Iterator) ([]string, []string) {
var keys, vals []string
for ; it.Valid(); it.Next() {
k := it.Key()
keys = append(keys, string(y.ParseKey(k)))
v := it.Value()
vals = append(vals, string(v.Value))
}
return keys, vals
}
func closeAndCheck(t *testing.T, it y.Iterator, expected int) {
closeCount = 0
it.Close()
require.EqualValues(t, expected, closeCount)
}
func TestSimpleIterator(t *testing.T) {
keys := []string{"1", "2", "3"}
vals := []string{"v1", "v2", "v3"}
it := newSimpleIterator(keys, vals, false)
it.Rewind()
k, v := getAll(it)
require.EqualValues(t, keys, k)
require.EqualValues(t, vals, v)
closeAndCheck(t, it, 1)
}
func reversed(a []string) []string {
var out []string
for i := len(a) - 1; i >= 0; i-- {
out = append(out, a[i])
}
return out
}
func TestMergeSingle(t *testing.T) {
keys := []string{"1", "2", "3"}
vals := []string{"v1", "v2", "v3"}
it := newSimpleIterator(keys, vals, false)
mergeIt := NewMergeIterator([]y.Iterator{it}, false)
mergeIt.Rewind()
k, v := getAll(mergeIt)
require.EqualValues(t, keys, k)
require.EqualValues(t, vals, v)
closeAndCheck(t, mergeIt, 1)
}
func TestMergeSingleReversed(t *testing.T) {
keys := []string{"1", "2", "3"}
vals := []string{"v1", "v2", "v3"}
it := newSimpleIterator(keys, vals, true)
mergeIt := NewMergeIterator([]y.Iterator{it}, true)
mergeIt.Rewind()
k, v := getAll(mergeIt)
require.EqualValues(t, reversed(keys), k)
require.EqualValues(t, reversed(vals), v)
closeAndCheck(t, mergeIt, 1)
}
func TestMergeMore(t *testing.T) {
it := newSimpleIterator([]string{"1", "3", "7"}, []string{"a1", "a3", "a7"}, false)
it2 := newSimpleIterator([]string{"2", "3", "5"}, []string{"b2", "b3", "b5"}, false)
it3 := newSimpleIterator([]string{"1"}, []string{"c1"}, false)
it4 := newSimpleIterator([]string{"1", "7", "9"}, []string{"d1", "d7", "d9"}, false)
t.Run("forward", func(t *testing.T) {
expectedKeys := []string{"1", "2", "3", "5", "7", "9"}
expectedVals := []string{"a1", "b2", "a3", "b5", "a7", "d9"}
t.Run("no duplicates", func(t *testing.T) {
mergeIt := NewMergeIterator([]y.Iterator{it, it2, it3, it4}, false)
mergeIt.Rewind()
k, v := getAll(mergeIt)
require.EqualValues(t, expectedKeys, k)
require.EqualValues(t, expectedVals, v)
closeAndCheck(t, mergeIt, 4)
})
t.Run("duplicates", func(t *testing.T) {
it5 := newSimpleIterator(
[]string{"1", "1", "3", "7"},
[]string{"a1", "a1-1", "a3", "a7"},
false)
mergeIt := NewMergeIterator([]y.Iterator{it5, it2, it3, it4}, false)
expectedKeys := []string{"1", "2", "3", "5", "7", "9"}
expectedVals := []string{"a1", "b2", "a3", "b5", "a7", "d9"}
mergeIt.Rewind()
k, v := getAll(mergeIt)
require.EqualValues(t, expectedKeys, k)
require.EqualValues(t, expectedVals, v)
closeAndCheck(t, mergeIt, 4)
})
})
t.Run("reverse", func(t *testing.T) {
it.reversed = true
it2.reversed = true
it3.reversed = true
it4.reversed = true
t.Run("no duplicates", func(t *testing.T) {
mergeIt := NewMergeIterator([]y.Iterator{it, it2, it3, it4}, true)
expectedKeys := []string{"9", "7", "5", "3", "2", "1"}
expectedVals := []string{"d9", "a7", "b5", "a3", "b2", "a1"}
mergeIt.Rewind()
k, v := getAll(mergeIt)
require.EqualValues(t, expectedKeys, k)
require.EqualValues(t, expectedVals, v)
closeAndCheck(t, mergeIt, 4)
})
t.Run("duplicates", func(t *testing.T) {
it5 := newSimpleIterator(
[]string{"1", "1", "3", "7"},
[]string{"a1", "a1-1", "a3", "a7"},
true)
mergeIt := NewMergeIterator([]y.Iterator{it5, it2, it3, it4}, true)
expectedKeys := []string{"9", "7", "5", "3", "2", "1"}
expectedVals := []string{"d9", "a7", "b5", "a3", "b2", "a1-1"}
mergeIt.Rewind()
k, v := getAll(mergeIt)
require.EqualValues(t, expectedKeys, k)
require.EqualValues(t, expectedVals, v)
closeAndCheck(t, mergeIt, 4)
})
})
}
// Ensure MergeIterator satisfies the Iterator interface
func TestMergeIteratorNested(t *testing.T) {
keys := []string{"1", "2", "3"}
vals := []string{"v1", "v2", "v3"}
it := newSimpleIterator(keys, vals, false)
mergeIt := NewMergeIterator([]y.Iterator{it}, false)
mergeIt2 := NewMergeIterator([]y.Iterator{mergeIt}, false)
mergeIt2.Rewind()
k, v := getAll(mergeIt2)
require.EqualValues(t, keys, k)
require.EqualValues(t, vals, v)
closeAndCheck(t, mergeIt2, 1)
}
func TestMergeIteratorSeek(t *testing.T) {
it := newSimpleIterator([]string{"1", "3", "7"}, []string{"a1", "a3", "a7"}, false)
it2 := newSimpleIterator([]string{"2", "3", "5"}, []string{"b2", "b3", "b5"}, false)
it3 := newSimpleIterator([]string{"1"}, []string{"c1"}, false)
it4 := newSimpleIterator([]string{"1", "7", "9"}, []string{"d1", "d7", "d9"}, false)
mergeIt := NewMergeIterator([]y.Iterator{it, it2, it3, it4}, false)
mergeIt.Seek([]byte("4"))
k, v := getAll(mergeIt)
require.EqualValues(t, []string{"5", "7", "9"}, k)
require.EqualValues(t, []string{"b5", "a7", "d9"}, v)
closeAndCheck(t, mergeIt, 4)
}
func TestMergeIteratorSeekReversed(t *testing.T) {
it := newSimpleIterator([]string{"1", "3", "7"}, []string{"a1", "a3", "a7"}, true)
it2 := newSimpleIterator([]string{"2", "3", "5"}, []string{"b2", "b3", "b5"}, true)
it3 := newSimpleIterator([]string{"1"}, []string{"c1"}, true)
it4 := newSimpleIterator([]string{"1", "7", "9"}, []string{"d1", "d7", "d9"}, true)
mergeIt := NewMergeIterator([]y.Iterator{it, it2, it3, it4}, true)
mergeIt.Seek([]byte("5"))
k, v := getAll(mergeIt)
require.EqualValues(t, []string{"5", "3", "2", "1"}, k)
require.EqualValues(t, []string{"b5", "a3", "b2", "a1"}, v)
closeAndCheck(t, mergeIt, 4)
}
func TestMergeIteratorSeekInvalid(t *testing.T) {
it := newSimpleIterator([]string{"1", "3", "7"}, []string{"a1", "a3", "a7"}, false)
it2 := newSimpleIterator([]string{"2", "3", "5"}, []string{"b2", "b3", "b5"}, false)
it3 := newSimpleIterator([]string{"1"}, []string{"c1"}, false)
it4 := newSimpleIterator([]string{"1", "7", "9"}, []string{"d1", "d7", "d9"}, false)
mergeIt := NewMergeIterator([]y.Iterator{it, it2, it3, it4}, false)
mergeIt.Seek([]byte("f"))
require.False(t, mergeIt.Valid())
closeAndCheck(t, mergeIt, 4)
}
func TestMergeIteratorSeekInvalidReversed(t *testing.T) {
it := newSimpleIterator([]string{"1", "3", "7"}, []string{"a1", "a3", "a7"}, true)
it2 := newSimpleIterator([]string{"2", "3", "5"}, []string{"b2", "b3", "b5"}, true)
it3 := newSimpleIterator([]string{"1"}, []string{"c1"}, true)
it4 := newSimpleIterator([]string{"1", "7", "9"}, []string{"d1", "d7", "d9"}, true)
mergeIt := NewMergeIterator([]y.Iterator{it, it2, it3, it4}, true)
mergeIt.Seek([]byte("0"))
require.False(t, mergeIt.Valid())
closeAndCheck(t, mergeIt, 4)
}
func TestMergeIteratorDuplicate(t *testing.T) {
it1 := newSimpleIterator([]string{"0", "1", "2"}, []string{"a0", "a1", "a2"}, false)
it2 := newSimpleIterator([]string{"1", "3"}, []string{"b1", "b3"}, false)
it3 := newSimpleIterator([]string{"0", "1", "2"}, []string{"c0", "c1", "c2"}, false)
t.Run("forward", func(t *testing.T) {
t.Run("only duplicates", func(t *testing.T) {
it := NewMergeIterator([]y.Iterator{it1, it3}, false)
expectedKeys := []string{"0", "1", "2"}
expectedVals := []string{"a0", "a1", "a2"}
it.Rewind()
k, v := getAll(it)
require.Equal(t, expectedKeys, k)
require.Equal(t, expectedVals, v)
})
t.Run("one", func(t *testing.T) {
it := NewMergeIterator([]y.Iterator{it3, it2, it1}, false)
expectedKeys := []string{"0", "1", "2", "3"}
expectedVals := []string{"c0", "c1", "c2", "b3"}
it.Rewind()
k, v := getAll(it)
require.Equal(t, expectedKeys, k)
require.Equal(t, expectedVals, v)
})
t.Run("two", func(t *testing.T) {
it1 := newSimpleIterator([]string{"0", "1", "2"}, []string{"0", "1", "2"}, false)
it2 := newSimpleIterator([]string{"1"}, []string{"1"}, false)
it3 := newSimpleIterator([]string{"2"}, []string{"2"}, false)
it := NewMergeIterator([]y.Iterator{it3, it2, it1}, false)
var cnt int
for it.Rewind(); it.Valid(); it.Next() {
require.EqualValues(t, cnt+48, it.Key()[0])
cnt++
}
require.Equal(t, 3, cnt)
})
})
t.Run("reverse", func(t *testing.T) {
it1.reversed = true
it2.reversed = true
it3.reversed = true
it := NewMergeIterator([]y.Iterator{it3, it2, it1}, true)
expectedKeys := []string{"3", "2", "1", "0"}
expectedVals := []string{"b3", "c2", "c1", "c0"}
it.Rewind()
k, v := getAll(it)
require.Equal(t, expectedKeys, k)
require.Equal(t, expectedVals, v)
})
}
func TestMergeDuplicates(t *testing.T) {
it := newSimpleIterator([]string{"1", "1", "1"}, []string{"a1", "a3", "a7"}, false)
it2 := newSimpleIterator([]string{"1", "1", "1"}, []string{"b2", "b3", "b5"}, false)
it3 := newSimpleIterator([]string{"1"}, []string{"c1"}, false)
it4 := newSimpleIterator([]string{"1", "1", "2"}, []string{"d1", "d7", "d9"}, false)
t.Run("forward", func(t *testing.T) {
expectedKeys := []string{"1", "2"}
expectedVals := []string{"a1", "d9"}
mergeIt := NewMergeIterator([]y.Iterator{it, it2, it3, it4}, false)
mergeIt.Rewind()
k, v := getAll(mergeIt)
require.EqualValues(t, expectedKeys, k)
require.EqualValues(t, expectedVals, v)
closeAndCheck(t, mergeIt, 4)
})
t.Run("reverse", func(t *testing.T) {
it.reversed = true
it2.reversed = true
it3.reversed = true
it4.reversed = true
expectedKeys := []string{"2", "1"}
expectedVals := []string{"d9", "a7"}
mergeIt := NewMergeIterator([]y.Iterator{it, it2, it3, it4}, true)
mergeIt.Rewind()
k, v := getAll(mergeIt)
require.EqualValues(t, expectedKeys, k)
require.EqualValues(t, expectedVals, v)
closeAndCheck(t, mergeIt, 4)
})
}
================================================
FILE: table/table.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package table
import (
"bytes"
"crypto/aes"
"encoding/binary"
"errors"
"fmt"
"math"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unsafe"
"github.com/klauspost/compress/snappy"
"github.com/klauspost/compress/zstd"
"google.golang.org/protobuf/proto"
"github.com/dgraph-io/badger/v4/fb"
"github.com/dgraph-io/badger/v4/options"
"github.com/dgraph-io/badger/v4/pb"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2"
"github.com/dgraph-io/ristretto/v2/z"
)
const fileSuffix = ".sst"
const intSize = int(unsafe.Sizeof(int(0)))
// Options contains configurable options for Table/Builder.
type Options struct {
// Options for Opening/Building Table.
// Open tables in read only mode.
ReadOnly bool
MetricsEnabled bool
// Maximum size of the table.
TableSize uint64
tableCapacity uint64 // 0.9x TableSize.
// ChkMode is the checksum verification mode for Table.
ChkMode options.ChecksumVerificationMode
// Options for Table builder.
// BloomFalsePositive is the false positive probabiltiy of bloom filter.
BloomFalsePositive float64
// BlockSize is the size of each block inside SSTable in bytes.
BlockSize int
// DataKey is the key used to decrypt the encrypted text.
DataKey *pb.DataKey
// Compression indicates the compression algorithm used for block compression.
Compression options.CompressionType
// Block cache is used to cache decompressed and decrypted blocks.
BlockCache *ristretto.Cache[[]byte, *Block]
IndexCache *ristretto.Cache[uint64, *fb.TableIndex]
AllocPool *z.AllocatorPool
// ZSTDCompressionLevel is the ZSTD compression level used for compressing blocks.
ZSTDCompressionLevel int
}
// TableInterface is useful for testing.
type TableInterface interface {
Smallest() []byte
Biggest() []byte
DoesNotHave(hash uint32) bool
MaxVersion() uint64
}
// Table represents a loaded table file with the info we have about it.
type Table struct {
sync.Mutex
*z.MmapFile
tableSize int // Initialized in OpenTable, using fd.Stat().
_index *fb.TableIndex // Nil if encryption is enabled. Use fetchIndex to access.
_cheap *cheapIndex
ref atomic.Int32 // For file garbage collection
// The following are initialized once and const.
smallest, biggest []byte // Smallest and largest keys (with timestamps).
id uint64 // file id, part of filename
Checksum []byte
CreatedAt time.Time
indexStart int
indexLen int
hasBloomFilter bool
IsInmemory bool // Set to true if the table is on level 0 and opened in memory.
opt *Options
}
type cheapIndex struct {
MaxVersion uint64
KeyCount uint32
UncompressedSize uint32
OnDiskSize uint32
BloomFilterLength int
OffsetsLength int
}
func (t *Table) cheapIndex() *cheapIndex {
return t._cheap
}
func (t *Table) offsetsLength() int { return t.cheapIndex().OffsetsLength }
// MaxVersion returns the maximum version across all keys stored in this table.
func (t *Table) MaxVersion() uint64 { return t.cheapIndex().MaxVersion }
// BloomFilterSize returns the size of the bloom filter in bytes stored in memory.
func (t *Table) BloomFilterSize() int { return t.cheapIndex().BloomFilterLength }
// UncompressedSize is the size uncompressed data stored in this file.
func (t *Table) UncompressedSize() uint32 { return t.cheapIndex().UncompressedSize }
// KeyCount is the total number of keys in this table.
func (t *Table) KeyCount() uint32 { return t.cheapIndex().KeyCount }
// OnDiskSize returns the total size of key-values stored in this table (including the
// disk space occupied on the value log).
func (t *Table) OnDiskSize() uint32 { return t.cheapIndex().OnDiskSize }
// CompressionType returns the compression algorithm used for block compression.
func (t *Table) CompressionType() options.CompressionType {
return t.opt.Compression
}
// IncrRef increments the refcount (having to do with whether the file should be deleted)
func (t *Table) IncrRef() {
t.ref.Add(1)
}
// DecrRef decrements the refcount and possibly deletes the table
func (t *Table) DecrRef() error {
newRef := t.ref.Add(-1)
if newRef == 0 {
// We can safely delete this file, because for all the current files, we always have
// at least one reference pointing to them.
// Delete all blocks from the cache.
for i := 0; i < t.offsetsLength(); i++ {
t.opt.BlockCache.Del(t.blockCacheKey(i))
}
if err := t.Delete(); err != nil {
return err
}
}
return nil
}
// BlockEvictHandler is used to reuse the byte slice stored in the block on cache eviction.
func BlockEvictHandler(b *Block) {
b.decrRef()
}
type Block struct {
offset int
data []byte
checksum []byte
entriesIndexStart int // start index of entryOffsets list
entryOffsets []uint32 // used to binary search an entry in the block.
chkLen int // checksum length.
freeMe bool // used to determine if the blocked should be reused.
ref atomic.Int32
}
var NumBlocks atomic.Int32
// incrRef increments the ref of a block and return a bool indicating if the
// increment was successful. A true value indicates that the block can be used.
func (b *Block) incrRef() bool {
for {
// We can't blindly add 1 to ref. We need to check whether it has
// reached zero first, because if it did, then we should absolutely not
// use this block.
ref := b.ref.Load()
// The ref would not be equal to 0 unless the existing
// block get evicted before this line. If the ref is zero, it means that
// the block is already added the the blockPool and cannot be used
// anymore. The ref of a new block is 1 so the following condition will
// be true only if the block got reused before we could increment its
// ref.
if ref == 0 {
return false
}
// Increment the ref only if it is not zero and has not changed between
// the time we read it and we're updating it.
//
if b.ref.CompareAndSwap(ref, ref+1) {
return true
}
}
}
func (b *Block) decrRef() {
if b == nil {
return
}
// Insert the []byte into pool only if the block is reusable. When a block
// is reusable a new []byte is used for decompression and this []byte can
// be reused.
// In case of an uncompressed block, the []byte is a reference to the
// table.mmap []byte slice. Any attempt to write data to the mmap []byte
// will lead to SEGFAULT.
if b.ref.Add(-1) == 0 {
if b.freeMe {
z.Free(b.data)
}
NumBlocks.Add(-1)
// blockPool.Put(&b.data)
}
y.AssertTrue(b.ref.Load() >= 0)
}
func (b *Block) size() int64 {
return int64(3*intSize /* Size of the offset, entriesIndexStart and chkLen */ +
cap(b.data) + cap(b.checksum) + cap(b.entryOffsets)*4)
}
func (b *Block) verifyCheckSum() error {
cs := &pb.Checksum{}
if err := proto.Unmarshal(b.checksum, cs); err != nil {
return y.Wrapf(err, "unable to unmarshal checksum for block")
}
return y.VerifyChecksum(b.data, cs)
}
func CreateTable(fname string, builder *Builder) (*Table, error) {
bd := builder.Done()
mf, err := z.OpenMmapFile(fname, os.O_CREATE|os.O_RDWR|os.O_EXCL, bd.Size)
if err == z.NewFile {
// Expected.
} else if err != nil {
return nil, y.Wrapf(err, "while creating table: %s", fname)
} else {
return nil, fmt.Errorf("file already exists: %s", fname)
}
written := bd.Copy(mf.Data)
y.AssertTrue(written == len(mf.Data))
if err := z.Msync(mf.Data); err != nil {
return nil, y.Wrapf(err, "while calling msync on %s", fname)
}
return OpenTable(mf, *builder.opts)
}
// OpenTable assumes file has only one table and opens it. Takes ownership of fd upon function
// entry. Returns a table with one reference count on it (decrementing which may delete the file!
// -- consider t.Close() instead). The fd has to writeable because we call Truncate on it before
// deleting. Checksum for all blocks of table is verified based on value of chkMode.
func OpenTable(mf *z.MmapFile, opts Options) (*Table, error) {
// BlockSize is used to compute the approximate size of the decompressed
// block. It should not be zero if the table is compressed.
if opts.BlockSize == 0 && opts.Compression != options.None {
return nil, errors.New("Block size cannot be zero")
}
fileInfo, err := mf.Fd.Stat()
if err != nil {
mf.Close(-1)
return nil, y.Wrap(err, "")
}
filename := fileInfo.Name()
id, ok := ParseFileID(filename)
if !ok {
mf.Close(-1)
return nil, fmt.Errorf("Invalid filename: %s", filename)
}
t := &Table{
MmapFile: mf,
id: id,
opt: &opts,
IsInmemory: false,
tableSize: int(fileInfo.Size()),
CreatedAt: fileInfo.ModTime(),
}
// Caller is given one reference.
t.ref.Store(1)
if err := t.initBiggestAndSmallest(); err != nil {
return nil, y.Wrapf(err, "failed to initialize table")
}
if opts.ChkMode == options.OnTableRead || opts.ChkMode == options.OnTableAndBlockRead {
if err := t.VerifyChecksum(); err != nil {
mf.Close(-1)
return nil, y.Wrapf(err, "failed to verify checksum")
}
}
return t, nil
}
// OpenInMemoryTable is similar to OpenTable but it opens a new table from the provided data.
// OpenInMemoryTable is used for L0 tables.
func OpenInMemoryTable(data []byte, id uint64, opt *Options) (*Table, error) {
mf := &z.MmapFile{
Data: data,
Fd: nil,
}
t := &Table{
MmapFile: mf,
opt: opt,
tableSize: len(data),
IsInmemory: true,
id: id, // It is important that each table gets a unique ID.
}
// Caller is given one reference.
t.ref.Store(1)
if err := t.initBiggestAndSmallest(); err != nil {
return nil, err
}
return t, nil
}
func (t *Table) initBiggestAndSmallest() error {
// This defer will help gathering debugging info in case initIndex crashes.
defer func() {
if r := recover(); r != nil {
// Use defer for printing info because there may be an intermediate panic.
var debugBuf bytes.Buffer
defer func() {
panic(fmt.Sprintf("%s\n== Recovered ==\n", debugBuf.String()))
}()
// Get the count of null bytes at the end of file. This is to make sure if there was an
// issue with mmap sync or file copy.
count := 0
for i := len(t.Data) - 1; i >= 0; i-- {
if t.Data[i] != 0 {
break
}
count++
}
fmt.Fprintf(&debugBuf, "\n== Recovering from initIndex crash ==\n")
fmt.Fprintf(&debugBuf, "File Info: [ID: %d, Size: %d, Zeros: %d]\n",
t.id, t.tableSize, count)
fmt.Fprintf(&debugBuf, "isEnrypted: %v ", t.shouldDecrypt())
readPos := t.tableSize
// Read checksum size.
readPos -= 4
buf := t.readNoFail(readPos, 4)
checksumLen := int(y.BytesToU32(buf))
fmt.Fprintf(&debugBuf, "checksumLen: %d ", checksumLen)
// Read checksum.
checksum := &pb.Checksum{}
readPos -= checksumLen
buf = t.readNoFail(readPos, checksumLen)
_ = proto.Unmarshal(buf, checksum)
fmt.Fprintf(&debugBuf, "checksum: %+v ", checksum)
// Read index size from the footer.
readPos -= 4
buf = t.readNoFail(readPos, 4)
indexLen := int(y.BytesToU32(buf))
fmt.Fprintf(&debugBuf, "indexLen: %d ", indexLen)
// Read index.
readPos -= t.indexLen
t.indexStart = readPos
indexData := t.readNoFail(readPos, t.indexLen)
fmt.Fprintf(&debugBuf, "index: %v ", indexData)
}
}()
var err error
var ko *fb.BlockOffset
if ko, err = t.initIndex(); err != nil {
return y.Wrapf(err, "failed to read index.")
}
t.smallest = y.Copy(ko.KeyBytes())
it2 := t.NewIterator(REVERSED | NOCACHE)
defer it2.Close()
it2.Rewind()
if !it2.Valid() {
return y.Wrapf(it2.err, "failed to initialize biggest for table %s", t.Filename())
}
t.biggest = y.Copy(it2.Key())
return nil
}
func (t *Table) read(off, sz int) ([]byte, error) {
return t.Bytes(off, sz)
}
func (t *Table) readNoFail(off, sz int) []byte {
res, err := t.read(off, sz)
y.Check(err)
return res
}
// initIndex reads the index and populate the necessary table fields and returns
// first block offset
func (t *Table) initIndex() (*fb.BlockOffset, error) {
readPos := t.tableSize
// Read checksum len from the last 4 bytes.
readPos -= 4
buf := t.readNoFail(readPos, 4)
checksumLen := int(y.BytesToU32(buf))
if checksumLen < 0 {
return nil, errors.New("checksum length less than zero. Data corrupted")
}
// Read checksum.
expectedChk := &pb.Checksum{}
readPos -= checksumLen
buf = t.readNoFail(readPos, checksumLen)
if err := proto.Unmarshal(buf, expectedChk); err != nil {
return nil, err
}
// Read index size from the footer.
readPos -= 4
buf = t.readNoFail(readPos, 4)
t.indexLen = int(y.BytesToU32(buf))
// Read index.
readPos -= t.indexLen
t.indexStart = readPos
data := t.readNoFail(readPos, t.indexLen)
if err := y.VerifyChecksum(data, expectedChk); err != nil {
return nil, y.Wrapf(err, "failed to verify checksum for table: %s", t.Filename())
}
index, err := t.readTableIndex()
if err != nil {
return nil, err
}
if !t.shouldDecrypt() {
// If there's no encryption, this points to the mmap'ed buffer.
t._index = index
}
t._cheap = &cheapIndex{
MaxVersion: index.MaxVersion(),
KeyCount: index.KeyCount(),
UncompressedSize: index.UncompressedSize(),
OnDiskSize: index.OnDiskSize(),
OffsetsLength: index.OffsetsLength(),
BloomFilterLength: index.BloomFilterLength(),
}
t.hasBloomFilter = len(index.BloomFilterBytes()) > 0
var bo fb.BlockOffset
y.AssertTrue(index.Offsets(&bo, 0))
return &bo, nil
}
// KeySplits splits the table into at least n ranges based on the block offsets.
func (t *Table) KeySplits(n int, prefix []byte) []string {
if n == 0 {
return nil
}
oLen := t.offsetsLength()
jump := oLen / n
if jump == 0 {
jump = 1
}
var bo fb.BlockOffset
var res []string
for i := 0; i < oLen; i += jump {
if i >= oLen {
i = oLen - 1
}
y.AssertTrue(t.offsets(&bo, i))
if bytes.HasPrefix(bo.KeyBytes(), prefix) {
res = append(res, string(bo.KeyBytes()))
}
}
return res
}
func (t *Table) fetchIndex() *fb.TableIndex {
if !t.shouldDecrypt() {
return t._index
}
if t.opt.IndexCache == nil {
panic("Index Cache must be set for encrypted workloads")
}
if val, ok := t.opt.IndexCache.Get(t.indexKey()); ok && val != nil {
return val
}
index, err := t.readTableIndex()
y.Check(err)
t.opt.IndexCache.Set(t.indexKey(), index, int64(t.indexLen))
return index
}
func (t *Table) offsets(ko *fb.BlockOffset, i int) bool {
return t.fetchIndex().Offsets(ko, i)
}
// block function return a new block. Each block holds a ref and the byte
// slice stored in the block will be reused when the ref becomes zero. The
// caller should release the block by calling block.decrRef() on it.
func (t *Table) block(idx int, useCache bool) (*Block, error) {
y.AssertTruef(idx >= 0, "idx=%d", idx)
if idx >= t.offsetsLength() {
return nil, errors.New("block out of index")
}
if t.opt.BlockCache != nil {
key := t.blockCacheKey(idx)
blk, ok := t.opt.BlockCache.Get(key)
if ok && blk != nil {
// Use the block only if the increment was successful. The block
// could get evicted from the cache between the Get() call and the
// incrRef() call.
if blk.incrRef() {
return blk, nil
}
}
}
var ko fb.BlockOffset
y.AssertTrue(t.offsets(&ko, idx))
blk := &Block{offset: int(ko.Offset())}
blk.ref.Store(1)
defer blk.decrRef() // Deal with any errors, where blk would not be returned.
NumBlocks.Add(1)
var err error
if blk.data, err = t.read(blk.offset, int(ko.Len())); err != nil {
return nil, y.Wrapf(err,
"failed to read from file: %s at offset: %d, len: %d",
t.Fd.Name(), blk.offset, ko.Len())
}
if t.shouldDecrypt() {
// Decrypt the block if it is encrypted.
if blk.data, err = t.decrypt(blk.data, true); err != nil {
return nil, err
}
// blk.data is allocated via Calloc. So, do free.
blk.freeMe = true
}
if err = t.decompress(blk); err != nil {
return nil, y.Wrapf(err,
"failed to decode compressed data in file: %s at offset: %d, len: %d",
t.Fd.Name(), blk.offset, ko.Len())
}
// Read meta data related to block.
readPos := len(blk.data) - 4 // First read checksum length.
blk.chkLen = int(y.BytesToU32(blk.data[readPos : readPos+4]))
// Checksum length greater than block size could happen if the table was compressed and
// it was opened with an incorrect compression algorithm (or the data was corrupted).
if blk.chkLen > len(blk.data) {
return nil, errors.New("invalid checksum length. Either the data is " +
"corrupted or the table options are incorrectly set")
}
// Read checksum and store it
readPos -= blk.chkLen
blk.checksum = blk.data[readPos : readPos+blk.chkLen]
// Move back and read numEntries in the block.
readPos -= 4
numEntries := int(y.BytesToU32(blk.data[readPos : readPos+4]))
entriesIndexStart := readPos - (numEntries * 4)
entriesIndexEnd := entriesIndexStart + numEntries*4
blk.entryOffsets = y.BytesToU32Slice(blk.data[entriesIndexStart:entriesIndexEnd])
blk.entriesIndexStart = entriesIndexStart
// Drop checksum and checksum length.
// The checksum is calculated for actual data + entry index + index length
blk.data = blk.data[:readPos+4]
// Verify checksum on if checksum verification mode is OnRead on OnStartAndRead.
if t.opt.ChkMode == options.OnBlockRead || t.opt.ChkMode == options.OnTableAndBlockRead {
if err = blk.verifyCheckSum(); err != nil {
return nil, err
}
}
blk.incrRef()
if useCache && t.opt.BlockCache != nil {
key := t.blockCacheKey(idx)
// incrRef should never return false here because we're calling it on a
// new block with ref=1.
y.AssertTrue(blk.incrRef())
// Decrement the block ref if we could not insert it in the cache.
if !t.opt.BlockCache.Set(key, blk, blk.size()) {
blk.decrRef()
}
// We have added an OnReject func in our cache, which gets called in case the block is not
// admitted to the cache. So, every block would be accounted for.
}
return blk, nil
}
// blockCacheKey is used to store blocks in the block cache.
func (t *Table) blockCacheKey(idx int) []byte {
y.AssertTrue(t.id < math.MaxUint32)
y.AssertTrue(uint32(idx) < math.MaxUint32)
buf := make([]byte, 8)
// Assume t.ID does not overflow uint32.
binary.BigEndian.PutUint32(buf[:4], uint32(t.ID()))
binary.BigEndian.PutUint32(buf[4:], uint32(idx))
return buf
}
// indexKey returns the cache key for block offsets. blockOffsets
// are stored in the index cache.
func (t *Table) indexKey() uint64 {
return t.id
}
// IndexSize is the size of table index in bytes.
func (t *Table) IndexSize() int {
return t.indexLen
}
// Size is its file size in bytes
func (t *Table) Size() int64 { return int64(t.tableSize) }
// StaleDataSize is the amount of stale data (that can be dropped by a compaction )in this SST.
func (t *Table) StaleDataSize() uint32 { return t.fetchIndex().StaleDataSize() }
// Smallest is its smallest key, or nil if there are none
func (t *Table) Smallest() []byte { return t.smallest }
// Biggest is its biggest key, or nil if there are none
func (t *Table) Biggest() []byte { return t.biggest }
// Filename is NOT the file name. Just kidding, it is.
func (t *Table) Filename() string { return t.Fd.Name() }
// ID is the table's ID number (used to make the file name).
func (t *Table) ID() uint64 { return t.id }
// DoesNotHave returns true if and only if the table does not have the key hash.
// It does a bloom filter lookup.
func (t *Table) DoesNotHave(hash uint32) bool {
if !t.hasBloomFilter {
return false
}
y.NumLSMBloomHitsAdd(t.opt.MetricsEnabled, "DoesNotHave_ALL", 1)
index := t.fetchIndex()
bf := index.BloomFilterBytes()
mayContain := y.Filter(bf).MayContain(hash)
if !mayContain {
y.NumLSMBloomHitsAdd(t.opt.MetricsEnabled, "DoesNotHave_HIT", 1)
}
return !mayContain
}
// readTableIndex reads table index from the sst and returns its pb format.
func (t *Table) readTableIndex() (*fb.TableIndex, error) {
data := t.readNoFail(t.indexStart, t.indexLen)
var err error
// Decrypt the table index if it is encrypted.
if t.shouldDecrypt() {
if data, err = t.decrypt(data, false); err != nil {
return nil, y.Wrapf(err,
"Error while decrypting table index for the table %d in readTableIndex", t.id)
}
}
return fb.GetRootAsTableIndex(data, 0), nil
}
// VerifyChecksum verifies checksum for all blocks of table. This function is called by
// OpenTable() function. This function is also called inside levelsController.VerifyChecksum().
func (t *Table) VerifyChecksum() error {
ti := t.fetchIndex()
for i := 0; i < ti.OffsetsLength(); i++ {
b, err := t.block(i, true)
if err != nil {
return y.Wrapf(err, "checksum validation failed for table: %s, block: %d, offset:%d",
t.Filename(), i, b.offset)
}
// We should not call incrRef here, because the block already has one ref when created.
defer b.decrRef()
// OnBlockRead or OnTableAndBlockRead, we don't need to call verify checksum
// on block, verification would be done while reading block itself.
if !(t.opt.ChkMode == options.OnBlockRead || t.opt.ChkMode == options.OnTableAndBlockRead) {
if err = b.verifyCheckSum(); err != nil {
return y.Wrapf(err,
"checksum validation failed for table: %s, block: %d, offset:%d",
t.Filename(), i, b.offset)
}
}
}
return nil
}
// shouldDecrypt tells whether to decrypt or not. We decrypt only if the datakey exist
// for the table.
func (t *Table) shouldDecrypt() bool {
return t.opt.DataKey != nil
}
// KeyID returns data key id.
func (t *Table) KeyID() uint64 {
if t.opt.DataKey != nil {
return t.opt.DataKey.KeyId
}
// By default it's 0, if it is plain text.
return 0
}
// decrypt decrypts the given data. It should be called only after checking shouldDecrypt.
func (t *Table) decrypt(data []byte, viaCalloc bool) ([]byte, error) {
// Last BlockSize bytes of the data is the IV.
iv := data[len(data)-aes.BlockSize:]
// Rest all bytes are data.
data = data[:len(data)-aes.BlockSize]
var dst []byte
if viaCalloc {
dst = z.Calloc(len(data), "Table.Decrypt")
} else {
dst = make([]byte, len(data))
}
if err := y.XORBlock(dst, data, t.opt.DataKey.Data, iv); err != nil {
return nil, y.Wrapf(err, "while decrypt")
}
return dst, nil
}
// ParseFileID reads the file id out of a filename.
func ParseFileID(name string) (uint64, bool) {
name = filepath.Base(name)
if !strings.HasSuffix(name, fileSuffix) {
return 0, false
}
// suffix := name[len(fileSuffix):]
name = strings.TrimSuffix(name, fileSuffix)
id, err := strconv.Atoi(name)
if err != nil {
return 0, false
}
y.AssertTrue(id >= 0)
return uint64(id), true
}
// IDToFilename does the inverse of ParseFileID
func IDToFilename(id uint64) string {
return fmt.Sprintf("%06d", id) + fileSuffix
}
// NewFilename should be named TableFilepath -- it combines the dir with the ID to make a table
// filepath.
func NewFilename(id uint64, dir string) string {
return filepath.Join(dir, IDToFilename(id))
}
// decompress decompresses the data stored in a block.
func (t *Table) decompress(b *Block) error {
var dst []byte
var err error
// Point to the original b.data
src := b.data
switch t.opt.Compression {
case options.None:
// Nothing to be done here.
return nil
case options.Snappy:
if sz, err := snappy.DecodedLen(b.data); err == nil {
dst = z.Calloc(sz, "Table.Decompress")
} else {
dst = z.Calloc(len(b.data)*4, "Table.Decompress") // Take a guess.
}
b.data, err = snappy.Decode(dst, b.data)
if err != nil {
z.Free(dst)
return y.Wrap(err, "failed to decompress")
}
case options.ZSTD:
sz := int(float64(t.opt.BlockSize) * 1.2)
// Get frame content size from header.
var hdr zstd.Header
if err := hdr.Decode(b.data); err == nil && hdr.HasFCS && hdr.FrameContentSize < uint64(t.opt.BlockSize*2) {
sz = int(hdr.FrameContentSize)
}
dst = z.Calloc(sz, "Table.Decompress")
b.data, err = y.ZSTDDecompress(dst, b.data)
if err != nil {
z.Free(dst)
return y.Wrap(err, "failed to decompress")
}
default:
return errors.New("Unsupported compression type")
}
if b.freeMe {
z.Free(src)
b.freeMe = false
}
if len(b.data) > 0 && len(dst) > 0 && &dst[0] != &b.data[0] {
z.Free(dst)
} else {
b.freeMe = true
}
return nil
}
================================================
FILE: table/table_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package table
import (
"bytes"
"crypto/sha256"
"fmt"
"hash/crc32"
"math/rand"
"os"
"sort"
"strings"
"sync"
"testing"
"time"
"github.com/cespare/xxhash/v2"
"github.com/stretchr/testify/require"
"github.com/dgraph-io/badger/v4/options"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2"
)
func key(prefix string, i int) string {
return prefix + fmt.Sprintf("%04d", i)
}
func getTestTableOptions() Options {
return Options{
Compression: options.ZSTD,
ZSTDCompressionLevel: 15,
BlockSize: 4 * 1024,
BloomFalsePositive: 0.01,
}
}
func buildTestTable(t *testing.T, prefix string, n int, opts Options) *Table {
if opts.BlockSize == 0 {
opts.BlockSize = 4 * 1024
}
y.AssertTrue(n <= 10000)
keyValues := make([][]string, n)
for i := 0; i < n; i++ {
k := key(prefix, i)
v := fmt.Sprintf("%d", i)
keyValues[i] = []string{k, v}
}
return buildTable(t, keyValues, opts)
}
// keyValues is n by 2 where n is number of pairs.
func buildTable(t *testing.T, keyValues [][]string, opts Options) *Table {
b := NewTableBuilder(opts)
defer b.Close()
// TODO: Add test for file garbage collection here. No files should be left after the tests here.
filename := fmt.Sprintf("%s%s%d.sst", os.TempDir(), string(os.PathSeparator), rand.Uint32())
sort.Slice(keyValues, func(i, j int) bool {
return keyValues[i][0] < keyValues[j][0]
})
for _, kv := range keyValues {
y.AssertTrue(len(kv) == 2)
b.Add(y.KeyWithTs([]byte(kv[0]), 0),
y.ValueStruct{Value: []byte(kv[1]), Meta: 'A', UserMeta: 0}, 0)
}
tbl, err := CreateTable(filename, b)
require.NoError(t, err, "writing to file failed")
return tbl
}
func TestTableIterator(t *testing.T) {
for _, n := range []int{99, 100, 101} {
t.Run(fmt.Sprintf("n=%d", n), func(t *testing.T) {
opts := getTestTableOptions()
table := buildTestTable(t, "key", n, opts)
defer func() { require.NoError(t, table.DecrRef()) }()
it := table.NewIterator(0)
defer it.Close()
count := 0
for it.Rewind(); it.Valid(); it.Next() {
v := it.Value()
k := y.KeyWithTs([]byte(key("key", count)), 0)
require.EqualValues(t, k, it.Key())
require.EqualValues(t, fmt.Sprintf("%d", count), string(v.Value))
count++
}
require.Equal(t, count, n)
})
}
}
func TestSeekToFirst(t *testing.T) {
for _, n := range []int{99, 100, 101, 199, 200, 250, 9999, 10000} {
t.Run(fmt.Sprintf("n=%d", n), func(t *testing.T) {
opts := getTestTableOptions()
table := buildTestTable(t, "key", n, opts)
defer func() { require.NoError(t, table.DecrRef()) }()
it := table.NewIterator(0)
defer it.Close()
it.seekToFirst()
require.True(t, it.Valid())
v := it.Value()
require.EqualValues(t, "0", string(v.Value))
require.EqualValues(t, 'A', v.Meta)
})
}
}
func TestSeekToLast(t *testing.T) {
for _, n := range []int{99, 100, 101, 199, 200, 250, 9999, 10000} {
t.Run(fmt.Sprintf("n=%d", n), func(t *testing.T) {
opts := getTestTableOptions()
table := buildTestTable(t, "key", n, opts)
defer func() { require.NoError(t, table.DecrRef()) }()
it := table.NewIterator(0)
defer it.Close()
it.seekToLast()
require.True(t, it.Valid())
v := it.Value()
require.EqualValues(t, fmt.Sprintf("%d", n-1), string(v.Value))
require.EqualValues(t, 'A', v.Meta)
it.prev()
require.True(t, it.Valid())
v = it.Value()
require.EqualValues(t, fmt.Sprintf("%d", n-2), string(v.Value))
require.EqualValues(t, 'A', v.Meta)
})
}
}
func TestSeek(t *testing.T) {
opts := getTestTableOptions()
table := buildTestTable(t, "k", 10000, opts)
defer func() { require.NoError(t, table.DecrRef()) }()
it := table.NewIterator(0)
defer it.Close()
var data = []struct {
in string
valid bool
out string
}{
{"abc", true, "k0000"},
{"k0100", true, "k0100"},
{"k0100b", true, "k0101"}, // Test case where we jump to next block.
{"k1234", true, "k1234"},
{"k1234b", true, "k1235"},
{"k9999", true, "k9999"},
{"z", false, ""},
}
for _, tt := range data {
it.seek(y.KeyWithTs([]byte(tt.in), 0))
if !tt.valid {
require.False(t, it.Valid())
continue
}
require.True(t, it.Valid())
k := it.Key()
require.EqualValues(t, tt.out, string(y.ParseKey(k)))
}
}
func TestSeekForPrev(t *testing.T) {
opts := getTestTableOptions()
table := buildTestTable(t, "k", 10000, opts)
defer func() { require.NoError(t, table.DecrRef()) }()
it := table.NewIterator(0)
defer it.Close()
var data = []struct {
in string
valid bool
out string
}{
{"abc", false, ""},
{"k0100", true, "k0100"},
{"k0100b", true, "k0100"}, // Test case where we jump to next block.
{"k1234", true, "k1234"},
{"k1234b", true, "k1234"},
{"k9999", true, "k9999"},
{"z", true, "k9999"},
}
for _, tt := range data {
it.seekForPrev(y.KeyWithTs([]byte(tt.in), 0))
if !tt.valid {
require.False(t, it.Valid())
continue
}
require.True(t, it.Valid())
k := it.Key()
require.EqualValues(t, tt.out, string(y.ParseKey(k)))
}
}
func TestIterateFromStart(t *testing.T) {
// Vary the number of elements added.
for _, n := range []int{99, 100, 101, 199, 200, 250, 9999, 10000} {
t.Run(fmt.Sprintf("n=%d", n), func(t *testing.T) {
opts := getTestTableOptions()
table := buildTestTable(t, "key", n, opts)
defer func() { require.NoError(t, table.DecrRef()) }()
ti := table.NewIterator(0)
defer ti.Close()
ti.reset()
ti.seekToFirst()
require.True(t, ti.Valid())
// No need to do a Next.
// ti.Seek brings us to the first key >= "". Essentially a SeekToFirst.
var count int
for ; ti.Valid(); ti.next() {
v := ti.Value()
require.EqualValues(t, fmt.Sprintf("%d", count), string(v.Value))
require.EqualValues(t, 'A', v.Meta)
count++
}
require.EqualValues(t, n, count)
})
}
}
func TestIterateFromEnd(t *testing.T) {
// Vary the number of elements added.
for _, n := range []int{99, 100, 101, 199, 200, 250, 9999, 10000} {
t.Run(fmt.Sprintf("n=%d", n), func(t *testing.T) {
opts := getTestTableOptions()
table := buildTestTable(t, "key", n, opts)
defer func() { require.NoError(t, table.DecrRef()) }()
ti := table.NewIterator(0)
defer ti.Close()
ti.reset()
ti.seek(y.KeyWithTs([]byte("zzzzzz"), 0)) // Seek to end, an invalid element.
require.False(t, ti.Valid())
for i := n - 1; i >= 0; i-- {
ti.prev()
require.True(t, ti.Valid())
v := ti.Value()
require.EqualValues(t, fmt.Sprintf("%d", i), string(v.Value))
require.EqualValues(t, 'A', v.Meta)
}
ti.prev()
require.False(t, ti.Valid())
})
}
}
func TestTable(t *testing.T) {
opts := getTestTableOptions()
table := buildTestTable(t, "key", 10000, opts)
defer func() { require.NoError(t, table.DecrRef()) }()
ti := table.NewIterator(0)
defer ti.Close()
kid := 1010
seek := y.KeyWithTs([]byte(key("key", kid)), 0)
for ti.seek(seek); ti.Valid(); ti.next() {
k := ti.Key()
require.EqualValues(t, string(y.ParseKey(k)), key("key", kid))
kid++
}
if kid != 10000 {
t.Errorf("Expected kid: 10000. Got: %v", kid)
}
ti.seek(y.KeyWithTs([]byte(key("key", 99999)), 0))
require.False(t, ti.Valid())
ti.seek(y.KeyWithTs([]byte(key("key", -1)), 0))
require.True(t, ti.Valid())
k := ti.Key()
require.EqualValues(t, string(y.ParseKey(k)), key("key", 0))
}
func TestIterateBackAndForth(t *testing.T) {
opts := getTestTableOptions()
table := buildTestTable(t, "key", 10000, opts)
defer func() { require.NoError(t, table.DecrRef()) }()
seek := y.KeyWithTs([]byte(key("key", 1010)), 0)
it := table.NewIterator(0)
defer it.Close()
it.seek(seek)
require.True(t, it.Valid())
k := it.Key()
require.EqualValues(t, seek, k)
it.prev()
it.prev()
require.True(t, it.Valid())
k = it.Key()
require.EqualValues(t, key("key", 1008), string(y.ParseKey(k)))
it.next()
it.next()
require.True(t, it.Valid())
k = it.Key()
require.EqualValues(t, key("key", 1010), y.ParseKey(k))
it.seek(y.KeyWithTs([]byte(key("key", 2000)), 0))
require.True(t, it.Valid())
k = it.Key()
require.EqualValues(t, key("key", 2000), y.ParseKey(k))
it.prev()
require.True(t, it.Valid())
k = it.Key()
require.EqualValues(t, key("key", 1999), y.ParseKey(k))
it.seekToFirst()
k = it.Key()
require.EqualValues(t, key("key", 0), string(y.ParseKey(k)))
}
func TestUniIterator(t *testing.T) {
opts := getTestTableOptions()
table := buildTestTable(t, "key", 10000, opts)
defer func() { require.NoError(t, table.DecrRef()) }()
{
it := table.NewIterator(0)
defer it.Close()
var count int
for it.Rewind(); it.Valid(); it.Next() {
v := it.Value()
require.EqualValues(t, fmt.Sprintf("%d", count), string(v.Value))
require.EqualValues(t, 'A', v.Meta)
count++
}
require.EqualValues(t, 10000, count)
}
{
it := table.NewIterator(REVERSED)
defer it.Close()
var count int
for it.Rewind(); it.Valid(); it.Next() {
v := it.Value()
require.EqualValues(t, fmt.Sprintf("%d", 10000-1-count), string(v.Value))
require.EqualValues(t, 'A', v.Meta)
count++
}
require.EqualValues(t, 10000, count)
}
}
// Try having only one table.
func TestConcatIteratorOneTable(t *testing.T) {
opts := getTestTableOptions()
tbl := buildTable(t, [][]string{
{"k1", "a1"},
{"k2", "a2"},
}, opts)
defer func() { require.NoError(t, tbl.DecrRef()) }()
it := NewConcatIterator([]*Table{tbl}, 0)
defer it.Close()
it.Rewind()
require.True(t, it.Valid())
k := it.Key()
require.EqualValues(t, "k1", string(y.ParseKey(k)))
vs := it.Value()
require.EqualValues(t, "a1", string(vs.Value))
require.EqualValues(t, 'A', vs.Meta)
}
func TestConcatIterator(t *testing.T) {
opts := getTestTableOptions()
tbl := buildTestTable(t, "keya", 10000, opts)
defer func() { require.NoError(t, tbl.DecrRef()) }()
tbl2 := buildTestTable(t, "keyb", 10000, opts)
defer func() { require.NoError(t, tbl2.DecrRef()) }()
tbl3 := buildTestTable(t, "keyc", 10000, opts)
defer func() { require.NoError(t, tbl3.DecrRef()) }()
{
it := NewConcatIterator([]*Table{tbl, tbl2, tbl3}, 0)
defer it.Close()
it.Rewind()
require.True(t, it.Valid())
var count int
for ; it.Valid(); it.Next() {
vs := it.Value()
require.EqualValues(t, fmt.Sprintf("%d", count%10000), string(vs.Value))
require.EqualValues(t, 'A', vs.Meta)
count++
}
require.EqualValues(t, 30000, count)
it.Seek(y.KeyWithTs([]byte("a"), 0))
require.EqualValues(t, "keya0000", string(y.ParseKey(it.Key())))
vs := it.Value()
require.EqualValues(t, "0", string(vs.Value))
it.Seek(y.KeyWithTs([]byte("keyb"), 0))
require.EqualValues(t, "keyb0000", string(y.ParseKey(it.Key())))
vs = it.Value()
require.EqualValues(t, "0", string(vs.Value))
it.Seek(y.KeyWithTs([]byte("keyb9999b"), 0))
require.EqualValues(t, "keyc0000", string(y.ParseKey(it.Key())))
vs = it.Value()
require.EqualValues(t, "0", string(vs.Value))
it.Seek(y.KeyWithTs([]byte("keyd"), 0))
require.False(t, it.Valid())
}
{
it := NewConcatIterator([]*Table{tbl, tbl2, tbl3}, REVERSED)
defer it.Close()
it.Rewind()
require.True(t, it.Valid())
var count int
for ; it.Valid(); it.Next() {
vs := it.Value()
require.EqualValues(t, fmt.Sprintf("%d", 10000-(count%10000)-1), string(vs.Value))
require.EqualValues(t, 'A', vs.Meta)
count++
}
require.EqualValues(t, 30000, count)
it.Seek(y.KeyWithTs([]byte("a"), 0))
require.False(t, it.Valid())
it.Seek(y.KeyWithTs([]byte("keyb"), 0))
require.EqualValues(t, "keya9999", string(y.ParseKey(it.Key())))
vs := it.Value()
require.EqualValues(t, "9999", string(vs.Value))
it.Seek(y.KeyWithTs([]byte("keyb9999b"), 0))
require.EqualValues(t, "keyb9999", string(y.ParseKey(it.Key())))
vs = it.Value()
require.EqualValues(t, "9999", string(vs.Value))
it.Seek(y.KeyWithTs([]byte("keyd"), 0))
require.EqualValues(t, "keyc9999", string(y.ParseKey(it.Key())))
vs = it.Value()
require.EqualValues(t, "9999", string(vs.Value))
}
}
func TestMergingIterator(t *testing.T) {
opts := getTestTableOptions()
tbl1 := buildTable(t, [][]string{
{"k1", "a1"},
{"k4", "a4"},
{"k5", "a5"},
}, opts)
defer func() { require.NoError(t, tbl1.DecrRef()) }()
tbl2 := buildTable(t, [][]string{
{"k2", "b2"},
{"k3", "b3"},
{"k4", "b4"},
}, opts)
defer func() { require.NoError(t, tbl2.DecrRef()) }()
expected := []struct {
key string
value string
}{
{"k1", "a1"},
{"k2", "b2"},
{"k3", "b3"},
{"k4", "a4"},
{"k5", "a5"},
}
it1 := tbl1.NewIterator(0)
it2 := NewConcatIterator([]*Table{tbl2}, 0)
it := NewMergeIterator([]y.Iterator{it1, it2}, false)
defer it.Close()
var i int
for it.Rewind(); it.Valid(); it.Next() {
k := it.Key()
vs := it.Value()
require.EqualValues(t, expected[i].key, string(y.ParseKey(k)))
require.EqualValues(t, expected[i].value, string(vs.Value))
require.EqualValues(t, 'A', vs.Meta)
i++
}
require.Equal(t, i, len(expected))
require.False(t, it.Valid())
}
func TestMergingIteratorReversed(t *testing.T) {
opts := getTestTableOptions()
tbl1 := buildTable(t, [][]string{
{"k1", "a1"},
{"k2", "a2"},
{"k4", "a4"},
{"k5", "a5"},
}, opts)
defer func() { require.NoError(t, tbl1.DecrRef()) }()
tbl2 := buildTable(t, [][]string{
{"k1", "b2"},
{"k3", "b3"},
{"k4", "b4"},
{"k5", "b5"},
}, opts)
defer func() { require.NoError(t, tbl2.DecrRef()) }()
expected := []struct {
key string
value string
}{
{"k5", "a5"},
{"k4", "a4"},
{"k3", "b3"},
{"k2", "a2"},
{"k1", "a1"},
}
it1 := tbl1.NewIterator(REVERSED)
it2 := NewConcatIterator([]*Table{tbl2}, REVERSED)
it := NewMergeIterator([]y.Iterator{it1, it2}, true)
defer it.Close()
var i int
for it.Rewind(); it.Valid(); it.Next() {
k := it.Key()
vs := it.Value()
require.EqualValues(t, expected[i].key, string(y.ParseKey(k)))
require.EqualValues(t, expected[i].value, string(vs.Value))
require.EqualValues(t, 'A', vs.Meta)
i++
}
require.Equal(t, i, len(expected))
require.False(t, it.Valid())
}
// Take only the first iterator.
func TestMergingIteratorTakeOne(t *testing.T) {
opts := getTestTableOptions()
t1 := buildTable(t, [][]string{
{"k1", "a1"},
{"k2", "a2"},
}, opts)
defer func() { require.NoError(t, t1.DecrRef()) }()
t2 := buildTable(t, [][]string{{"l1", "b1"}}, opts)
defer func() { require.NoError(t, t2.DecrRef()) }()
it1 := NewConcatIterator([]*Table{t1}, 0)
it2 := NewConcatIterator([]*Table{t2}, 0)
it := NewMergeIterator([]y.Iterator{it1, it2}, false)
defer it.Close()
it.Rewind()
require.True(t, it.Valid())
k := it.Key()
require.EqualValues(t, "k1", string(y.ParseKey(k)))
vs := it.Value()
require.EqualValues(t, "a1", string(vs.Value))
require.EqualValues(t, 'A', vs.Meta)
it.Next()
require.True(t, it.Valid())
k = it.Key()
require.EqualValues(t, "k2", string(y.ParseKey(k)))
vs = it.Value()
require.EqualValues(t, "a2", string(vs.Value))
require.EqualValues(t, 'A', vs.Meta)
it.Next()
k = it.Key()
require.EqualValues(t, "l1", string(y.ParseKey(k)))
vs = it.Value()
require.EqualValues(t, "b1", string(vs.Value))
require.EqualValues(t, 'A', vs.Meta)
it.Next()
require.False(t, it.Valid())
}
// Take only the second iterator.
func TestMergingIteratorTakeTwo(t *testing.T) {
opts := getTestTableOptions()
t1 := buildTable(t, [][]string{{"l1", "b1"}}, opts)
defer func() { require.NoError(t, t1.DecrRef()) }()
t2 := buildTable(t, [][]string{
{"k1", "a1"},
{"k2", "a2"},
}, opts)
defer func() { require.NoError(t, t2.DecrRef()) }()
it1 := NewConcatIterator([]*Table{t1}, 0)
it2 := NewConcatIterator([]*Table{t2}, 0)
it := NewMergeIterator([]y.Iterator{it1, it2}, false)
defer it.Close()
it.Rewind()
require.True(t, it.Valid())
k := it.Key()
require.EqualValues(t, "k1", string(y.ParseKey(k)))
vs := it.Value()
require.EqualValues(t, "a1", string(vs.Value))
require.EqualValues(t, 'A', vs.Meta)
it.Next()
require.True(t, it.Valid())
k = it.Key()
require.EqualValues(t, "k2", string(y.ParseKey(k)))
vs = it.Value()
require.EqualValues(t, "a2", string(vs.Value))
require.EqualValues(t, 'A', vs.Meta)
it.Next()
require.True(t, it.Valid())
k = it.Key()
require.EqualValues(t, "l1", string(y.ParseKey(k)))
vs = it.Value()
require.EqualValues(t, "b1", string(vs.Value))
require.EqualValues(t, 'A', vs.Meta)
it.Next()
require.False(t, it.Valid())
}
func TestTableBigValues(t *testing.T) {
value := func(i int) []byte {
return []byte(fmt.Sprintf("%01048576d", i)) // Return 1MB value which is > math.MaxUint16.
}
rand.Seed(time.Now().UnixNano())
n := 100 // Insert 100 keys.
opts := Options{Compression: options.ZSTD, BlockSize: 4 * 1024, BloomFalsePositive: 0.01,
TableSize: uint64(n) * 1 << 20}
builder := NewTableBuilder(opts)
defer builder.Close()
for i := 0; i < n; i++ {
key := y.KeyWithTs([]byte(key("", i)), uint64(i+1))
vs := y.ValueStruct{Value: value(i)}
builder.Add(key, vs, 0)
}
filename := fmt.Sprintf("%s%s%d.sst", os.TempDir(), string(os.PathSeparator), rand.Uint32())
tbl, err := CreateTable(filename, builder)
require.NoError(t, err, "unable to open table")
defer func() { require.NoError(t, tbl.DecrRef()) }()
itr := tbl.NewIterator(0)
require.True(t, itr.Valid())
count := 0
for itr.Rewind(); itr.Valid(); itr.Next() {
require.Equal(t, []byte(key("", count)), y.ParseKey(itr.Key()), "keys are not equal")
require.Equal(t, value(count), itr.Value().Value, "values are not equal")
count++
}
require.False(t, itr.Valid(), "table iterator should be invalid now")
require.Equal(t, n, count)
require.Equal(t, n, int(tbl.MaxVersion()))
}
// This test is for verifying checksum failure during table open.
func TestTableChecksum(t *testing.T) {
rand.Seed(time.Now().Unix())
// we are going to write random byte at random location in table file.
rb := make([]byte, 100)
rand.Read(rb)
opts := getTestTableOptions()
opts.ChkMode = options.OnTableAndBlockRead
// When verifying checksum capability, we find it simpler to disable compression
// since randomly initializing bytes can kill the compression storage.
opts.Compression = options.None
tbl := buildTestTable(t, "k", 10000, opts)
defer func() { require.NoError(t, tbl.DecrRef()) }()
// Write random bytes at location guaranteed to not be in range of
// metadata for block. (No particular reason for the value 128,
// it just avoids the sensitive block size or other metadata blocks).
start := 128
n := copy(tbl.Data[start:], rb)
require.Equal(t, n, len(rb))
require.Panics(t, func() {
// Either OpenTable will panic on corrupted data or the checksum verification will fail.
_, err := OpenTable(tbl.MmapFile, opts)
if strings.Contains(err.Error(), "checksum") {
panic("checksum mismatch")
} else {
require.NoError(t, err)
}
})
}
var cacheConfig = ristretto.Config[[]byte, *Block]{
NumCounters: 1000000 * 10,
MaxCost: 1000000,
BufferItems: 64,
Metrics: true,
}
func BenchmarkRead(b *testing.B) {
n := int(5 * 1e6)
tbl := getTableForBenchmarks(b, n, nil)
defer func() { _ = tbl.DecrRef() }()
b.ResetTimer()
// Iterate b.N times over the entire table.
for i := 0; i < b.N; i++ {
func() {
it := tbl.NewIterator(0)
defer it.Close()
for it.seekToFirst(); it.Valid(); it.next() {
}
}()
}
}
func BenchmarkReadAndBuild(b *testing.B) {
n := int(5 * 1e6)
var cache, _ = ristretto.NewCache(&cacheConfig)
tbl := getTableForBenchmarks(b, n, cache)
defer func() { _ = tbl.DecrRef() }()
b.ResetTimer()
// Iterate b.N times over the entire table.
for i := 0; i < b.N; i++ {
func() {
opts := Options{Compression: options.ZSTD, BlockSize: 4 * 0124, BloomFalsePositive: 0.01}
opts.BlockCache = cache
newBuilder := NewTableBuilder(opts)
it := tbl.NewIterator(0)
defer it.Close()
for it.seekToFirst(); it.Valid(); it.next() {
vs := it.Value()
newBuilder.Add(it.Key(), vs, 0)
}
newBuilder.Finish()
}()
}
}
func BenchmarkReadMerged(b *testing.B) {
n := int(5 * 1e6)
m := 5 // Number of tables.
y.AssertTrue((n % m) == 0)
tableSize := n / m
var tables []*Table
var cache, err = ristretto.NewCache(&cacheConfig)
require.NoError(b, err)
for i := 0; i < m; i++ {
filename := fmt.Sprintf("%s%s%d.sst", os.TempDir(), string(os.PathSeparator), rand.Uint32())
opts := Options{Compression: options.ZSTD, BlockSize: 4 * 1024, BloomFalsePositive: 0.01}
opts.BlockCache = cache
builder := NewTableBuilder(opts)
for j := 0; j < tableSize; j++ {
id := j*m + i // Arrays are interleaved.
// id := i*tableSize+j (not interleaved)
k := fmt.Sprintf("%016x", id)
v := fmt.Sprintf("%d", id)
builder.Add([]byte(k), y.ValueStruct{Value: []byte(v), Meta: 123, UserMeta: 0}, 0)
}
tbl, err := CreateTable(filename, builder)
y.Check(err)
builder.Close()
tables = append(tables, tbl)
defer func() { _ = tbl.DecrRef() }()
}
b.ResetTimer()
// Iterate b.N times over the entire table.
for i := 0; i < b.N; i++ {
func() {
var iters []y.Iterator
for _, tbl := range tables {
iters = append(iters, tbl.NewIterator(0))
}
it := NewMergeIterator(iters, false)
defer it.Close()
for it.Rewind(); it.Valid(); it.Next() {
}
}()
}
}
func BenchmarkChecksum(b *testing.B) {
keySz := []int{KB, 2 * KB, 4 * KB, 8 * KB, 16 * KB, 32 * KB, 64 * KB, 128 * KB, 256 * KB, MB}
for _, kz := range keySz {
key := make([]byte, kz)
b.Run(fmt.Sprintf("CRC %d", kz), func(b *testing.B) {
for i := 0; i < b.N; i++ {
crc32.ChecksumIEEE(key)
}
})
b.Run(fmt.Sprintf("xxHash64 %d", kz), func(b *testing.B) {
for i := 0; i < b.N; i++ {
xxhash.Sum64(key)
}
})
b.Run(fmt.Sprintf("SHA256 %d", kz), func(b *testing.B) {
for i := 0; i < b.N; i++ {
sha256.Sum256(key)
}
})
}
}
func BenchmarkRandomRead(b *testing.B) {
n := int(5 * 1e6)
tbl := getTableForBenchmarks(b, n, nil)
defer func() { _ = tbl.DecrRef() }()
r := rand.New(rand.NewSource(time.Now().Unix()))
b.ResetTimer()
for i := 0; i < b.N; i++ {
itr := tbl.NewIterator(0)
no := r.Intn(n)
k := []byte(fmt.Sprintf("%016x", no))
v := []byte(fmt.Sprintf("%d", no))
itr.Seek(k)
if !itr.Valid() {
b.Fatal("itr should be valid")
}
v1 := itr.Value().Value
if !bytes.Equal(v, v1) {
fmt.Println("value does not match")
b.Fatal()
}
itr.Close()
}
}
func getTableForBenchmarks(b *testing.B, count int, cache *ristretto.Cache[[]byte, *Block]) *Table {
rand.Seed(time.Now().Unix())
opts := Options{Compression: options.ZSTD, BlockSize: 4 * 1024, BloomFalsePositive: 0.01}
if cache == nil {
var err error
cache, err = ristretto.NewCache(&cacheConfig)
require.NoError(b, err)
}
opts.BlockCache = cache
builder := NewTableBuilder(opts)
defer builder.Close()
filename := fmt.Sprintf("%s%s%d.sst", os.TempDir(), string(os.PathSeparator), rand.Uint32())
for i := 0; i < count; i++ {
k := fmt.Sprintf("%016x", i)
v := fmt.Sprintf("%d", i)
builder.Add([]byte(k), y.ValueStruct{Value: []byte(v)}, 0)
}
tbl, err := CreateTable(filename, builder)
require.NoError(b, err, "unable to open table")
return tbl
}
func TestMain(m *testing.M) {
rand.Seed(time.Now().UTC().UnixNano())
os.Exit(m.Run())
}
// Run this test with command "go test -race -run TestDoesNotHaveRace"
func TestDoesNotHaveRace(t *testing.T) {
opts := getTestTableOptions()
table := buildTestTable(t, "key", 10000, opts)
defer func() { require.NoError(t, table.DecrRef()) }()
var wg sync.WaitGroup
wg.Add(5)
for i := 0; i < 5; i++ {
go func() {
require.True(t, table.DoesNotHave(uint32(1237882)))
wg.Done()
}()
}
wg.Wait()
}
func TestMaxVersion(t *testing.T) {
opt := getTestTableOptions()
b := NewTableBuilder(opt)
defer b.Close()
filename := fmt.Sprintf("%s%s%d.sst", os.TempDir(), string(os.PathSeparator), rand.Uint32())
N := 1000
for i := 0; i < N; i++ {
b.Add(y.KeyWithTs([]byte(fmt.Sprintf("foo:%d", i)), uint64(i+1)), y.ValueStruct{}, 0)
}
table, err := CreateTable(filename, b)
require.NoError(t, err)
require.Equal(t, N, int(table.MaxVersion()))
}
================================================
FILE: test.sh
================================================
#!/bin/bash
set -eo pipefail
go version
# Check if Github Actions is running
if [ "$CI" = "true" ]; then
# Enable code coverage
# export because tests run in a subprocess
export covermode="-covermode=atomic"
export coverprofile="-coverprofile=cover_tmp.out"
echo "mode: atomic" >>cover.out
fi
# Run `go list` BEFORE setting GOFLAGS so that the output is in the right
# format for grep.
# export packages because the test will run in a sub process.
export packages=$(go list ./... | grep "github.com/dgraph-io/badger/v4/")
tags="-tags=jemalloc"
# Compile the Badger binary
pushd badger
go build -v $tags .
popd
# Run the memory intensive tests first.
manual() {
timeout="-timeout 5m"
echo "==> Running package tests for $packages"
set -e
go env -w GOTOOLCHAIN=go1.25.0+auto
for pkg in $packages; do
echo "===> Testing $pkg"
go test $tags -timeout=25m $covermode $coverprofile -failfast -race -parallel 16 $pkg && write_coverage || return 1
done
echo "==> DONE package tests"
echo "==> Running manual tests"
# Run the special Truncate test.
rm -rf p
set -e
go test $tags $timeout $covermode $coverprofile -run='TestTruncateVlogNoClose$' -failfast --manual=true && write_coverage || return 1
truncate --size=4096 p/000000.vlog
go test $tags $timeout $covermode $coverprofile -run='TestTruncateVlogNoClose2$' -failfast --manual=true && write_coverage || return 1
go test $tags $timeout $covermode $coverprofile -run='TestTruncateVlogNoClose3$' -failfast --manual=true && write_coverage || return 1
rm -rf p
# TODO(ibrahim): Let's make these tests have Manual prefix.
# go test $tags -run='TestManual' --manual=true --parallel=2
# TestWriteBatch
# TestValueGCManaged
# TestDropPrefix
# TestDropAllManaged
go test $tags $timeout $covermode $coverprofile -failfast -run='TestBigKeyValuePairs$' --manual=true && write_coverage || return 1
go test $tags $timeout $covermode $coverprofile -failfast -run='TestPushValueLogLimit' --manual=true && write_coverage || return 1
go test $tags $timeout $covermode $coverprofile -failfast -run='TestKeyCount' --manual=true && write_coverage || return 1
go test $tags $timeout $covermode $coverprofile -failfast -run='TestIteratePrefix' --manual=true && write_coverage || return 1
go test $tags $timeout $covermode $coverprofile -failfast -run='TestIterateParallel' --manual=true && write_coverage || return 1
go test $tags $timeout $covermode $coverprofile -failfast -run='TestBigStream' --manual=true && write_coverage || return 1
go test $tags $timeout $covermode $coverprofile -failfast -run='TestGoroutineLeak' --manual=true && write_coverage || return 1
go test $tags $timeout $covermode $coverprofile -failfast -run='TestGetMore' --manual=true && write_coverage || return 1
echo "==> DONE manual tests"
}
root() {
# Run the normal tests.
# go test -timeout=25m -v -race github.com/dgraph-io/badger/v4/...
echo "==> Running root level tests."
go test $tags -v -race -parallel=16 -timeout=25m -failfast $covermode $coverprofile . && write_coverage || return 1
echo "==> DONE root level tests"
}
stream() {
set -eo pipefail
pushd badger
baseDir=$(mktemp -d -p .)
./badger benchmark write -s --dir=$baseDir/test | tee $baseDir/log.txt
./badger benchmark read --dir=$baseDir/test --full-scan | tee --append $baseDir/log.txt
./badger benchmark read --dir=$baseDir/test -d=30s | tee --append $baseDir/log.txt
./badger stream --dir=$baseDir/test -o "$baseDir/test2" | tee --append $baseDir/log.txt
count=$(cat "$baseDir/log.txt" | grep "at program end: 0 B" | wc -l)
rm -rf $baseDir
if [ $count -ne 4 ]; then
echo "LEAK detected in Badger stream."
return 1
fi
echo "==> DONE stream test"
popd
return 0
}
write_coverage() {
if [[ $CI == "true" ]]; then
if [[ -f cover_tmp.out ]]; then
sed -i '1d' cover_tmp.out
cat cover_tmp.out >>cover.out && rm cover_tmp.out
fi
fi
}
# parallel tests currently not working
# parallel --halt now,fail=1 --progress --line-buffer ::: stream manual root
# run tests in sequence
root
stream
manual
================================================
FILE: test_extensions.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
// Important: Do NOT import the "testing" package, as otherwise, that
// will pull in imports into the production class that we do not want.
// TODO: Consider using this with specific compilation tags so that it only
// shows up when performing testing (e.g., specify build tag=unit).
// We are not yet ready to do that, as it may impact customer usage as
// well as requiring us to update the CI build flags. Moreover, the
// current model does not actually incur any significant cost.
// If we do this, we will also want to introduce a parallel file that
// overrides some of these structs and functions with empty contents.
// String constants for messages to be pushed to syncChan.
const (
updateDiscardStatsMsg = "updateDiscardStats iteration done"
endVLogInitMsg = "End: vlog.init(db)"
)
// testOnlyOptions specifies an extension to the type Options that we want to
// use only in the context of testing.
type testOnlyOptions struct {
// syncChan is used to listen for specific messages related to activities
// that can occur in a DB instance. Currently, this is only used in
// testing activities.
syncChan chan string
}
// testOnlyDBExtensions specifies an extension to the type DB that we want to
// use only in the context of testing.
type testOnlyDBExtensions struct {
syncChan chan string
// onCloseDiscardCapture will be populated by a DB instance during the
// process of performing the Close operation. Currently, we only consider
// using this during testing.
onCloseDiscardCapture map[uint64]uint64
}
// logToSyncChan sends a message to the DB's syncChan. Note that we expect
// that the DB never closes this channel; the responsibility for
// allocating and closing the channel belongs to the test module.
// if db.syncChan is nil or has never been initialized, this will be
// silently ignored.
func (db *DB) logToSyncChan(msg string) {
if db.syncChan != nil {
db.syncChan <- msg
}
}
// captureDiscardStats will copy the contents of the discardStats file
// maintained by vlog to the onCloseDiscardCapture map specified by
// db.opt. Of course, if db.opt.onCloseDiscardCapture is nil (as expected
// for a production system as opposed to a test system), this is a no-op.
func (db *DB) captureDiscardStats() {
if db.onCloseDiscardCapture != nil {
db.vlog.discardStats.Lock()
db.vlog.discardStats.Iterate(func(id, val uint64) {
db.onCloseDiscardCapture[id] = val
})
db.vlog.discardStats.Unlock()
}
}
================================================
FILE: trie/trie.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package trie
import (
"fmt"
"strconv"
"strings"
"github.com/dgraph-io/badger/v4/pb"
"github.com/dgraph-io/badger/v4/y"
)
type node struct {
children map[byte]*node
ignore *node
ids []uint64
}
func (n *node) isEmpty() bool {
return len(n.children) == 0 && len(n.ids) == 0 && n.ignore == nil
}
func newNode() *node {
return &node{
children: make(map[byte]*node),
ids: []uint64{},
}
}
// Trie datastructure.
type Trie struct {
root *node
}
// NewTrie returns Trie.
func NewTrie() *Trie {
return &Trie{
root: newNode(),
}
}
// parseIgnoreBytes would parse the ignore string, and convert it into a list of bools, where
// bool[idx] = true implies that key[idx] can be ignored during comparison.
func parseIgnoreBytes(ig string) ([]bool, error) {
var out []bool
if ig == "" {
return out, nil
}
for _, each := range strings.Split(strings.TrimSpace(ig), ",") {
r := strings.Split(strings.TrimSpace(each), "-")
if len(r) == 0 || len(r) > 2 {
return out, fmt.Errorf("Invalid range: %s", each)
}
start, end := -1, -1 //nolint:ineffassign
if len(r) == 2 {
idx, err := strconv.Atoi(strings.TrimSpace(r[1]))
if err != nil {
return out, err
}
end = idx
}
{
// Always consider r[0]
idx, err := strconv.Atoi(strings.TrimSpace(r[0]))
if err != nil {
return out, err
}
start = idx
}
if start == -1 {
return out, fmt.Errorf("Invalid range: %s", each)
}
for start >= len(out) {
out = append(out, false)
}
for end >= len(out) { // end could be -1, so do have the start loop above.
out = append(out, false)
}
if end == -1 {
out[start] = true
} else {
for i := start; i <= end; i++ {
out[i] = true
}
}
}
return out, nil
}
// Add adds the id in the trie for the given prefix path.
func (t *Trie) Add(prefix []byte, id uint64) {
m := pb.Match{
Prefix: prefix,
}
y.Check(t.AddMatch(m, id))
}
// AddMatch allows you to send in a prefix match, with "holes" in the prefix. The holes are
// specified via IgnoreBytes in a comma-separated list of indices starting from 0. A dash can be
// used to denote a range. Valid example is "3, 5-8, 10, 12-15". Length of IgnoreBytes does not need
// to match the length of the Prefix passed.
//
// Consider a prefix = "aaaa". If the IgnoreBytes is set to "0, 2", then along with key "aaaa...",
// a key "baba..." would also match.
func (t *Trie) AddMatch(m pb.Match, id uint64) error {
return t.fix(m, id, set)
}
const (
set = iota
del
)
func (t *Trie) fix(m pb.Match, id uint64, op int) error {
curNode := t.root
ignore, err := parseIgnoreBytes(m.IgnoreBytes)
if err != nil {
return fmt.Errorf("while parsing ignore bytes: %s: %w", m.IgnoreBytes, err)
}
for len(ignore) < len(m.Prefix) {
ignore = append(ignore, false)
}
for idx, byt := range m.Prefix {
var child *node
if ignore[idx] {
child = curNode.ignore
if child == nil {
if op == del {
// No valid node found for delete operation. Return immediately.
return nil
}
child = newNode()
curNode.ignore = child
}
} else {
child = curNode.children[byt]
if child == nil {
if op == del {
// No valid node found for delete operation. Return immediately.
return nil
}
child = newNode()
curNode.children[byt] = child
}
}
curNode = child
}
// We only need to add the id to the last node of the given prefix.
if op == set {
curNode.ids = append(curNode.ids, id)
} else if op == del {
out := curNode.ids[:0]
for _, cid := range curNode.ids {
if id != cid {
out = append(out, cid)
}
}
curNode.ids = out
} else {
y.AssertTrue(false)
}
return nil
}
func (t *Trie) Get(key []byte) map[uint64]struct{} {
return t.get(t.root, key)
}
// Get returns prefix matched ids for the given key.
func (t *Trie) get(curNode *node, key []byte) map[uint64]struct{} {
y.AssertTrue(curNode != nil)
out := make(map[uint64]struct{})
// If any node in the path of the key has ids, pick them up.
// This would also match nil prefixes.
for _, i := range curNode.ids {
out[i] = struct{}{}
}
if len(key) == 0 {
return out
}
// If we found an ignore node, traverse that path.
if curNode.ignore != nil {
res := t.get(curNode.ignore, key[1:])
for id := range res {
out[id] = struct{}{}
}
}
if child := curNode.children[key[0]]; child != nil {
res := t.get(child, key[1:])
for id := range res {
out[id] = struct{}{}
}
}
return out
}
func removeEmpty(curNode *node) bool {
// Go depth first.
if curNode.ignore != nil {
if empty := removeEmpty(curNode.ignore); empty {
curNode.ignore = nil
}
}
for byt, n := range curNode.children {
if empty := removeEmpty(n); empty {
delete(curNode.children, byt)
}
}
return curNode.isEmpty()
}
// Delete will delete the id if the id exist in the given index path.
func (t *Trie) Delete(prefix []byte, id uint64) error {
return t.DeleteMatch(pb.Match{Prefix: prefix}, id)
}
func (t *Trie) DeleteMatch(m pb.Match, id uint64) error {
if err := t.fix(m, id, del); err != nil {
return err
}
// Would recursively delete empty nodes.
// Do not remove the t.root even if its empty.
removeEmpty(t.root)
return nil
}
func numNodes(curNode *node) int {
if curNode == nil {
return 0
}
num := numNodes(curNode.ignore)
for _, n := range curNode.children {
num += numNodes(n)
}
return num + 1
}
================================================
FILE: trie/trie_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package trie
import (
"sort"
"testing"
"github.com/stretchr/testify/require"
"github.com/dgraph-io/badger/v4/pb"
)
func TestGet(t *testing.T) {
trie := NewTrie()
trie.Add([]byte("hello"), 1)
trie.Add([]byte("hello"), 3)
trie.Add([]byte("hello"), 4)
trie.Add([]byte("hel"), 20)
trie.Add([]byte("he"), 20)
trie.Add([]byte("badger"), 30)
trie.Add(nil, 10)
require.Equal(t, map[uint64]struct{}{10: {}}, trie.Get([]byte("A")))
ids := trie.Get([]byte("hel"))
require.Equal(t, 2, len(ids))
require.Equal(t, map[uint64]struct{}{10: {}, 20: {}}, ids)
ids = trie.Get([]byte("badger"))
require.Equal(t, 2, len(ids))
require.Equal(t, map[uint64]struct{}{10: {}, 30: {}}, ids)
ids = trie.Get([]byte("hello"))
require.Equal(t, 5, len(ids))
require.Equal(t, map[uint64]struct{}{10: {}, 1: {}, 3: {}, 4: {}, 20: {}}, ids)
trie.Add([]byte{}, 11)
require.Equal(t, map[uint64]struct{}{10: {}, 11: {}}, trie.Get([]byte("A")))
}
func TestTrieDelete(t *testing.T) {
trie := NewTrie()
t.Logf("Num nodes: %d", numNodes(trie.root))
require.Equal(t, 1, numNodes(trie.root))
trie.Add([]byte("hello"), 1)
trie.Add([]byte("hello"), 3)
trie.Add([]byte("hello"), 4)
trie.Add(nil, 5)
t.Logf("Num nodes: %d", numNodes(trie.root))
require.NoError(t, trie.Delete([]byte("hello"), 4))
t.Logf("Num nodes: %d", numNodes(trie.root))
require.Equal(t, map[uint64]struct{}{5: {}, 1: {}, 3: {}}, trie.Get([]byte("hello")))
require.NoError(t, trie.Delete(nil, 5))
t.Logf("Num nodes: %d", numNodes(trie.root))
require.Equal(t, map[uint64]struct{}{1: {}, 3: {}}, trie.Get([]byte("hello")))
require.NoError(t, trie.Delete([]byte("hello"), 1))
require.NoError(t, trie.Delete([]byte("hello"), 3))
require.NoError(t, trie.Delete([]byte("hello"), 4))
require.NoError(t, trie.Delete([]byte("hello"), 5))
require.NoError(t, trie.Delete([]byte("hello"), 6))
require.Equal(t, 1, numNodes(trie.root))
t.Logf("Num nodes: %d", numNodes(trie.root))
require.Equal(t, true, trie.root.isEmpty())
require.Equal(t, map[uint64]struct{}{}, trie.Get([]byte("hello")))
}
func TestParseIgnoreBytes(t *testing.T) {
out, err := parseIgnoreBytes("1")
require.NoError(t, err)
require.Equal(t, []bool{false, true}, out)
out, err = parseIgnoreBytes("0")
require.NoError(t, err)
require.Equal(t, []bool{true}, out)
out, err = parseIgnoreBytes("0, 3 - 5, 7")
require.NoError(t, err)
require.Equal(t, []bool{true, false, false, true, true, true, false, true}, out)
}
func TestPrefixMatchWithHoles(t *testing.T) {
trie := NewTrie()
add := func(prefix, ignore string, id uint64) {
m := pb.Match{
Prefix: []byte(prefix),
IgnoreBytes: ignore,
}
require.NoError(t, trie.AddMatch(m, id))
}
add("", "", 1)
add("aaaa", "", 2)
add("aaaaaa", "2-10", 3)
add("aaaaaaaaa", "0, 4 - 6, 8", 4)
get := func(k string) []uint64 {
var ids []uint64
m := trie.Get([]byte(k))
for id := range m {
ids = append(ids, id)
}
sort.Slice(ids, func(i, j int) bool {
return ids[i] < ids[j]
})
return ids
}
// Everything matches 1
require.Equal(t, []uint64{1}, get(""))
require.Equal(t, []uint64{1}, get("aax"))
// aaaaa would match 2, but not 3 because 3's length is 6.
require.Equal(t, []uint64{1, 2}, get("aaaaa"))
// aa and enough length is sufficient to match 3.
require.Equal(t, []uint64{1, 3}, get("aabbbbbbbb"))
// has differences in the right place to match 4.
require.Equal(t, []uint64{1, 4}, get("baaabbbabba"))
// Even with differences matches everything.
require.Equal(t, []uint64{1, 2, 3, 4}, get("aaaabbbabba"))
t.Logf("Num nodes: %d", numNodes(trie.root))
del := func(prefix, ignore string, id uint64) {
m := pb.Match{
Prefix: []byte(prefix),
IgnoreBytes: ignore,
}
require.NoError(t, trie.DeleteMatch(m, id))
}
del("aaaaaaaaa", "0, 4 - 6, 8", 5)
t.Logf("Num nodes: %d", numNodes(trie.root))
del("aaaaaaaaa", "0, 4 - 6, 8", 4)
t.Logf("Num nodes: %d", numNodes(trie.root))
del("aaaaaa", "2-10", 3)
t.Logf("Num nodes: %d", numNodes(trie.root))
del("aaaa", "", 2)
t.Logf("Num nodes: %d", numNodes(trie.root))
del("", "", 1)
t.Logf("Num nodes: %d", numNodes(trie.root))
del("abracadabra", "", 4)
t.Logf("Num nodes: %d", numNodes(trie.root))
require.Equal(t, 1, numNodes(trie.root))
}
================================================
FILE: txn.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"bytes"
"context"
"encoding/hex"
"errors"
"fmt"
"math"
"sort"
"strconv"
"sync"
"sync/atomic"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2/z"
)
type oracle struct {
isManaged bool // Does not change value, so no locking required.
detectConflicts bool // Determines if the txns should be checked for conflicts.
sync.Mutex // For nextTxnTs and commits.
// writeChLock lock is for ensuring that transactions go to the write
// channel in the same order as their commit timestamps.
writeChLock sync.Mutex
nextTxnTs uint64
// Used to block NewTransaction, so all previous commits are visible to a new read.
txnMark *y.WaterMark
// Either of these is used to determine which versions can be permanently
// discarded during compaction.
discardTs uint64 // Used by ManagedDB.
readMark *y.WaterMark // Used by DB.
// committedTxns contains all committed writes (contains fingerprints
// of keys written and their latest commit counter).
committedTxns []committedTxn
lastCleanupTs uint64
// closer is used to stop watermarks.
closer *z.Closer
}
type committedTxn struct {
ts uint64
// ConflictKeys Keeps track of the entries written at timestamp ts.
conflictKeys map[uint64]struct{}
}
func newOracle(opt Options) *oracle {
orc := &oracle{
isManaged: opt.managedTxns,
detectConflicts: opt.DetectConflicts,
// We're not initializing nextTxnTs and readOnlyTs. It would be done after replay in Open.
//
// WaterMarks must be 64-bit aligned for atomic package, hence we must use pointers here.
// See https://golang.org/pkg/sync/atomic/#pkg-note-BUG.
readMark: &y.WaterMark{Name: "badger.PendingReads"},
txnMark: &y.WaterMark{Name: "badger.TxnTimestamp"},
closer: z.NewCloser(2),
}
orc.readMark.Init(orc.closer)
orc.txnMark.Init(orc.closer)
return orc
}
func (o *oracle) Stop() {
o.closer.SignalAndWait()
}
func (o *oracle) readTs() uint64 {
if o.isManaged {
panic("ReadTs should not be retrieved for managed DB")
}
var readTs uint64
o.Lock()
readTs = o.nextTxnTs - 1
o.readMark.Begin(readTs)
o.Unlock()
// Wait for all txns which have no conflicts, have been assigned a commit
// timestamp and are going through the write to value log and LSM tree
// process. Not waiting here could mean that some txns which have been
// committed would not be read.
y.Check(o.txnMark.WaitForMark(context.Background(), readTs))
return readTs
}
func (o *oracle) nextTs() uint64 {
o.Lock()
defer o.Unlock()
return o.nextTxnTs
}
func (o *oracle) incrementNextTs() {
o.Lock()
defer o.Unlock()
o.nextTxnTs++
}
// Any deleted or invalid versions at or below ts would be discarded during
// compaction to reclaim disk space in LSM tree and thence value log.
func (o *oracle) setDiscardTs(ts uint64) {
o.Lock()
defer o.Unlock()
o.discardTs = ts
o.cleanupCommittedTransactions()
}
func (o *oracle) discardAtOrBelow() uint64 {
if o.isManaged {
o.Lock()
defer o.Unlock()
return o.discardTs
}
return o.readMark.DoneUntil()
}
// hasConflict must be called while having a lock.
func (o *oracle) hasConflict(txn *Txn) bool {
if len(txn.reads) == 0 {
return false
}
for _, committedTxn := range o.committedTxns {
// If the committedTxn.ts is less than txn.readTs that implies that the
// committedTxn finished before the current transaction started.
// We don't need to check for conflict in that case.
// This change assumes linearizability. Lack of linearizability could
// cause the read ts of a new txn to be lower than the commit ts of
// a txn before it (@mrjn).
if committedTxn.ts <= txn.readTs {
continue
}
for _, ro := range txn.reads {
if _, has := committedTxn.conflictKeys[ro]; has {
return true
}
}
}
return false
}
func (o *oracle) newCommitTs(txn *Txn) (uint64, bool) {
o.Lock()
defer o.Unlock()
if o.hasConflict(txn) {
return 0, true
}
var ts uint64
if !o.isManaged {
o.doneRead(txn)
o.cleanupCommittedTransactions()
// This is the general case, when user doesn't specify the read and commit ts.
ts = o.nextTxnTs
o.nextTxnTs++
o.txnMark.Begin(ts)
} else {
// If commitTs is set, use it instead.
ts = txn.commitTs
}
y.AssertTrue(ts >= o.lastCleanupTs)
if o.detectConflicts {
// We should ensure that txns are not added to o.committedTxns slice when
// conflict detection is disabled otherwise this slice would keep growing.
o.committedTxns = append(o.committedTxns, committedTxn{
ts: ts,
conflictKeys: txn.conflictKeys,
})
}
return ts, false
}
func (o *oracle) doneRead(txn *Txn) {
if !txn.doneRead {
txn.doneRead = true
o.readMark.Done(txn.readTs)
}
}
func (o *oracle) cleanupCommittedTransactions() { // Must be called under o.Lock
if !o.detectConflicts {
// When detectConflicts is set to false, we do not store any
// committedTxns and so there's nothing to clean up.
return
}
// Same logic as discardAtOrBelow but unlocked
var maxReadTs uint64
if o.isManaged {
maxReadTs = o.discardTs
} else {
maxReadTs = o.readMark.DoneUntil()
}
y.AssertTrue(maxReadTs >= o.lastCleanupTs)
// do not run clean up if the maxReadTs (read timestamp of the
// oldest transaction that is still in flight) has not increased
if maxReadTs == o.lastCleanupTs {
return
}
o.lastCleanupTs = maxReadTs
tmp := o.committedTxns[:0]
for _, txn := range o.committedTxns {
if txn.ts <= maxReadTs {
continue
}
tmp = append(tmp, txn)
}
o.committedTxns = tmp
}
func (o *oracle) doneCommit(cts uint64) {
if o.isManaged {
// No need to update anything.
return
}
o.txnMark.Done(cts)
}
// Txn represents a Badger transaction.
type Txn struct {
readTs uint64
commitTs uint64
size int64
count int64
db *DB
reads []uint64 // contains fingerprints of keys read.
// contains fingerprints of keys written. This is used for conflict detection.
conflictKeys map[uint64]struct{}
readsLock sync.Mutex // guards the reads slice. See addReadKey.
pendingWrites map[string]*Entry // cache stores any writes done by txn.
duplicateWrites []*Entry // Used in managed mode to store duplicate entries.
numIterators atomic.Int32
discarded bool
doneRead bool
update bool // update is used to conditionally keep track of reads.
}
type pendingWritesIterator struct {
entries []*Entry
nextIdx int
readTs uint64
reversed bool
}
func (pi *pendingWritesIterator) Next() {
pi.nextIdx++
}
func (pi *pendingWritesIterator) Rewind() {
pi.nextIdx = 0
}
func (pi *pendingWritesIterator) Seek(key []byte) {
key = y.ParseKey(key)
pi.nextIdx = sort.Search(len(pi.entries), func(idx int) bool {
cmp := bytes.Compare(pi.entries[idx].Key, key)
if !pi.reversed {
return cmp >= 0
}
return cmp <= 0
})
}
func (pi *pendingWritesIterator) Key() []byte {
y.AssertTrue(pi.Valid())
entry := pi.entries[pi.nextIdx]
return y.KeyWithTs(entry.Key, pi.readTs)
}
func (pi *pendingWritesIterator) Value() y.ValueStruct {
y.AssertTrue(pi.Valid())
entry := pi.entries[pi.nextIdx]
return y.ValueStruct{
Value: entry.Value,
Meta: entry.meta,
UserMeta: entry.UserMeta,
ExpiresAt: entry.ExpiresAt,
Version: pi.readTs,
}
}
func (pi *pendingWritesIterator) Valid() bool {
return pi.nextIdx < len(pi.entries)
}
func (pi *pendingWritesIterator) Close() error {
return nil
}
func (txn *Txn) newPendingWritesIterator(reversed bool) *pendingWritesIterator {
if !txn.update || len(txn.pendingWrites) == 0 {
return nil
}
entries := make([]*Entry, 0, len(txn.pendingWrites))
for _, e := range txn.pendingWrites {
entries = append(entries, e)
}
// Number of pending writes per transaction shouldn't be too big in general.
sort.Slice(entries, func(i, j int) bool {
cmp := bytes.Compare(entries[i].Key, entries[j].Key)
if !reversed {
return cmp < 0
}
return cmp > 0
})
return &pendingWritesIterator{
readTs: txn.readTs,
entries: entries,
reversed: reversed,
}
}
func (txn *Txn) checkSize(e *Entry) error {
count := txn.count + 1
// Extra bytes for the version in key.
size := txn.size + e.estimateSizeAndSetThreshold(txn.db.valueThreshold()) + 10
if count >= txn.db.opt.maxBatchCount || size >= txn.db.opt.maxBatchSize {
return ErrTxnTooBig
}
txn.count, txn.size = count, size
return nil
}
func exceedsSize(prefix string, max int64, key []byte) error {
return fmt.Errorf("%s with size %d exceeded %d limit. %s:\n%s",
prefix, len(key), max, prefix, hex.Dump(key[:1<<10]))
}
func (txn *Txn) modify(e *Entry) error {
const maxKeySize = 65000
switch {
case !txn.update:
return ErrReadOnlyTxn
case txn.discarded:
return ErrDiscardedTxn
case len(e.Key) == 0:
return ErrEmptyKey
case bytes.HasPrefix(e.Key, badgerPrefix):
return ErrInvalidKey
case len(e.Key) > maxKeySize:
// Key length can't be more than uint16, as determined by table::header. To
// keep things safe and allow badger move prefix and a timestamp suffix, let's
// cut it down to 65000, instead of using 65536.
return exceedsSize("Key", maxKeySize, e.Key)
case int64(len(e.Value)) > txn.db.opt.ValueLogFileSize:
return exceedsSize("Value", txn.db.opt.ValueLogFileSize, e.Value)
case txn.db.opt.InMemory && int64(len(e.Value)) > txn.db.valueThreshold():
return exceedsSize("Value", txn.db.valueThreshold(), e.Value)
}
if err := txn.db.isBanned(e.Key); err != nil {
return err
}
if err := txn.checkSize(e); err != nil {
return err
}
// The txn.conflictKeys is used for conflict detection. If conflict detection
// is disabled, we don't need to store key hashes in this map.
if txn.db.opt.DetectConflicts {
fp := z.MemHash(e.Key) // Avoid dealing with byte arrays.
txn.conflictKeys[fp] = struct{}{}
}
// If a duplicate entry was inserted in managed mode, move it to the duplicate writes slice.
// Add the entry to duplicateWrites only if both the entries have different versions. For
// same versions, we will overwrite the existing entry.
if oldEntry, ok := txn.pendingWrites[string(e.Key)]; ok && oldEntry.version != e.version {
txn.duplicateWrites = append(txn.duplicateWrites, oldEntry)
}
txn.pendingWrites[string(e.Key)] = e
return nil
}
// Set adds a key-value pair to the database.
// It will return ErrReadOnlyTxn if update flag was set to false when creating the transaction.
//
// The current transaction keeps a reference to the key and val byte slice
// arguments. Users must not modify key and val until the end of the transaction.
func (txn *Txn) Set(key, val []byte) error {
return txn.SetEntry(NewEntry(key, val))
}
// SetEntry takes an Entry struct and adds the key-value pair in the struct,
// along with other metadata to the database.
//
// The current transaction keeps a reference to the entry passed in argument.
// Users must not modify the entry until the end of the transaction.
func (txn *Txn) SetEntry(e *Entry) error {
return txn.modify(e)
}
// Delete deletes a key.
//
// This is done by adding a delete marker for the key at commit timestamp. Any
// reads happening before this timestamp would be unaffected. Any reads after
// this commit would see the deletion.
//
// The current transaction keeps a reference to the key byte slice argument.
// Users must not modify the key until the end of the transaction.
func (txn *Txn) Delete(key []byte) error {
e := &Entry{
Key: key,
meta: bitDelete,
}
return txn.modify(e)
}
// Get looks for key and returns corresponding Item.
// If key is not found, ErrKeyNotFound is returned.
func (txn *Txn) Get(key []byte) (item *Item, rerr error) {
if len(key) == 0 {
return nil, ErrEmptyKey
} else if txn.discarded {
return nil, ErrDiscardedTxn
}
if err := txn.db.isBanned(key); err != nil {
return nil, err
}
item = new(Item)
if txn.update {
if e, has := txn.pendingWrites[string(key)]; has && bytes.Equal(key, e.Key) {
if isDeletedOrExpired(e.meta, e.ExpiresAt) {
return nil, ErrKeyNotFound
}
// Fulfill from cache.
item.meta = e.meta
item.val = e.Value
item.userMeta = e.UserMeta
item.key = key
item.status = prefetched
item.version = txn.readTs
item.expiresAt = e.ExpiresAt
// We probably don't need to set db on item here.
return item, nil
}
// Only track reads if this is update txn. No need to track read if txn serviced it
// internally.
txn.addReadKey(key)
}
seek := y.KeyWithTs(key, txn.readTs)
vs, err := txn.db.get(seek)
if err != nil {
return nil, y.Wrapf(err, "DB::Get key: %q", key)
}
if vs.Value == nil && vs.Meta == 0 {
return nil, ErrKeyNotFound
}
if isDeletedOrExpired(vs.Meta, vs.ExpiresAt) {
return nil, ErrKeyNotFound
}
item.key = key
item.version = vs.Version
item.meta = vs.Meta
item.userMeta = vs.UserMeta
item.vptr = y.SafeCopy(item.vptr, vs.Value)
item.txn = txn
item.expiresAt = vs.ExpiresAt
return item, nil
}
func (txn *Txn) addReadKey(key []byte) {
if txn.update {
fp := z.MemHash(key)
// Because of the possibility of multiple iterators it is now possible
// for multiple threads within a read-write transaction to read keys at
// the same time. The reads slice is not currently thread-safe and
// needs to be locked whenever we mark a key as read.
txn.readsLock.Lock()
txn.reads = append(txn.reads, fp)
txn.readsLock.Unlock()
}
}
// Discard discards a created transaction. This method is very important and must be called. Commit
// method calls this internally, however, calling this multiple times doesn't cause any issues. So,
// this can safely be called via a defer right when transaction is created.
//
// NOTE: If any operations are run on a discarded transaction, ErrDiscardedTxn is returned.
func (txn *Txn) Discard() {
if txn.discarded { // Avoid a re-run.
return
}
if txn.numIterators.Load() > 0 {
panic("Unclosed iterator at time of Txn.Discard.")
}
txn.discarded = true
if !txn.db.orc.isManaged {
txn.db.orc.doneRead(txn)
}
}
func (txn *Txn) commitAndSend() (func() error, error) {
orc := txn.db.orc
// Ensure that the order in which we get the commit timestamp is the same as
// the order in which we push these updates to the write channel. So, we
// acquire a writeChLock before getting a commit timestamp, and only release
// it after pushing the entries to it.
orc.writeChLock.Lock()
defer orc.writeChLock.Unlock()
commitTs, conflict := orc.newCommitTs(txn)
if conflict {
return nil, ErrConflict
}
keepTogether := true
setVersion := func(e *Entry) {
if e.version == 0 {
e.version = commitTs
} else {
keepTogether = false
}
}
for _, e := range txn.pendingWrites {
setVersion(e)
}
// The duplicateWrites slice will be non-empty only if there are duplicate
// entries with different versions.
for _, e := range txn.duplicateWrites {
setVersion(e)
}
entries := make([]*Entry, 0, len(txn.pendingWrites)+len(txn.duplicateWrites)+1)
processEntry := func(e *Entry) {
// Suffix the keys with commit ts, so the key versions are sorted in
// descending order of commit timestamp.
e.Key = y.KeyWithTs(e.Key, e.version)
// Add bitTxn only if these entries are part of a transaction. We
// support SetEntryAt(..) in managed mode which means a single
// transaction can have entries with different timestamps. If entries
// in a single transaction have different timestamps, we don't add the
// transaction markers.
if keepTogether {
e.meta |= bitTxn
}
entries = append(entries, e)
}
// The following debug information is what led to determining the cause of
// bank txn violation bug, and it took a whole bunch of effort to narrow it
// down to here. So, keep this around for at least a couple of months.
// var b strings.Builder
// fmt.Fprintf(&b, "Read: %d. Commit: %d. reads: %v. writes: %v. Keys: ",
// txn.readTs, commitTs, txn.reads, txn.conflictKeys)
for _, e := range txn.pendingWrites {
processEntry(e)
}
for _, e := range txn.duplicateWrites {
processEntry(e)
}
if keepTogether {
// CommitTs should not be zero if we're inserting transaction markers.
y.AssertTrue(commitTs != 0)
e := &Entry{
Key: y.KeyWithTs(txnKey, commitTs),
Value: []byte(strconv.FormatUint(commitTs, 10)),
meta: bitFinTxn,
}
entries = append(entries, e)
}
req, err := txn.db.sendToWriteCh(entries)
if err != nil {
orc.doneCommit(commitTs)
return nil, err
}
ret := func() error {
err := req.Wait()
// Wait before marking commitTs as done.
// We can't defer doneCommit above, because it is being called from a
// callback here.
orc.doneCommit(commitTs)
return err
}
return ret, nil
}
func (txn *Txn) commitPrecheck() error {
if txn.discarded {
return errors.New("Trying to commit a discarded txn")
}
keepTogether := true
for _, e := range txn.pendingWrites {
if e.version != 0 {
keepTogether = false
}
}
// If keepTogether is True, it implies transaction markers will be added.
// In that case, commitTs should not be never be zero. This might happen if
// someone uses txn.Commit instead of txn.CommitAt in managed mode. This
// should happen only in managed mode. In normal mode, keepTogether will
// always be true.
if keepTogether && txn.db.opt.managedTxns && txn.commitTs == 0 {
return errors.New("CommitTs cannot be zero. Please use commitAt instead")
}
return nil
}
// Commit commits the transaction, following these steps:
//
// 1. If there are no writes, return immediately.
//
// 2. Check if read rows were updated since txn started. If so, return ErrConflict.
//
// 3. If no conflict, generate a commit timestamp and update written rows' commit ts.
//
// 4. Batch up all writes, write them to value log and LSM tree.
//
// 5. If callback is provided, Badger will return immediately after checking
// for conflicts. Writes to the database will happen in the background. If
// there is a conflict, an error will be returned and the callback will not
// run. If there are no conflicts, the callback will be called in the
// background upon successful completion of writes or any error during write.
//
// If error is nil, the transaction is successfully committed. In case of a non-nil error, the LSM
// tree won't be updated, so there's no need for any rollback.
func (txn *Txn) Commit() error {
// txn.conflictKeys can be zero if conflict detection is turned off. So we
// should check txn.pendingWrites.
if len(txn.pendingWrites) == 0 {
// Discard the transaction so that the read is marked done.
txn.Discard()
return nil
}
// Precheck before discarding txn.
if err := txn.commitPrecheck(); err != nil {
return err
}
defer txn.Discard()
txnCb, err := txn.commitAndSend()
if err != nil {
return err
}
// If batchSet failed, LSM would not have been updated. So, no need to rollback anything.
// TODO: What if some of the txns successfully make it to value log, but others fail.
// Nothing gets updated to LSM, until a restart happens.
return txnCb()
}
type txnCb struct {
commit func() error
user func(error)
err error
}
func runTxnCallback(cb *txnCb) {
switch {
case cb == nil:
panic("txn callback is nil")
case cb.user == nil:
panic("Must have caught a nil callback for txn.CommitWith")
case cb.err != nil:
cb.user(cb.err)
case cb.commit != nil:
err := cb.commit()
cb.user(err)
default:
cb.user(nil)
}
}
// CommitWith acts like Commit, but takes a callback, which gets run via a
// goroutine to avoid blocking this function. The callback is guaranteed to run,
// so it is safe to increment sync.WaitGroup before calling CommitWith, and
// decrementing it in the callback; to block until all callbacks are run.
func (txn *Txn) CommitWith(cb func(error)) {
if cb == nil {
panic("Nil callback provided to CommitWith")
}
if len(txn.pendingWrites) == 0 {
// Do not run these callbacks from here, because the CommitWith and the
// callback might be acquiring the same locks. Instead run the callback
// from another goroutine.
go runTxnCallback(&txnCb{user: cb, err: nil})
// Discard the transaction so that the read is marked done.
txn.Discard()
return
}
// Precheck before discarding txn.
if err := txn.commitPrecheck(); err != nil {
cb(err)
return
}
defer txn.Discard()
commitCb, err := txn.commitAndSend()
if err != nil {
go runTxnCallback(&txnCb{user: cb, err: err})
return
}
go runTxnCallback(&txnCb{user: cb, commit: commitCb})
}
// ReadTs returns the read timestamp of the transaction.
func (txn *Txn) ReadTs() uint64 {
return txn.readTs
}
// NewTransaction creates a new transaction. Badger supports concurrent execution of transactions,
// providing serializable snapshot isolation, avoiding write skews. Badger achieves this by tracking
// the keys read and at Commit time, ensuring that these read keys weren't concurrently modified by
// another transaction.
//
// For read-only transactions, set update to false. In this mode, we don't track the rows read for
// any changes. Thus, any long running iterations done in this mode wouldn't pay this overhead.
//
// Running transactions concurrently is OK. However, a transaction itself isn't thread safe, and
// should only be run serially. It doesn't matter if a transaction is created by one goroutine and
// passed down to other, as long as the Txn APIs are called serially.
//
// When you create a new transaction, it is absolutely essential to call
// Discard(). This should be done irrespective of what the update param is set
// to. Commit API internally runs Discard, but running it twice wouldn't cause
// any issues.
//
// txn := db.NewTransaction(false)
// defer txn.Discard()
// // Call various APIs.
func (db *DB) NewTransaction(update bool) *Txn {
return db.newTransaction(update, false)
}
func (db *DB) newTransaction(update, isManaged bool) *Txn {
if db.opt.ReadOnly && update {
// DB is read-only, force read-only transaction.
update = false
}
txn := &Txn{
update: update,
db: db,
count: 1, // One extra entry for BitFin.
size: int64(len(txnKey) + 10), // Some buffer for the extra entry.
}
if update {
if db.opt.DetectConflicts {
txn.conflictKeys = make(map[uint64]struct{})
}
txn.pendingWrites = make(map[string]*Entry)
}
if !isManaged {
txn.readTs = db.orc.readTs()
}
return txn
}
// View executes a function creating and managing a read-only transaction for the user. Error
// returned by the function is relayed by the View method.
// If View is used with managed transactions, it would assume a read timestamp of MaxUint64.
func (db *DB) View(fn func(txn *Txn) error) error {
if db.IsClosed() {
return ErrDBClosed
}
var txn *Txn
if db.opt.managedTxns {
txn = db.NewTransactionAt(math.MaxUint64, false)
} else {
txn = db.NewTransaction(false)
}
defer txn.Discard()
return fn(txn)
}
// Update executes a function, creating and managing a read-write transaction
// for the user. Error returned by the function is relayed by the Update method.
// Update cannot be used with managed transactions.
func (db *DB) Update(fn func(txn *Txn) error) error {
if db.IsClosed() {
return ErrDBClosed
}
if db.opt.managedTxns {
panic("Update can only be used with managedDB=false.")
}
txn := db.NewTransaction(true)
defer txn.Discard()
if err := fn(txn); err != nil {
return err
}
return txn.Commit()
}
================================================
FILE: txn_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"fmt"
"math/rand"
"os"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2/z"
)
func TestTxnSimple(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
txn := db.NewTransaction(true)
for i := 0; i < 10; i++ {
k := []byte(fmt.Sprintf("key=%d", i))
v := []byte(fmt.Sprintf("val=%d", i))
require.NoError(t, txn.SetEntry(NewEntry(k, v)))
}
item, err := txn.Get([]byte("key=8"))
require.NoError(t, err)
require.NoError(t, item.Value(func(val []byte) error {
require.Equal(t, []byte("val=8"), val)
return nil
}))
require.Panics(t, func() { _ = txn.CommitAt(100, nil) })
require.NoError(t, txn.Commit())
})
}
func TestTxnReadAfterWrite(t *testing.T) {
test := func(t *testing.T, db *DB) {
var wg sync.WaitGroup
N := 100
wg.Add(N)
for i := 0; i < N; i++ {
go func(i int) {
defer wg.Done()
key := []byte(fmt.Sprintf("key%d", i))
err := db.Update(func(tx *Txn) error {
return tx.SetEntry(NewEntry(key, key))
})
require.NoError(t, err)
err = db.View(func(tx *Txn) error {
item, err := tx.Get(key)
require.NoError(t, err)
val, err := item.ValueCopy(nil)
require.NoError(t, err)
require.Equal(t, val, key)
return nil
})
require.NoError(t, err)
}(i)
}
wg.Wait()
}
t.Run("disk mode", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
test(t, db)
})
})
t.Run("InMemory mode", func(t *testing.T) {
opt := getTestOptions("")
opt.InMemory = true
db, err := Open(opt)
require.NoError(t, err)
test(t, db)
require.NoError(t, db.Close())
})
}
func TestTxnCommitAsync(t *testing.T) {
key := func(i int) []byte {
return []byte(fmt.Sprintf("key=%d", i))
}
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
txn := db.NewTransaction(true)
for i := 0; i < 40; i++ {
err := txn.SetEntry(NewEntry(key(i), []byte(strconv.Itoa(100))))
require.NoError(t, err)
}
require.NoError(t, txn.Commit())
txn.Discard()
closer := z.NewCloser(1)
go func() {
defer closer.Done()
for {
select {
case <-closer.HasBeenClosed():
return
default:
}
// Keep checking balance variant
txn := db.NewTransaction(false)
totalBalance := 0
for i := 0; i < 40; i++ {
item, err := txn.Get(key(i))
require.NoError(t, err)
val, err := item.ValueCopy(nil)
require.NoError(t, err)
bal, err := strconv.Atoi(string(val))
require.NoError(t, err)
totalBalance += bal
}
require.Equal(t, totalBalance, 4000)
txn.Discard()
}
}()
var wg sync.WaitGroup
wg.Add(100)
for i := 0; i < 100; i++ {
go func() {
txn := db.NewTransaction(true)
delta := rand.Intn(100)
for i := 0; i < 20; i++ {
err := txn.SetEntry(NewEntry(key(i), []byte(strconv.Itoa(100-delta))))
require.NoError(t, err)
}
for i := 20; i < 40; i++ {
err := txn.SetEntry(NewEntry(key(i), []byte(strconv.Itoa(100+delta))))
require.NoError(t, err)
}
// We are only doing writes, so there won't be any conflicts.
txn.CommitWith(func(err error) {})
txn.Discard()
wg.Done()
}()
}
wg.Wait()
closer.SignalAndWait()
time.Sleep(time.Millisecond * 10) // allow goroutine to complete.
})
}
func TestTxnVersions(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
k := []byte("key")
for i := 1; i < 10; i++ {
txn := db.NewTransaction(true)
require.NoError(t, txn.SetEntry(NewEntry(k, []byte(fmt.Sprintf("valversion=%d", i)))))
require.NoError(t, txn.Commit())
require.Equal(t, uint64(i), db.orc.readTs())
}
checkIterator := func(itr *Iterator, i int) {
defer itr.Close()
count := 0
for itr.Rewind(); itr.Valid(); itr.Next() {
item := itr.Item()
require.Equal(t, k, item.Key())
val, err := item.ValueCopy(nil)
require.NoError(t, err)
exp := fmt.Sprintf("valversion=%d", i)
require.Equal(t, exp, string(val), "i=%d", i)
count++
}
require.Equal(t, 1, count, "i=%d", i) // Should only loop once.
}
checkAllVersions := func(itr *Iterator, i int) {
var version uint64
if itr.opt.Reverse {
version = 1
} else {
version = uint64(i)
}
count := 0
for itr.Rewind(); itr.Valid(); itr.Next() {
item := itr.Item()
require.Equal(t, k, item.Key())
require.Equal(t, version, item.Version())
val, err := item.ValueCopy(nil)
require.NoError(t, err)
exp := fmt.Sprintf("valversion=%d", version)
require.Equal(t, exp, string(val), "v=%d", version)
count++
if itr.opt.Reverse {
version++
} else {
version--
}
}
require.Equal(t, i, count, "i=%d", i) // Should loop as many times as i.
}
for i := 1; i < 10; i++ {
txn := db.NewTransaction(true)
txn.readTs = uint64(i) // Read version at i.
item, err := txn.Get(k)
require.NoError(t, err)
val, err := item.ValueCopy(nil)
require.NoError(t, err)
require.Equal(t, []byte(fmt.Sprintf("valversion=%d", i)), val,
"Expected versions to match up at i=%d", i)
// Try retrieving the latest version forward and reverse.
itr := txn.NewIterator(DefaultIteratorOptions)
checkIterator(itr, i)
opt := DefaultIteratorOptions
opt.Reverse = true
itr = txn.NewIterator(opt)
checkIterator(itr, i)
// Now try retrieving all versions forward and reverse.
opt = DefaultIteratorOptions
opt.AllVersions = true
itr = txn.NewIterator(opt)
checkAllVersions(itr, i)
itr.Close()
opt = DefaultIteratorOptions
opt.AllVersions = true
opt.Reverse = true
itr = txn.NewIterator(opt)
checkAllVersions(itr, i)
itr.Close()
txn.Discard()
}
txn := db.NewTransaction(true)
defer txn.Discard()
item, err := txn.Get(k)
require.NoError(t, err)
val, err := item.ValueCopy(nil)
require.NoError(t, err)
require.Equal(t, []byte("valversion=9"), val)
})
}
func TestTxnWriteSkew(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
// Accounts
ax := []byte("x")
ay := []byte("y")
// Set balance to $100 in each account.
txn := db.NewTransaction(true)
defer txn.Discard()
val := []byte(strconv.Itoa(100))
require.NoError(t, txn.SetEntry(NewEntry(ax, val)))
require.NoError(t, txn.SetEntry(NewEntry(ay, val)))
require.NoError(t, txn.Commit())
require.Equal(t, uint64(1), db.orc.readTs())
getBal := func(txn *Txn, key []byte) (bal int) {
item, err := txn.Get(key)
require.NoError(t, err)
val, err := item.ValueCopy(nil)
require.NoError(t, err)
bal, err = strconv.Atoi(string(val))
require.NoError(t, err)
return bal
}
// Start two transactions, each would read both accounts and deduct from one account.
txn1 := db.NewTransaction(true)
sum := getBal(txn1, ax)
sum += getBal(txn1, ay)
require.Equal(t, 200, sum)
require.NoError(t, txn1.SetEntry(NewEntry(ax, []byte("0")))) // Deduct 100 from ax.
// Let's read this back.
sum = getBal(txn1, ax)
require.Equal(t, 0, sum)
sum += getBal(txn1, ay)
require.Equal(t, 100, sum)
// Don't commit yet.
txn2 := db.NewTransaction(true)
sum = getBal(txn2, ax)
sum += getBal(txn2, ay)
require.Equal(t, 200, sum)
require.NoError(t, txn2.SetEntry(NewEntry(ay, []byte("0")))) // Deduct 100 from ay.
// Let's read this back.
sum = getBal(txn2, ax)
require.Equal(t, 100, sum)
sum += getBal(txn2, ay)
require.Equal(t, 100, sum)
// Commit both now.
require.NoError(t, txn1.Commit())
require.Error(t, txn2.Commit()) // This should fail.
require.Equal(t, uint64(2), db.orc.readTs())
})
}
// a3, a2, b4 (del), b3, c2, c1
// Read at ts=4 -> a3, c2
// Read at ts=4(Uncommitted) -> a3, b4
// Read at ts=3 -> a3, b3, c2
// Read at ts=2 -> a2, c2
// Read at ts=1 -> c1
func TestTxnIterationEdgeCase(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
ka := []byte("a")
kb := []byte("b")
kc := []byte("c")
// c1
txn := db.NewTransaction(true)
require.NoError(t, txn.SetEntry(NewEntry(kc, []byte("c1"))))
require.NoError(t, txn.Commit())
require.Equal(t, uint64(1), db.orc.readTs())
// a2, c2
txn = db.NewTransaction(true)
require.NoError(t, txn.SetEntry(NewEntry(ka, []byte("a2"))))
require.NoError(t, txn.SetEntry(NewEntry(kc, []byte("c2"))))
require.NoError(t, txn.Commit())
require.Equal(t, uint64(2), db.orc.readTs())
// b3
txn = db.NewTransaction(true)
require.NoError(t, txn.SetEntry(NewEntry(ka, []byte("a3"))))
require.NoError(t, txn.SetEntry(NewEntry(kb, []byte("b3"))))
require.NoError(t, txn.Commit())
require.Equal(t, uint64(3), db.orc.readTs())
// b4, c4(del) (Uncommitted)
txn4 := db.NewTransaction(true)
require.NoError(t, txn4.SetEntry(NewEntry(kb, []byte("b4"))))
require.NoError(t, txn4.Delete(kc))
require.Equal(t, uint64(3), db.orc.readTs())
// b4 (del)
txn = db.NewTransaction(true)
require.NoError(t, txn.Delete(kb))
require.NoError(t, txn.Commit())
require.Equal(t, uint64(4), db.orc.readTs())
checkIterator := func(itr *Iterator, expected []string) {
defer itr.Close()
var i int
for itr.Rewind(); itr.Valid(); itr.Next() {
item := itr.Item()
val, err := item.ValueCopy(nil)
require.NoError(t, err)
require.Equal(t, expected[i], string(val), "readts=%d", itr.readTs)
i++
}
require.Equal(t, len(expected), i)
}
txn = db.NewTransaction(true)
defer txn.Discard()
itr := txn.NewIterator(DefaultIteratorOptions)
itr5 := txn4.NewIterator(DefaultIteratorOptions)
checkIterator(itr, []string{"a3", "c2"})
checkIterator(itr5, []string{"a3", "b4"})
rev := DefaultIteratorOptions
rev.Reverse = true
itr = txn.NewIterator(rev)
itr5 = txn4.NewIterator(rev)
checkIterator(itr, []string{"c2", "a3"})
checkIterator(itr5, []string{"b4", "a3"})
txn.readTs = 3
itr = txn.NewIterator(DefaultIteratorOptions)
checkIterator(itr, []string{"a3", "b3", "c2"})
itr = txn.NewIterator(rev)
checkIterator(itr, []string{"c2", "b3", "a3"})
txn.readTs = 2
itr = txn.NewIterator(DefaultIteratorOptions)
checkIterator(itr, []string{"a2", "c2"})
itr = txn.NewIterator(rev)
checkIterator(itr, []string{"c2", "a2"})
txn.readTs = 1
itr = txn.NewIterator(DefaultIteratorOptions)
checkIterator(itr, []string{"c1"})
itr = txn.NewIterator(rev)
checkIterator(itr, []string{"c1"})
})
}
// a2, a3, b4 (del), b3, c2, c1
// Read at ts=4 -> a3, c2
// Read at ts=3 -> a3, b3, c2
// Read at ts=2 -> a2, c2
// Read at ts=1 -> c1
func TestTxnIterationEdgeCase2(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
ka := []byte("a")
kb := []byte("aa")
kc := []byte("aaa")
// c1
txn := db.NewTransaction(true)
require.NoError(t, txn.SetEntry(NewEntry(kc, []byte("c1"))))
require.NoError(t, txn.Commit())
require.Equal(t, uint64(1), db.orc.readTs())
// a2, c2
txn = db.NewTransaction(true)
require.NoError(t, txn.SetEntry(NewEntry(ka, []byte("a2"))))
require.NoError(t, txn.SetEntry(NewEntry(kc, []byte("c2"))))
require.NoError(t, txn.Commit())
require.Equal(t, uint64(2), db.orc.readTs())
// b3
txn = db.NewTransaction(true)
require.NoError(t, txn.SetEntry(NewEntry(ka, []byte("a3"))))
require.NoError(t, txn.SetEntry(NewEntry(kb, []byte("b3"))))
require.NoError(t, txn.Commit())
require.Equal(t, uint64(3), db.orc.readTs())
// b4 (del)
txn = db.NewTransaction(true)
require.NoError(t, txn.Delete(kb))
require.NoError(t, txn.Commit())
require.Equal(t, uint64(4), db.orc.readTs())
checkIterator := func(itr *Iterator, expected []string) {
defer itr.Close()
var i int
for itr.Rewind(); itr.Valid(); itr.Next() {
item := itr.Item()
val, err := item.ValueCopy(nil)
require.NoError(t, err)
require.Equal(t, expected[i], string(val), "readts=%d", itr.readTs)
i++
}
require.Equal(t, len(expected), i)
}
txn = db.NewTransaction(true)
defer txn.Discard()
rev := DefaultIteratorOptions
rev.Reverse = true
itr := txn.NewIterator(DefaultIteratorOptions)
checkIterator(itr, []string{"a3", "c2"})
itr = txn.NewIterator(rev)
checkIterator(itr, []string{"c2", "a3"})
txn.readTs = 5
itr = txn.NewIterator(DefaultIteratorOptions)
itr.Seek(ka)
require.True(t, itr.Valid())
require.Equal(t, itr.item.Key(), ka)
itr.Seek(kc)
require.True(t, itr.Valid())
require.Equal(t, itr.item.Key(), kc)
itr.Close()
itr = txn.NewIterator(rev)
itr.Seek(ka)
require.True(t, itr.Valid())
require.Equal(t, itr.item.Key(), ka)
itr.Seek(kc)
require.True(t, itr.Valid())
require.Equal(t, itr.item.Key(), kc)
itr.Close()
txn.readTs = 3
itr = txn.NewIterator(DefaultIteratorOptions)
checkIterator(itr, []string{"a3", "b3", "c2"})
itr = txn.NewIterator(rev)
checkIterator(itr, []string{"c2", "b3", "a3"})
txn.readTs = 2
itr = txn.NewIterator(DefaultIteratorOptions)
checkIterator(itr, []string{"a2", "c2"})
itr = txn.NewIterator(rev)
checkIterator(itr, []string{"c2", "a2"})
txn.readTs = 1
itr = txn.NewIterator(DefaultIteratorOptions)
checkIterator(itr, []string{"c1"})
itr = txn.NewIterator(rev)
checkIterator(itr, []string{"c1"})
})
}
func TestTxnIterationEdgeCase3(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
kb := []byte("abc")
kc := []byte("acd")
kd := []byte("ade")
// c1
txn := db.NewTransaction(true)
require.NoError(t, txn.SetEntry(NewEntry(kc, []byte("c1"))))
require.NoError(t, txn.Commit())
require.Equal(t, uint64(1), db.orc.readTs())
// b2
txn = db.NewTransaction(true)
require.NoError(t, txn.SetEntry(NewEntry(kb, []byte("b2"))))
require.NoError(t, txn.Commit())
require.Equal(t, uint64(2), db.orc.readTs())
txn2 := db.NewTransaction(true)
require.NoError(t, txn2.SetEntry(NewEntry(kd, []byte("d2"))))
require.NoError(t, txn2.Delete(kc))
txn = db.NewTransaction(true)
defer txn.Discard()
rev := DefaultIteratorOptions
rev.Reverse = true
itr := txn.NewIterator(DefaultIteratorOptions)
itr.Seek([]byte("ab"))
require.True(t, itr.Valid())
require.Equal(t, itr.item.Key(), kb)
itr.Seek([]byte("ac"))
require.True(t, itr.Valid())
require.Equal(t, itr.item.Key(), kc)
itr.Seek(nil)
require.True(t, itr.Valid())
require.Equal(t, itr.item.Key(), kb)
itr.Seek([]byte("ac"))
itr.Rewind()
itr.Seek(nil)
require.True(t, itr.Valid())
require.Equal(t, itr.item.Key(), kb)
itr.Seek([]byte("ac"))
require.True(t, itr.Valid())
require.Equal(t, itr.item.Key(), kc)
itr.Close()
// Keys: "abc", "ade"
// Read pending writes.
itr = txn2.NewIterator(DefaultIteratorOptions)
itr.Seek([]byte("ab"))
require.True(t, itr.Valid())
require.Equal(t, itr.item.Key(), kb)
itr.Seek([]byte("ac"))
require.True(t, itr.Valid())
require.Equal(t, itr.item.Key(), kd)
itr.Seek(nil)
require.True(t, itr.Valid())
require.Equal(t, itr.item.Key(), kb)
itr.Seek([]byte("ac"))
itr.Rewind()
itr.Seek(nil)
require.True(t, itr.Valid())
require.Equal(t, itr.item.Key(), kb)
itr.Seek([]byte("ad"))
require.True(t, itr.Valid())
require.Equal(t, itr.item.Key(), kd)
itr.Close()
itr = txn.NewIterator(rev)
itr.Seek([]byte("ac"))
require.True(t, itr.Valid())
require.Equal(t, itr.item.Key(), kb)
itr.Seek([]byte("ad"))
require.True(t, itr.Valid())
require.Equal(t, itr.item.Key(), kc)
itr.Seek(nil)
require.True(t, itr.Valid())
require.Equal(t, itr.item.Key(), kc)
itr.Seek([]byte("ac"))
itr.Rewind()
require.True(t, itr.Valid())
require.Equal(t, itr.item.Key(), kc)
itr.Seek([]byte("ad"))
require.True(t, itr.Valid())
require.Equal(t, itr.item.Key(), kc)
itr.Close()
// Keys: "abc", "ade"
itr = txn2.NewIterator(rev)
itr.Seek([]byte("ad"))
require.True(t, itr.Valid())
require.Equal(t, itr.item.Key(), kb)
itr.Seek([]byte("ae"))
require.True(t, itr.Valid())
require.Equal(t, itr.item.Key(), kd)
itr.Seek(nil)
require.True(t, itr.Valid())
require.Equal(t, itr.item.Key(), kd)
itr.Seek([]byte("ab"))
itr.Rewind()
require.True(t, itr.Valid())
require.Equal(t, itr.item.Key(), kd)
itr.Seek([]byte("ac"))
require.True(t, itr.Valid())
require.Equal(t, itr.item.Key(), kb)
itr.Close()
})
}
func TestIteratorAllVersionsWithDeleted(t *testing.T) {
test := func(t *testing.T, db *DB) {
// Write two keys
err := db.Update(func(txn *Txn) error {
require.NoError(t, txn.SetEntry(NewEntry([]byte("answer1"), []byte("42"))))
return txn.SetEntry(NewEntry([]byte("answer2"), []byte("43")))
})
require.NoError(t, err)
// Delete the specific key version from underlying db directly
err = db.View(func(txn *Txn) error {
item, err := txn.Get([]byte("answer1"))
require.NoError(t, err)
err = txn.db.batchSet([]*Entry{
{
Key: y.KeyWithTs(item.key, item.version),
meta: bitDelete,
},
})
require.NoError(t, err)
return err
})
require.NoError(t, err)
opts := DefaultIteratorOptions
opts.AllVersions = true
opts.PrefetchValues = false
// Verify that deleted shows up when AllVersions is set.
err = db.View(func(txn *Txn) error {
it := txn.NewIterator(opts)
defer it.Close()
var count int
for it.Rewind(); it.Valid(); it.Next() {
count++
item := it.Item()
if count == 1 {
require.Equal(t, []byte("answer1"), item.Key())
require.True(t, item.meta&bitDelete > 0)
} else {
require.Equal(t, []byte("answer2"), item.Key())
}
}
require.Equal(t, 2, count)
return nil
})
require.NoError(t, err)
}
t.Run("disk mode", func(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
test(t, db)
})
})
t.Run("InMemory mode", func(t *testing.T) {
opt := getTestOptions("")
opt.InMemory = true
db, err := Open(opt)
require.NoError(t, err)
test(t, db)
require.NoError(t, db.Close())
})
}
func TestIteratorAllVersionsWithDeleted2(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
// Set and delete alternatively
for i := 0; i < 4; i++ {
err := db.Update(func(txn *Txn) error {
if i%2 == 0 {
require.NoError(t, txn.SetEntry(NewEntry([]byte("key"), []byte("value"))))
return nil
}
return txn.Delete([]byte("key"))
})
require.NoError(t, err)
}
opts := DefaultIteratorOptions
opts.AllVersions = true
opts.PrefetchValues = false
// Verify that deleted shows up when AllVersions is set.
err := db.View(func(txn *Txn) error {
it := txn.NewIterator(opts)
defer it.Close()
var count int
for it.Rewind(); it.Valid(); it.Next() {
item := it.Item()
require.Equal(t, []byte("key"), item.Key())
if count%2 != 0 {
val, err := item.ValueCopy(nil)
require.NoError(t, err)
require.Equal(t, val, []byte("value"))
} else {
require.True(t, item.meta&bitDelete > 0)
}
count++
}
require.Equal(t, 4, count)
return nil
})
require.NoError(t, err)
})
}
func TestManagedDB(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := getTestOptions(dir)
opt.managedTxns = true
test := func(t *testing.T, db *DB) {
key := func(i int) []byte {
return []byte(fmt.Sprintf("key-%02d", i))
}
val := func(i int) []byte {
return []byte(fmt.Sprintf("val-%d", i))
}
require.Panics(t, func() {
_ = db.Update(func(tx *Txn) error { return nil })
})
err = db.View(func(tx *Txn) error { return nil })
require.NoError(t, err)
// Write data at t=3.
txn := db.NewTransactionAt(3, true)
for i := 0; i <= 3; i++ {
require.NoError(t, txn.SetEntry(NewEntry(key(i), val(i))))
}
require.Error(t, txn.Commit())
require.NoError(t, txn.CommitAt(3, nil))
// Read data at t=2.
txn = db.NewTransactionAt(2, false)
for i := 0; i <= 3; i++ {
_, err := txn.Get(key(i))
require.Equal(t, ErrKeyNotFound, err)
}
txn.Discard()
// Read data at t=3.
txn = db.NewTransactionAt(3, false)
for i := 0; i <= 3; i++ {
item, err := txn.Get(key(i))
require.NoError(t, err)
require.Equal(t, uint64(3), item.Version())
v, err := item.ValueCopy(nil)
require.NoError(t, err)
require.Equal(t, val(i), v)
}
txn.Discard()
// Write data at t=7.
txn = db.NewTransactionAt(6, true)
for i := 0; i <= 7; i++ {
_, err := txn.Get(key(i))
if err == nil {
continue // Don't overwrite existing keys.
}
require.NoError(t, txn.SetEntry(NewEntry(key(i), val(i))))
}
require.NoError(t, txn.CommitAt(7, nil))
// Read data at t=9.
txn = db.NewTransactionAt(9, false)
for i := 0; i <= 9; i++ {
item, err := txn.Get(key(i))
if i <= 7 {
require.NoError(t, err)
} else {
require.Equal(t, ErrKeyNotFound, err)
}
if i <= 3 {
require.Equal(t, uint64(3), item.Version())
} else if i <= 7 {
require.Equal(t, uint64(7), item.Version())
}
if i <= 7 {
v, err := item.ValueCopy(nil)
require.NoError(t, err)
require.Equal(t, val(i), v)
}
}
txn.Discard()
// Write data to same key, causing a conflict
txn = db.NewTransactionAt(10, true)
txnb := db.NewTransactionAt(10, true)
_, err := txnb.Get(key(0))
require.NoError(t, err)
require.NoError(t, txn.SetEntry(NewEntry(key(0), val(0))))
require.NoError(t, txnb.SetEntry(NewEntry(key(0), val(1))))
require.NoError(t, txn.CommitAt(11, nil))
require.Equal(t, ErrConflict, txnb.CommitAt(11, nil))
}
t.Run("disk mode", func(t *testing.T) {
db, err := Open(opt)
require.NoError(t, err)
test(t, db)
require.NoError(t, db.Close())
})
t.Run("InMemory mode", func(t *testing.T) {
opt.InMemory = true
opt.Dir = ""
opt.ValueDir = ""
db, err := Open(opt)
require.NoError(t, err)
test(t, db)
require.NoError(t, db.Close())
})
}
func TestArmV7Issue311Fix(t *testing.T) {
dir, err := os.MkdirTemp("", "")
require.NoError(t, err)
defer removeDir(dir)
db, err := Open(DefaultOptions(dir).
WithValueLogFileSize(16 << 20).
WithBaseLevelSize(8 << 20).
WithBaseTableSize(2 << 20).
WithSyncWrites(false))
require.NoError(t, err)
err = db.View(func(txn *Txn) error { return nil })
require.NoError(t, err)
err = db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry([]byte{0x11}, []byte{0x22}))
})
require.NoError(t, err)
err = db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry([]byte{0x11}, []byte{0x22}))
})
require.NoError(t, err)
require.NoError(t, db.Close())
}
// This test tries to perform a GetAndSet operation using multiple concurrent
// transaction and only one of the transactions should be successful.
// Regression test for https://github.com/dgraph-io/badger/issues/1289
func TestConflict(t *testing.T) {
key := []byte("foo")
var setCount atomic.Uint32
testAndSet := func(wg *sync.WaitGroup, db *DB) {
defer wg.Done()
txn := db.NewTransaction(true)
defer txn.Discard()
_, err := txn.Get(key)
if err == ErrKeyNotFound {
// Unset the error.
err = nil
require.NoError(t, txn.Set(key, []byte("AA")))
txn.CommitWith(func(err error) {
if err == nil {
require.LessOrEqual(t, uint32(1), setCount.Add(1))
} else {
require.Error(t, err, ErrConflict)
}
})
}
require.NoError(t, err)
}
testAndSetItr := func(wg *sync.WaitGroup, db *DB) {
defer wg.Done()
txn := db.NewTransaction(true)
defer txn.Discard()
iopt := DefaultIteratorOptions
it := txn.NewIterator(iopt)
found := false
for it.Seek(key); it.Valid(); it.Next() {
found = true
}
it.Close()
if !found {
require.NoError(t, txn.Set(key, []byte("AA")))
txn.CommitWith(func(err error) {
if err == nil {
require.LessOrEqual(t, setCount.Add(1), uint32(1))
} else {
require.Error(t, err, ErrConflict)
}
})
}
}
runTest := func(t *testing.T, fn func(wg *sync.WaitGroup, db *DB)) {
loop := 10
numGo := 16 // This many concurrent transactions.
for i := 0; i < loop; i++ {
var wg sync.WaitGroup
wg.Add(numGo)
setCount.Store(0)
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
for j := 0; j < numGo; j++ {
go fn(&wg, db)
}
wg.Wait()
})
require.Equal(t, uint32(1), setCount.Load())
}
}
t.Run("TxnGet", func(t *testing.T) {
runTest(t, testAndSet)
})
t.Run("ItrSeek", func(t *testing.T) {
runTest(t, testAndSetItr)
})
}
================================================
FILE: util.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"encoding/hex"
"fmt"
"math/rand"
"os"
"time"
"github.com/dgraph-io/badger/v4/table"
"github.com/dgraph-io/badger/v4/y"
)
func (s *levelsController) validate() error {
for _, l := range s.levels {
if err := l.validate(); err != nil {
return y.Wrap(err, "Levels Controller")
}
}
return nil
}
// Check does some sanity check on one level of data or in-memory index.
func (s *levelHandler) validate() error {
if s.level == 0 {
return nil
}
s.RLock()
defer s.RUnlock()
numTables := len(s.tables)
for j := 1; j < numTables; j++ {
if j >= len(s.tables) {
return fmt.Errorf("Level %d, j=%d numTables=%d", s.level, j, numTables)
}
if y.CompareKeys(s.tables[j-1].Biggest(), s.tables[j].Smallest()) >= 0 {
return fmt.Errorf(
"Inter: Biggest(j-1)[%d] \n%s\n vs Smallest(j)[%d]: \n%s\n: "+
"level=%d j=%d numTables=%d",
s.tables[j-1].ID(), hex.Dump(s.tables[j-1].Biggest()), s.tables[j].ID(),
hex.Dump(s.tables[j].Smallest()), s.level, j, numTables)
}
if y.CompareKeys(s.tables[j].Smallest(), s.tables[j].Biggest()) > 0 {
return fmt.Errorf(
"Intra: \n%s\n vs \n%s\n: level=%d j=%d numTables=%d",
hex.Dump(s.tables[j].Smallest()), hex.Dump(s.tables[j].Biggest()), s.level, j, numTables)
}
}
return nil
}
// func (s *KV) debugPrintMore() { s.lc.debugPrintMore() }
// // debugPrintMore shows key ranges of each level.
// func (s *levelsController) debugPrintMore() {
// s.Lock()
// defer s.Unlock()
// for i := 0; i < s.kv.opt.MaxLevels; i++ {
// s.levels[i].debugPrintMore()
// }
// }
// func (s *levelHandler) debugPrintMore() {
// s.RLock()
// defer s.RUnlock()
// s.elog.Printf("Level %d:", s.level)
// for _, t := range s.tables {
// y.Printf(" [%s, %s]", t.Smallest(), t.Biggest())
// }
// y.Printf("\n")
// }
// reserveFileID reserves a unique file id.
func (s *levelsController) reserveFileID() uint64 {
id := s.nextFileID.Add(1)
return id - 1
}
func getIDMap(dir string) map[uint64]struct{} {
fileInfos, err := os.ReadDir(dir)
y.Check(err)
idMap := make(map[uint64]struct{})
for _, info := range fileInfos {
if info.IsDir() {
continue
}
fileID, ok := table.ParseFileID(info.Name())
if !ok {
continue
}
idMap[fileID] = struct{}{}
}
return idMap
}
func init() {
rand.Seed(time.Now().UnixNano())
}
================================================
FILE: value.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"bytes"
"context"
"errors"
"fmt"
"hash"
"hash/crc32"
"io"
"math"
"os"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"github.com/dgraph-io/badger/v4/y"
"github.com/dgraph-io/ristretto/v2/z"
)
// maxVlogFileSize is the maximum size of the vlog file which can be created. Vlog Offset is of
// uint32, so limiting at max uint32.
var maxVlogFileSize uint32 = math.MaxUint32
// Values have their first byte being byteData or byteDelete. This helps us distinguish between
// a key that has never been seen and a key that has been explicitly deleted.
const (
bitDelete byte = 1 << 0 // Set if the key has been deleted.
bitValuePointer byte = 1 << 1 // Set if the value is NOT stored directly next to key.
bitDiscardEarlierVersions byte = 1 << 2 // Set if earlier versions can be discarded.
// Set if item shouldn't be discarded via compactions (used by merge operator)
bitMergeEntry byte = 1 << 3
// The MSB 2 bits are for transactions.
bitTxn byte = 1 << 6 // Set if the entry is part of a txn.
bitFinTxn byte = 1 << 7 // Set if the entry is to indicate end of txn in value log.
mi int64 = 1 << 20 //nolint:unused
// size of vlog header.
// +----------------+------------------+
// | keyID(8 bytes) | baseIV(12 bytes)|
// +----------------+------------------+
vlogHeaderSize = 20
)
var errStop = errors.New("Stop iteration")
var errTruncate = errors.New("Do truncate")
type logEntry func(e Entry, vp valuePointer) error
type safeRead struct {
k []byte
v []byte
recordOffset uint32
lf *logFile
}
// hashReader implements io.Reader, io.ByteReader interfaces. It also keeps track of the number
// bytes read. The hashReader writes to h (hash) what it reads from r.
type hashReader struct {
r io.Reader
h hash.Hash32
bytesRead int // Number of bytes read.
}
func newHashReader(r io.Reader) *hashReader {
hash := crc32.New(y.CastagnoliCrcTable)
return &hashReader{
r: r,
h: hash,
}
}
// Read reads len(p) bytes from the reader. Returns the number of bytes read, error on failure.
func (t *hashReader) Read(p []byte) (int, error) {
n, err := t.r.Read(p)
if err != nil {
return n, err
}
t.bytesRead += n
return t.h.Write(p[:n])
}
// ReadByte reads exactly one byte from the reader. Returns error on failure.
func (t *hashReader) ReadByte() (byte, error) {
b := make([]byte, 1)
_, err := t.Read(b)
return b[0], err
}
// Sum32 returns the sum32 of the underlying hash.
func (t *hashReader) Sum32() uint32 {
return t.h.Sum32()
}
// Entry reads an entry from the provided reader. It also validates the checksum for every entry
// read. Returns error on failure.
func (r *safeRead) Entry(reader io.Reader) (*Entry, error) {
tee := newHashReader(reader)
var h header
hlen, err := h.DecodeFrom(tee)
if err != nil {
return nil, err
}
if h.klen > uint32(1<<16) { // Key length must be below uint16.
return nil, errTruncate
}
kl := int(h.klen)
if cap(r.k) < kl {
r.k = make([]byte, 2*kl)
}
vl := int(h.vlen)
if cap(r.v) < vl {
r.v = make([]byte, 2*vl)
}
e := &Entry{}
e.offset = r.recordOffset
e.hlen = hlen
buf := make([]byte, h.klen+h.vlen)
if _, err := io.ReadFull(tee, buf[:]); err != nil {
if err == io.EOF {
err = errTruncate
}
return nil, err
}
if r.lf.encryptionEnabled() {
if buf, err = r.lf.decryptKV(buf[:], r.recordOffset); err != nil {
return nil, err
}
}
e.Key = buf[:h.klen]
e.Value = buf[h.klen:]
var crcBuf [crc32.Size]byte
if _, err := io.ReadFull(reader, crcBuf[:]); err != nil {
if err == io.EOF {
err = errTruncate
}
return nil, err
}
crc := y.BytesToU32(crcBuf[:])
if crc != tee.Sum32() {
return nil, errTruncate
}
e.meta = h.meta
e.UserMeta = h.userMeta
e.ExpiresAt = h.expiresAt
return e, nil
}
func (vlog *valueLog) rewrite(f *logFile) error {
vlog.filesLock.RLock()
for _, fid := range vlog.filesToBeDeleted {
if fid == f.fid {
vlog.filesLock.RUnlock()
return fmt.Errorf("value log file already marked for deletion fid: %d", fid)
}
}
maxFid := vlog.maxFid
y.AssertTruef(f.fid < maxFid, "fid to move: %d. Current max fid: %d", f.fid, maxFid)
vlog.filesLock.RUnlock()
vlog.opt.Infof("Rewriting fid: %d", f.fid)
wb := make([]*Entry, 0, 1000)
var size int64
y.AssertTrue(vlog.db != nil)
var count, moved int
fe := func(e Entry) error {
count++
if count%100000 == 0 {
vlog.opt.Debugf("Processing entry %d", count)
}
vs, err := vlog.db.get(e.Key)
if err != nil {
return err
}
if discardEntry(e, vs, vlog.db) {
return nil
}
// Value is still present in value log.
if len(vs.Value) == 0 {
return fmt.Errorf("Empty value: %+v", vs)
}
var vp valuePointer
vp.Decode(vs.Value)
// If the entry found from the LSM Tree points to a newer vlog file, don't do anything.
if vp.Fid > f.fid {
return nil
}
// If the entry found from the LSM Tree points to an offset greater than the one
// read from vlog, don't do anything.
if vp.Offset > e.offset {
return nil
}
// If the entry read from LSM Tree and vlog file point to the same vlog file and offset,
// insert them back into the DB.
// NOTE: It might be possible that the entry read from the LSM Tree points to
// an older vlog file. See the comments in the else part.
if vp.Fid == f.fid && vp.Offset == e.offset {
moved++
// This new entry only contains the key, and a pointer to the value.
ne := new(Entry)
// Remove only the bitValuePointer and transaction markers. We
// should keep the other bits.
ne.meta = e.meta &^ (bitValuePointer | bitTxn | bitFinTxn)
ne.UserMeta = e.UserMeta
ne.ExpiresAt = e.ExpiresAt
ne.Key = append([]byte{}, e.Key...)
ne.Value = append([]byte{}, e.Value...)
es := ne.estimateSizeAndSetThreshold(vlog.db.valueThreshold())
// Consider size of value as well while considering the total size
// of the batch. There have been reports of high memory usage in
// rewrite because we don't consider the value size. See #1292.
es += int64(len(e.Value))
// Ensure length and size of wb is within transaction limits.
if int64(len(wb)+1) >= vlog.opt.maxBatchCount ||
size+es >= vlog.opt.maxBatchSize {
if err := vlog.db.batchSet(wb); err != nil {
return err
}
size = 0
wb = wb[:0]
}
wb = append(wb, ne)
size += es
} else { //nolint:staticcheck
// It might be possible that the entry read from LSM Tree points to
// an older vlog file. This can happen in the following situation.
// Assume DB is opened with
// numberOfVersionsToKeep=1
//
// Now, if we have ONLY one key in the system "FOO" which has been
// updated 3 times and the same key has been garbage collected 3
// times, we'll have 3 versions of the movekey
// for the same key "FOO".
//
// NOTE: moveKeyi is the gc'ed version of the original key with version i
// We're calling the gc'ed keys as moveKey to simplify the
// explanation. We used to add move keys but we no longer do that.
//
// Assume we have 3 move keys in L0.
// - moveKey1 (points to vlog file 10),
// - moveKey2 (points to vlog file 14) and
// - moveKey3 (points to vlog file 15).
//
// Also, assume there is another move key "moveKey1" (points to
// vlog file 6) (this is also a move Key for key "FOO" ) on upper
// levels (let's say 3). The move key "moveKey1" on level 0 was
// inserted because vlog file 6 was GCed.
//
// Here's what the arrangement looks like
// L0 => (moveKey1 => vlog10), (moveKey2 => vlog14), (moveKey3 => vlog15)
// L1 => ....
// L2 => ....
// L3 => (moveKey1 => vlog6)
//
// When L0 compaction runs, it keeps only moveKey3 because the number of versions
// to keep is set to 1. (we've dropped moveKey1's latest version)
//
// The new arrangement of keys is
// L0 => ....
// L1 => (moveKey3 => vlog15)
// L2 => ....
// L3 => (moveKey1 => vlog6)
//
// Now if we try to GC vlog file 10, the entry read from vlog file
// will point to vlog10 but the entry read from LSM Tree will point
// to vlog6. The move key read from LSM tree will point to vlog6
// because we've asked for version 1 of the move key.
//
// This might seem like an issue but it's not really an issue
// because the user has set the number of versions to keep to 1 and
// the latest version of moveKey points to the correct vlog file
// and offset. The stale move key on L3 will be eventually dropped
// by compaction because there is a newer versions in the upper
// levels.
}
return nil
}
_, err := f.iterate(vlog.opt.ReadOnly, 0, func(e Entry, vp valuePointer) error {
return fe(e)
})
if err != nil {
return err
}
batchSize := 1024
var loops int
for i := 0; i < len(wb); {
loops++
if batchSize == 0 {
vlog.db.opt.Warningf("We shouldn't reach batch size of zero.")
return ErrNoRewrite
}
end := i + batchSize
if end > len(wb) {
end = len(wb)
}
if err := vlog.db.batchSet(wb[i:end]); err != nil {
if err == ErrTxnTooBig {
// Decrease the batch size to half.
batchSize = batchSize / 2
continue
}
return err
}
i += batchSize
}
vlog.opt.Infof("Processed %d entries in %d loops", len(wb), loops)
vlog.opt.Infof("Total entries: %d. Moved: %d", count, moved)
vlog.opt.Infof("Removing fid: %d", f.fid)
var deleteFileNow bool
// Entries written to LSM. Remove the older file now.
{
vlog.filesLock.Lock()
// Just a sanity-check.
if _, ok := vlog.filesMap[f.fid]; !ok {
vlog.filesLock.Unlock()
return fmt.Errorf("Unable to find fid: %d", f.fid)
}
if vlog.iteratorCount() == 0 {
delete(vlog.filesMap, f.fid)
deleteFileNow = true
} else {
vlog.filesToBeDeleted = append(vlog.filesToBeDeleted, f.fid)
}
vlog.filesLock.Unlock()
}
if deleteFileNow {
if err := vlog.deleteLogFile(f); err != nil {
return err
}
}
return nil
}
func (vlog *valueLog) incrIteratorCount() {
vlog.numActiveIterators.Add(1)
}
func (vlog *valueLog) iteratorCount() int {
return int(vlog.numActiveIterators.Load())
}
func (vlog *valueLog) decrIteratorCount() error {
num := vlog.numActiveIterators.Add(-1)
if num != 0 {
return nil
}
vlog.filesLock.Lock()
lfs := make([]*logFile, 0, len(vlog.filesToBeDeleted))
for _, id := range vlog.filesToBeDeleted {
lfs = append(lfs, vlog.filesMap[id])
delete(vlog.filesMap, id)
}
vlog.filesToBeDeleted = nil
vlog.filesLock.Unlock()
for _, lf := range lfs {
if err := vlog.deleteLogFile(lf); err != nil {
return err
}
}
return nil
}
func (vlog *valueLog) deleteLogFile(lf *logFile) error {
if lf == nil {
return nil
}
lf.lock.Lock()
defer lf.lock.Unlock()
// Delete fid from discard stats as well.
vlog.discardStats.Update(lf.fid, -1)
return lf.Delete()
}
func (vlog *valueLog) dropAll() (int, error) {
// If db is opened in InMemory mode, we don't need to do anything since there are no vlog files.
if vlog.db.opt.InMemory {
return 0, nil
}
// We don't want to block dropAll on any pending transactions. So, don't worry about iterator
// count.
var count int
deleteAll := func() error {
vlog.filesLock.Lock()
defer vlog.filesLock.Unlock()
for _, lf := range vlog.filesMap {
if err := vlog.deleteLogFile(lf); err != nil {
return err
}
count++
}
vlog.filesMap = make(map[uint32]*logFile)
vlog.maxFid = 0
return nil
}
if err := deleteAll(); err != nil {
return count, err
}
vlog.db.opt.Infof("Value logs deleted. Creating value log file: 1")
if _, err := vlog.createVlogFile(); err != nil { // Called while writes are stopped.
return count, err
}
return count, nil
}
func (db *DB) valueThreshold() int64 {
return db.threshold.valueThreshold.Load()
}
type valueLog struct {
dirPath string
// guards our view of which files exist, which to be deleted, how many active iterators
filesLock sync.RWMutex
filesMap map[uint32]*logFile
maxFid uint32
filesToBeDeleted []uint32
// A refcount of iterators -- when this hits zero, we can delete the filesToBeDeleted.
numActiveIterators atomic.Int32
db *DB
writableLogOffset atomic.Uint32 // read by read, written by write
numEntriesWritten uint32
opt Options
garbageCh chan struct{}
discardStats *discardStats
}
func vlogFilePath(dirPath string, fid uint32) string {
return fmt.Sprintf("%s%s%06d.vlog", dirPath, string(os.PathSeparator), fid)
}
func (vlog *valueLog) fpath(fid uint32) string {
return vlogFilePath(vlog.dirPath, fid)
}
func (vlog *valueLog) populateFilesMap() error {
vlog.filesMap = make(map[uint32]*logFile)
files, err := os.ReadDir(vlog.dirPath)
if err != nil {
return errFile(err, vlog.dirPath, "Unable to open log dir.")
}
found := make(map[uint64]struct{})
for _, file := range files {
if !strings.HasSuffix(file.Name(), ".vlog") {
continue
}
fsz := len(file.Name())
fid, err := strconv.ParseUint(file.Name()[:fsz-5], 10, 32)
if err != nil {
return errFile(err, file.Name(), "Unable to parse log id.")
}
if _, ok := found[fid]; ok {
return errFile(err, file.Name(), "Duplicate file found. Please delete one.")
}
found[fid] = struct{}{}
lf := &logFile{
fid: uint32(fid),
path: vlog.fpath(uint32(fid)),
registry: vlog.db.registry,
}
vlog.filesMap[uint32(fid)] = lf
if vlog.maxFid < uint32(fid) {
vlog.maxFid = uint32(fid)
}
}
return nil
}
func (vlog *valueLog) createVlogFile() (*logFile, error) {
fid := vlog.maxFid + 1
path := vlog.fpath(fid)
lf := &logFile{
fid: fid,
path: path,
registry: vlog.db.registry,
writeAt: vlogHeaderSize,
opt: vlog.opt,
}
err := lf.open(path, os.O_RDWR|os.O_CREATE|os.O_EXCL, 2*vlog.opt.ValueLogFileSize)
if err != z.NewFile && err != nil {
return nil, err
}
vlog.filesLock.Lock()
vlog.filesMap[fid] = lf
y.AssertTrue(vlog.maxFid < fid)
vlog.maxFid = fid
// writableLogOffset is only written by write func, by read by Read func.
// To avoid a race condition, all reads and updates to this variable must be
// done via atomics.
vlog.writableLogOffset.Store(vlogHeaderSize)
vlog.numEntriesWritten = 0
vlog.filesLock.Unlock()
return lf, nil
}
func errFile(err error, path string, msg string) error {
return fmt.Errorf("%s. Path=%s. Error=%v", msg, path, err)
}
// init initializes the value log struct. This initialization needs to happen
// before compactions start.
func (vlog *valueLog) init(db *DB) {
vlog.opt = db.opt
vlog.db = db
// We don't need to open any vlog files or collect stats for GC if DB is opened
// in InMemory mode. InMemory mode doesn't create any files/directories on disk.
if vlog.opt.InMemory {
return
}
vlog.dirPath = vlog.opt.ValueDir
vlog.garbageCh = make(chan struct{}, 1) // Only allow one GC at a time.
lf, err := InitDiscardStats(vlog.opt)
y.Check(err)
vlog.discardStats = lf
// See TestPersistLFDiscardStats for purpose of statement below.
db.logToSyncChan(endVLogInitMsg)
}
func (vlog *valueLog) open(db *DB) error {
// We don't need to open any vlog files or collect stats for GC if DB is opened
// in InMemory mode. InMemory mode doesn't create any files/directories on disk.
if db.opt.InMemory {
return nil
}
if err := vlog.populateFilesMap(); err != nil {
return err
}
// If no files are found, then create a new file.
if len(vlog.filesMap) == 0 {
if vlog.opt.ReadOnly {
return nil
}
_, err := vlog.createVlogFile()
return y.Wrapf(err, "Error while creating log file in valueLog.open")
}
fids := vlog.sortedFids()
for _, fid := range fids {
lf, ok := vlog.filesMap[fid]
y.AssertTrue(ok)
// Just open in RDWR mode. This should not create a new log file.
lf.opt = vlog.opt
if err := lf.open(vlog.fpath(fid), os.O_RDWR,
2*vlog.opt.ValueLogFileSize); err != nil {
return y.Wrapf(err, "Open existing file: %q", lf.path)
}
// We shouldn't delete the maxFid file.
if lf.size.Load() == vlogHeaderSize && fid != vlog.maxFid {
vlog.opt.Infof("Deleting empty file: %s", lf.path)
if err := lf.Delete(); err != nil {
return y.Wrapf(err, "while trying to delete empty file: %s", lf.path)
}
delete(vlog.filesMap, fid)
}
}
if vlog.opt.ReadOnly {
return nil
}
// Now we can read the latest value log file, and see if it needs truncation. We could
// technically do this over all the value log files, but that would mean slowing down the value
// log open.
last, ok := vlog.filesMap[vlog.maxFid]
y.AssertTrue(ok)
lastOff, err := last.iterate(vlog.opt.ReadOnly, vlogHeaderSize,
func(_ Entry, vp valuePointer) error {
return nil
})
if err != nil {
return y.Wrapf(err, "while iterating over: %s", last.path)
}
if err := last.Truncate(int64(lastOff)); err != nil {
return y.Wrapf(err, "while truncating last value log file: %s", last.path)
}
// Don't write to the old log file. Always create a new one.
if _, err := vlog.createVlogFile(); err != nil {
return y.Wrapf(err, "Error while creating log file in valueLog.open")
}
return nil
}
func (vlog *valueLog) Close() error {
if vlog == nil || vlog.db == nil || vlog.db.opt.InMemory {
return nil
}
vlog.opt.Debugf("Stopping garbage collection of values.")
var err error
for id, lf := range vlog.filesMap {
lf.lock.Lock() // We won’t release the lock.
offset := int64(-1)
if !vlog.opt.ReadOnly && id == vlog.maxFid {
offset = int64(vlog.woffset())
}
if terr := lf.Close(offset); terr != nil && err == nil {
err = terr
}
}
if vlog.discardStats != nil {
vlog.db.captureDiscardStats()
if terr := vlog.discardStats.Close(-1); terr != nil && err == nil {
err = terr
}
}
return err
}
// sortedFids returns the file id's not pending deletion, sorted. Assumes we have shared access to
// filesMap.
func (vlog *valueLog) sortedFids() []uint32 {
toBeDeleted := make(map[uint32]struct{})
for _, fid := range vlog.filesToBeDeleted {
toBeDeleted[fid] = struct{}{}
}
ret := make([]uint32, 0, len(vlog.filesMap))
for fid := range vlog.filesMap {
if _, ok := toBeDeleted[fid]; !ok {
ret = append(ret, fid)
}
}
sort.Slice(ret, func(i, j int) bool {
return ret[i] < ret[j]
})
return ret
}
type request struct {
// Input values
Entries []*Entry
// Output values and wait group stuff below
Ptrs []valuePointer
Wg sync.WaitGroup
Err error
ref atomic.Int32
}
func (req *request) reset() {
req.Entries = req.Entries[:0]
req.Ptrs = req.Ptrs[:0]
req.Wg = sync.WaitGroup{}
req.Err = nil
req.ref.Store(0)
}
func (req *request) IncrRef() {
req.ref.Add(1)
}
func (req *request) DecrRef() {
nRef := req.ref.Add(-1)
if nRef > 0 {
return
}
req.Entries = nil
requestPool.Put(req)
}
func (req *request) Wait() error {
req.Wg.Wait()
err := req.Err
req.DecrRef() // DecrRef after writing to DB.
return err
}
type requests []*request
func (reqs requests) DecrRef() {
for _, req := range reqs {
req.DecrRef()
}
}
func (reqs requests) IncrRef() {
for _, req := range reqs {
req.IncrRef()
}
}
// sync function syncs content of latest value log file to disk. Syncing of value log directory is
// not required here as it happens every time a value log file rotation happens(check createVlogFile
// function). During rotation, previous value log file also gets synced to disk. It only syncs file
// if fid >= vlog.maxFid. In some cases such as replay(while opening db), it might be called with
// fid < vlog.maxFid. To sync irrespective of file id just call it with math.MaxUint32.
func (vlog *valueLog) sync() error {
if vlog.opt.SyncWrites || vlog.opt.InMemory {
return nil
}
vlog.filesLock.RLock()
maxFid := vlog.maxFid
curlf := vlog.filesMap[maxFid]
// Sometimes it is possible that vlog.maxFid has been increased but file creation
// with same id is still in progress and this function is called. In those cases
// entry for the file might not be present in vlog.filesMap.
if curlf == nil {
vlog.filesLock.RUnlock()
return nil
}
curlf.lock.RLock()
vlog.filesLock.RUnlock()
err := curlf.Sync()
curlf.lock.RUnlock()
return err
}
func (vlog *valueLog) woffset() uint32 {
return vlog.writableLogOffset.Load()
}
// validateWrites will check whether the given requests can fit into 4GB vlog file.
// NOTE: 4GB is the maximum size we can create for vlog because value pointer offset is of type
// uint32. If we create more than 4GB, it will overflow uint32. So, limiting the size to 4GB.
func (vlog *valueLog) validateWrites(reqs []*request) error {
vlogOffset := uint64(vlog.woffset())
for _, req := range reqs {
// calculate size of the request.
size := estimateRequestSize(req)
estimatedVlogOffset := vlogOffset + size
if estimatedVlogOffset > uint64(maxVlogFileSize) {
return fmt.Errorf("Request size offset %d is bigger than maximum offset %d",
estimatedVlogOffset, maxVlogFileSize)
}
if estimatedVlogOffset >= uint64(vlog.opt.ValueLogFileSize) {
// We'll create a new vlog file if the estimated offset is greater or equal to
// max vlog size. So, resetting the vlogOffset.
vlogOffset = 0
continue
}
// Estimated vlog offset will become current vlog offset if the vlog is not rotated.
vlogOffset = estimatedVlogOffset
}
return nil
}
// estimateRequestSize returns the size that needed to be written for the given request.
func estimateRequestSize(req *request) uint64 {
size := uint64(0)
for _, e := range req.Entries {
size += uint64(maxHeaderSize + len(e.Key) + len(e.Value) + crc32.Size)
}
return size
}
// write is thread-unsafe by design and should not be called concurrently.
func (vlog *valueLog) write(reqs []*request) error {
if vlog.db.opt.InMemory {
return nil
}
// Validate writes before writing to vlog. Because, we don't want to partially write and return
// an error.
if err := vlog.validateWrites(reqs); err != nil {
return y.Wrapf(err, "while validating writes")
}
vlog.filesLock.RLock()
maxFid := vlog.maxFid
curlf := vlog.filesMap[maxFid]
vlog.filesLock.RUnlock()
defer func() {
if vlog.opt.SyncWrites {
if err := curlf.Sync(); err != nil {
vlog.opt.Errorf("Error while curlf sync: %v\n", err)
}
}
}()
write := func(buf *bytes.Buffer) error {
if buf.Len() == 0 {
return nil
}
n := uint32(buf.Len())
endOffset := vlog.writableLogOffset.Add(n)
// Increase the file size if we cannot accommodate this entry.
// [Aman] Should this be >= or just >? Doesn't make sense to extend the file if it big enough already.
if int(endOffset) >= len(curlf.Data) {
if err := curlf.Truncate(int64(endOffset)); err != nil {
return err
}
}
start := int(endOffset - n)
y.AssertTrue(copy(curlf.Data[start:], buf.Bytes()) == int(n))
curlf.size.Store(endOffset)
return nil
}
toDisk := func() error {
if vlog.woffset() > uint32(vlog.opt.ValueLogFileSize) ||
vlog.numEntriesWritten > vlog.opt.ValueLogMaxEntries {
if err := curlf.doneWriting(vlog.woffset()); err != nil {
return err
}
newlf, err := vlog.createVlogFile()
if err != nil {
return err
}
curlf = newlf
}
return nil
}
buf := new(bytes.Buffer)
for i := range reqs {
b := reqs[i]
b.Ptrs = b.Ptrs[:0]
var written, bytesWritten int
valueSizes := make([]int64, 0, len(b.Entries))
for j := range b.Entries {
buf.Reset()
e := b.Entries[j]
valueSizes = append(valueSizes, int64(len(e.Value)))
if e.skipVlogAndSetThreshold(vlog.db.valueThreshold()) {
b.Ptrs = append(b.Ptrs, valuePointer{})
continue
}
var p valuePointer
p.Fid = curlf.fid
p.Offset = vlog.woffset()
// We should not store transaction marks in the vlog file because it will never have all
// the entries in a transaction. If we store entries with transaction marks then value
// GC will not be able to iterate on the entire vlog file.
// But, we still want the entry to stay intact for the memTable WAL. So, store the meta
// in a temporary variable and reassign it after writing to the value log.
tmpMeta := e.meta
e.meta = e.meta &^ (bitTxn | bitFinTxn)
plen, err := curlf.encodeEntry(buf, e, p.Offset) // Now encode the entry into buffer.
if err != nil {
return err
}
// Restore the meta.
e.meta = tmpMeta
p.Len = uint32(plen)
b.Ptrs = append(b.Ptrs, p)
if err := write(buf); err != nil {
return err
}
written++
bytesWritten += buf.Len()
// No need to flush anything, we write to file directly via mmap.
}
y.NumWritesVlogAdd(vlog.opt.MetricsEnabled, int64(written))
y.NumBytesWrittenVlogAdd(vlog.opt.MetricsEnabled, int64(bytesWritten))
vlog.numEntriesWritten += uint32(written)
vlog.db.threshold.update(valueSizes)
// We write to disk here so that all entries that are part of the same transaction are
// written to the same vlog file.
if err := toDisk(); err != nil {
return err
}
}
return toDisk()
}
// Gets the logFile and acquires and RLock() for the mmap. You must call RUnlock on the file
// (if non-nil)
func (vlog *valueLog) getFileRLocked(vp valuePointer) (*logFile, error) {
vlog.filesLock.RLock()
defer vlog.filesLock.RUnlock()
ret, ok := vlog.filesMap[vp.Fid]
if !ok {
// log file has gone away, we can't do anything. Return.
return nil, fmt.Errorf("file with ID: %d not found", vp.Fid)
}
// Check for valid offset if we are reading from writable log.
maxFid := vlog.maxFid
// In read-only mode we don't need to check for writable offset as we are not writing anything.
// Moreover, this offset is not set in readonly mode.
if !vlog.opt.ReadOnly && vp.Fid == maxFid {
currentOffset := vlog.woffset()
if vp.Offset >= currentOffset {
return nil, fmt.Errorf(
"Invalid value pointer offset: %d greater than current offset: %d",
vp.Offset, currentOffset)
}
}
ret.lock.RLock()
return ret, nil
}
// Read reads the value log at a given location.
// TODO: Make this read private.
func (vlog *valueLog) Read(vp valuePointer, _ *y.Slice) ([]byte, func(), error) {
buf, lf, err := vlog.readValueBytes(vp)
// log file is locked so, decide whether to lock immediately or let the caller to
// unlock it, after caller uses it.
cb := vlog.getUnlockCallback(lf)
if err != nil {
return nil, cb, err
}
if vlog.opt.VerifyValueChecksum {
hash := crc32.New(y.CastagnoliCrcTable)
if _, err := hash.Write(buf[:len(buf)-crc32.Size]); err != nil {
runCallback(cb)
return nil, nil, y.Wrapf(err, "failed to write hash for vp %+v", vp)
}
// Fetch checksum from the end of the buffer.
checksum := buf[len(buf)-crc32.Size:]
if hash.Sum32() != y.BytesToU32(checksum) {
runCallback(cb)
return nil, nil, y.Wrapf(y.ErrChecksumMismatch, "value corrupted for vp: %+v", vp)
}
}
var h header
headerLen := h.Decode(buf)
kv := buf[headerLen:]
if lf.encryptionEnabled() {
kv, err = lf.decryptKV(kv, vp.Offset)
if err != nil {
return nil, cb, err
}
}
if uint32(len(kv)) < h.klen+h.vlen {
vlog.db.opt.Errorf("Invalid read: vp: %+v", vp)
return nil, nil, fmt.Errorf("Invalid read: Len: %d read at:[%d:%d]",
len(kv), h.klen, h.klen+h.vlen)
}
return kv[h.klen : h.klen+h.vlen], cb, nil
}
// getUnlockCallback will returns a function which unlock the logfile if the logfile is mmaped.
// otherwise, it unlock the logfile and return nil.
func (vlog *valueLog) getUnlockCallback(lf *logFile) func() {
if lf == nil {
return nil
}
return lf.lock.RUnlock
}
// readValueBytes return vlog entry slice and read locked log file. Caller should take care of
// logFile unlocking.
func (vlog *valueLog) readValueBytes(vp valuePointer) ([]byte, *logFile, error) {
lf, err := vlog.getFileRLocked(vp)
if err != nil {
return nil, nil, err
}
buf, err := lf.read(vp)
y.NumReadsVlogAdd(vlog.db.opt.MetricsEnabled, 1)
y.NumBytesReadsVlogAdd(vlog.db.opt.MetricsEnabled, int64(len(buf)))
return buf, lf, err
}
func (vlog *valueLog) pickLog(discardRatio float64) *logFile {
vlog.filesLock.RLock()
defer vlog.filesLock.RUnlock()
LOOP:
// Pick a candidate that contains the largest amount of discardable data
fid, discard := vlog.discardStats.MaxDiscard()
// MaxDiscard will return fid=0 if it doesn't have any discard data. The
// vlog files start from 1.
if fid == 0 {
vlog.opt.Debugf("No file with discard stats")
return nil
}
lf, ok := vlog.filesMap[fid]
// This file was deleted but it's discard stats increased because of compactions. The file
// doesn't exist so we don't need to do anything. Skip it and retry.
if !ok {
vlog.discardStats.Update(fid, -1)
goto LOOP
}
// We have a valid file.
fi, err := lf.Fd.Stat()
if err != nil {
vlog.opt.Errorf("Unable to get stats for value log fid: %d err: %+v", fi, err)
return nil
}
if thr := discardRatio * float64(fi.Size()); float64(discard) < thr {
vlog.opt.Debugf("Discard: %d less than threshold: %.0f for file: %s",
discard, thr, fi.Name())
return nil
}
if fid < vlog.maxFid {
vlog.opt.Infof("Found value log max discard fid: %d discard: %d\n", fid, discard)
lf, ok := vlog.filesMap[fid]
y.AssertTrue(ok)
return lf
}
// Don't randomly pick any value log file.
return nil
}
func discardEntry(e Entry, vs y.ValueStruct, db *DB) bool {
if vs.Version != y.ParseTs(e.Key) {
// Version not found. Discard.
return true
}
if isDeletedOrExpired(vs.Meta, vs.ExpiresAt) {
return true
}
if (vs.Meta & bitValuePointer) == 0 {
// Key also stores the value in LSM. Discard.
return true
}
if (vs.Meta & bitFinTxn) > 0 {
// Just a txn finish entry. Discard.
return true
}
return false
}
func (vlog *valueLog) doRunGC(lf *logFile) error {
_, span := otel.Tracer("").Start(context.TODO(), "Badger.GC")
span.SetAttributes(attribute.String("GC rewrite for", lf.path))
defer span.End()
if err := vlog.rewrite(lf); err != nil {
return err
}
// Remove the file from discardStats.
vlog.discardStats.Update(lf.fid, -1)
return nil
}
func (vlog *valueLog) waitOnGC(lc *z.Closer) {
defer lc.Done()
<-lc.HasBeenClosed() // Wait for lc to be closed.
// Block any GC in progress to finish, and don't allow any more writes to runGC by filling up
// the channel of size 1.
vlog.garbageCh <- struct{}{}
}
func (vlog *valueLog) runGC(discardRatio float64) error {
select {
case vlog.garbageCh <- struct{}{}:
// Pick a log file for GC.
defer func() {
<-vlog.garbageCh
}()
lf := vlog.pickLog(discardRatio)
if lf == nil {
return ErrNoRewrite
}
return vlog.doRunGC(lf)
default:
return ErrRejected
}
}
func (vlog *valueLog) updateDiscardStats(stats map[uint32]int64) {
if vlog.opt.InMemory {
return
}
for fid, discard := range stats {
vlog.discardStats.Update(fid, discard)
}
// The following is to coordinate with some test cases where we want to
// verify that at least one iteration of updateDiscardStats has been completed.
vlog.db.logToSyncChan(updateDiscardStatsMsg)
}
type vlogThreshold struct {
logger Logger
percentile float64
valueThreshold atomic.Int64
valueCh chan []int64
clearCh chan bool
closer *z.Closer
// Metrics contains a running log of statistics like amount of data stored etc.
vlMetrics *z.HistogramData
}
func initVlogThreshold(opt *Options) *vlogThreshold {
getBounds := func() []float64 {
mxbd := opt.maxValueThreshold
mnbd := float64(opt.ValueThreshold)
y.AssertTruef(mxbd >= mnbd, "maximum threshold bound is less than the min threshold")
size := math.Min(mxbd-mnbd+1, 1024.0)
bdstp := (mxbd - mnbd) / size
bounds := make([]float64, int64(size))
for i := range bounds {
if i == 0 {
bounds[0] = mnbd
continue
}
if i == int(size-1) {
bounds[i] = mxbd
continue
}
bounds[i] = bounds[i-1] + bdstp
}
return bounds
}
lt := &vlogThreshold{
logger: opt.Logger,
percentile: opt.VLogPercentile,
valueCh: make(chan []int64, 1000),
clearCh: make(chan bool, 1),
closer: z.NewCloser(1),
vlMetrics: z.NewHistogramData(getBounds()),
}
lt.valueThreshold.Store(opt.ValueThreshold)
return lt
}
func (v *vlogThreshold) Clear(opt Options) {
v.valueThreshold.Store(opt.ValueThreshold)
v.clearCh <- true
}
func (v *vlogThreshold) update(sizes []int64) {
v.valueCh <- sizes
}
func (v *vlogThreshold) close() {
v.closer.SignalAndWait()
}
func (v *vlogThreshold) listenForValueThresholdUpdate() {
defer v.closer.Done()
for {
select {
case <-v.closer.HasBeenClosed():
return
case val := <-v.valueCh:
for _, e := range val {
v.vlMetrics.Update(e)
}
// we are making it to get Options.VlogPercentile so that values with sizes
// in range of Options.VlogPercentile will make it to the LSM tree and rest to the
// value log file.
p := int64(v.vlMetrics.Percentile(v.percentile))
if v.valueThreshold.Load() != p {
if v.logger != nil {
v.logger.Infof("updating value of threshold to: %d", p)
}
v.valueThreshold.Store(p)
}
case <-v.clearCh:
v.vlMetrics.Clear()
}
}
}
================================================
FILE: value_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"bytes"
"errors"
"fmt"
"math"
"math/rand"
"os"
"reflect"
"sync"
"testing"
humanize "github.com/dustin/go-humanize"
"github.com/stretchr/testify/require"
"github.com/dgraph-io/badger/v4/y"
)
func TestDynamicValueThreshold(t *testing.T) {
t.Skip()
dir, err := os.MkdirTemp("", "badger-test")
y.Check(err)
defer removeDir(dir)
kv, _ := Open(getTestOptions(dir).WithValueThreshold(32).WithVLogPercentile(0.99))
defer kv.Close()
log := &kv.vlog
for vl := 32; vl <= 1024; vl = vl + 4 {
for i := 0; i < 1000; i++ {
val := make([]byte, vl)
y.Check2(rand.Read(val))
e1 := &Entry{
Key: []byte(fmt.Sprintf("samplekey_%d_%d", vl, i)),
Value: val,
meta: bitValuePointer,
}
b := new(request)
b.Entries = []*Entry{e1}
require.NoError(t, log.write([]*request{b}))
}
t.Logf("value threshold is %d \n", log.db.valueThreshold())
}
for vl := 511; vl >= 31; vl = vl - 4 {
for i := 0; i < 5000; i++ {
val := make([]byte, vl)
y.Check2(rand.Read(val))
e1 := &Entry{
Key: []byte(fmt.Sprintf("samplekey_%d_%d", vl, i)),
Value: val,
meta: bitValuePointer,
}
b := new(request)
b.Entries = []*Entry{e1}
require.NoError(t, log.write([]*request{b}))
}
t.Logf("value threshold is %d \n", log.db.valueThreshold())
}
require.Equal(t, log.db.valueThreshold(), int64(995))
}
func TestValueBasic(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
y.Check(err)
defer removeDir(dir)
kv, _ := Open(getTestOptions(dir).WithValueThreshold(32))
defer kv.Close()
log := &kv.vlog
// Use value big enough that the value log writes them even if SyncWrites is false.
const val1 = "sampleval012345678901234567890123"
const val2 = "samplevalb012345678901234567890123"
require.True(t, int64(len(val1)) >= kv.vlog.db.valueThreshold())
e1 := &Entry{
Key: []byte("samplekey"),
Value: []byte(val1),
meta: bitValuePointer,
}
e2 := &Entry{
Key: []byte("samplekeyb"),
Value: []byte(val2),
meta: bitValuePointer,
}
b := new(request)
b.Entries = []*Entry{e1, e2}
require.NoError(t, log.write([]*request{b}))
require.Len(t, b.Ptrs, 2)
t.Logf("Pointer written: %+v %+v\n", b.Ptrs[0], b.Ptrs[1])
buf1, lf1, err1 := log.readValueBytes(b.Ptrs[0])
buf2, lf2, err2 := log.readValueBytes(b.Ptrs[1])
require.NoError(t, err1)
require.NoError(t, err2)
defer runCallback(log.getUnlockCallback(lf1))
defer runCallback(log.getUnlockCallback(lf2))
e1, err = lf1.decodeEntry(buf1, b.Ptrs[0].Offset)
require.NoError(t, err)
e2, err = lf1.decodeEntry(buf2, b.Ptrs[1].Offset)
require.NoError(t, err)
readEntries := []Entry{*e1, *e2}
require.EqualValues(t, []Entry{
{
Key: []byte("samplekey"),
Value: []byte(val1),
meta: bitValuePointer,
offset: b.Ptrs[0].Offset,
},
{
Key: []byte("samplekeyb"),
Value: []byte(val2),
meta: bitValuePointer,
offset: b.Ptrs[1].Offset,
},
}, readEntries)
}
func TestValueGCManaged(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
N := 10000
opt := getTestOptions(dir)
opt.ValueLogMaxEntries = uint32(N / 10)
opt.managedTxns = true
opt.BaseTableSize = 1 << 15
opt.ValueThreshold = 1 << 10
opt.MemTableSize = 1 << 15
db, err := Open(opt)
require.NoError(t, err)
defer db.Close()
var ts uint64
newTs := func() uint64 {
ts++
return ts
}
sz := 64 << 10
var wg sync.WaitGroup
for i := 0; i < N; i++ {
v := make([]byte, sz)
rand.Read(v[:rand.Intn(sz)])
wg.Add(1)
txn := db.NewTransactionAt(newTs(), true)
require.NoError(t, txn.SetEntry(NewEntry([]byte(fmt.Sprintf("key%d", i)), v)))
require.NoError(t, txn.CommitAt(newTs(), func(err error) {
wg.Done()
require.NoError(t, err)
}))
}
for i := 0; i < N; i++ {
wg.Add(1)
txn := db.NewTransactionAt(newTs(), true)
require.NoError(t, txn.Delete([]byte(fmt.Sprintf("key%d", i))))
require.NoError(t, txn.CommitAt(newTs(), func(err error) {
wg.Done()
require.NoError(t, err)
}))
}
wg.Wait()
entries, err := os.ReadDir(dir)
require.NoError(t, err)
for _, e := range entries {
fi, err := e.Info()
require.NoError(t, err)
t.Logf("File: %s. Size: %s\n", fi.Name(), humanize.IBytes(uint64(fi.Size())))
}
db.SetDiscardTs(math.MaxUint32)
require.NoError(t, db.Flatten(3))
for i := 0; i < 100; i++ {
// Try at max 100 times to GC even a single value log file.
if err := db.RunValueLogGC(0.0001); err == nil {
return // Done
}
}
require.Fail(t, "Unable to GC even a single value log file.")
}
func TestValueGC(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := getTestOptions(dir)
opt.ValueLogFileSize = 1 << 20
opt.BaseTableSize = 1 << 15
opt.ValueThreshold = 1 << 10
kv, _ := Open(opt)
defer kv.Close()
sz := 32 << 10
txn := kv.NewTransaction(true)
for i := 0; i < 100; i++ {
v := make([]byte, sz)
rand.Read(v[:rand.Intn(sz)])
require.NoError(t, txn.SetEntry(NewEntry([]byte(fmt.Sprintf("key%d", i)), v)))
if i%20 == 0 {
require.NoError(t, txn.Commit())
txn = kv.NewTransaction(true)
}
}
require.NoError(t, txn.Commit())
for i := 0; i < 45; i++ {
txnDelete(t, kv, []byte(fmt.Sprintf("key%d", i)))
}
kv.vlog.filesLock.RLock()
lf := kv.vlog.filesMap[kv.vlog.sortedFids()[0]]
kv.vlog.filesLock.RUnlock()
// lf.iterate(0, func(e Entry) bool {
// e.print("lf")
// return true
// })
require.NoError(t, kv.vlog.rewrite(lf))
for i := 45; i < 100; i++ {
key := []byte(fmt.Sprintf("key%d", i))
require.NoError(t, kv.View(func(txn *Txn) error {
item, err := txn.Get(key)
require.NoError(t, err)
val := getItemValue(t, item)
require.NotNil(t, val)
require.True(t, len(val) == sz, "Size found: %d", len(val))
return nil
}))
}
}
func TestValueGC2(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := getTestOptions(dir)
opt.ValueLogFileSize = 1 << 20
opt.BaseTableSize = 1 << 15
opt.ValueThreshold = 1 << 10
kv, _ := Open(opt)
defer kv.Close()
sz := 32 << 10
txn := kv.NewTransaction(true)
for i := 0; i < 100; i++ {
v := make([]byte, sz)
rand.Read(v[:rand.Intn(sz)])
require.NoError(t, txn.SetEntry(NewEntry([]byte(fmt.Sprintf("key%d", i)), v)))
if i%20 == 0 {
require.NoError(t, txn.Commit())
txn = kv.NewTransaction(true)
}
}
require.NoError(t, txn.Commit())
for i := 0; i < 5; i++ {
txnDelete(t, kv, []byte(fmt.Sprintf("key%d", i)))
}
for i := 5; i < 10; i++ {
v := []byte(fmt.Sprintf("value%d", i))
txnSet(t, kv, []byte(fmt.Sprintf("key%d", i)), v, 0)
}
kv.vlog.filesLock.RLock()
lf := kv.vlog.filesMap[kv.vlog.sortedFids()[0]]
kv.vlog.filesLock.RUnlock()
// lf.iterate(0, func(e Entry) bool {
// e.print("lf")
// return true
// })
require.NoError(t, kv.vlog.rewrite(lf))
for i := 0; i < 5; i++ {
key := []byte(fmt.Sprintf("key%d", i))
require.NoError(t, kv.View(func(txn *Txn) error {
_, err := txn.Get(key)
require.Equal(t, ErrKeyNotFound, err)
return nil
}))
}
for i := 5; i < 10; i++ {
key := []byte(fmt.Sprintf("key%d", i))
require.NoError(t, kv.View(func(txn *Txn) error {
item, err := txn.Get(key)
require.NoError(t, err)
val := getItemValue(t, item)
require.NotNil(t, val)
require.Equal(t, string(val), fmt.Sprintf("value%d", i))
return nil
}))
}
// Moved entries.
for i := 10; i < 100; i++ {
key := []byte(fmt.Sprintf("key%d", i))
require.NoError(t, kv.View(func(txn *Txn) error {
item, err := txn.Get(key)
require.NoError(t, err)
val := getItemValue(t, item)
require.NotNil(t, val)
require.True(t, len(val) == sz, "Size found: %d", len(val))
return nil
}))
}
}
func TestValueGC3(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := getTestOptions(dir)
opt.ValueLogFileSize = 1 << 20
opt.BaseTableSize = 1 << 15
opt.ValueThreshold = 1 << 10
kv, err := Open(opt)
require.NoError(t, err)
defer kv.Close()
// We want to test whether an iterator can continue through a value log GC.
valueSize := 32 << 10
var value3 []byte
txn := kv.NewTransaction(true)
for i := 0; i < 100; i++ {
v := make([]byte, valueSize) // 32K * 100 will take >=3'276'800 B.
if i == 3 {
value3 = v
}
rand.Read(v[:])
// Keys key000, key001, key002, such that sorted order matches insertion order
require.NoError(t, txn.SetEntry(NewEntry([]byte(fmt.Sprintf("key%03d", i)), v)))
if i%20 == 0 {
require.NoError(t, txn.Commit())
txn = kv.NewTransaction(true)
}
}
require.NoError(t, txn.Commit())
// Start an iterator to keys in the first value log file
itOpt := IteratorOptions{
PrefetchValues: false,
PrefetchSize: 0,
Reverse: false,
}
txn = kv.NewTransaction(true)
it := txn.NewIterator(itOpt)
defer it.Close()
// Walk a few keys
it.Rewind()
require.True(t, it.Valid())
item := it.Item()
require.Equal(t, []byte("key000"), item.Key())
it.Next()
require.True(t, it.Valid())
item = it.Item()
require.Equal(t, []byte("key001"), item.Key())
it.Next()
require.True(t, it.Valid())
item = it.Item()
require.Equal(t, []byte("key002"), item.Key())
// Like other tests, we pull out a logFile to rewrite it directly
kv.vlog.filesLock.RLock()
logFile := kv.vlog.filesMap[kv.vlog.sortedFids()[0]]
kv.vlog.filesLock.RUnlock()
require.NoError(t, kv.vlog.rewrite(logFile))
it.Next()
require.True(t, it.Valid())
item = it.Item()
require.Equal(t, []byte("key003"), item.Key())
v3, err := item.ValueCopy(nil)
require.NoError(t, err)
require.Equal(t, value3, v3)
}
func TestValueGC4(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := getTestOptions(dir)
opt.ValueLogFileSize = 1 << 20
opt.BaseTableSize = 1 << 15
opt.ValueThreshold = 1 << 10
kv, err := Open(opt)
require.NoError(t, err)
sz := 128 << 10 // 5 entries per value log file.
txn := kv.NewTransaction(true)
for i := 0; i < 24; i++ {
v := make([]byte, sz)
rand.Read(v[:rand.Intn(sz)])
require.NoError(t, txn.SetEntry(NewEntry([]byte(fmt.Sprintf("key%d", i)), v)))
if i%3 == 0 {
require.NoError(t, txn.Commit())
txn = kv.NewTransaction(true)
}
}
require.NoError(t, txn.Commit())
for i := 0; i < 8; i++ {
txnDelete(t, kv, []byte(fmt.Sprintf("key%d", i)))
}
for i := 8; i < 16; i++ {
v := []byte(fmt.Sprintf("value%d", i))
txnSet(t, kv, []byte(fmt.Sprintf("key%d", i)), v, 0)
}
kv.vlog.filesLock.RLock()
lf0 := kv.vlog.filesMap[kv.vlog.sortedFids()[0]]
lf1 := kv.vlog.filesMap[kv.vlog.sortedFids()[1]]
kv.vlog.filesLock.RUnlock()
// lf.iterate(0, func(e Entry) bool {
// e.print("lf")
// return true
// })
require.NoError(t, kv.vlog.rewrite(lf0))
require.NoError(t, kv.vlog.rewrite(lf1))
require.NoError(t, kv.Close())
kv, err = Open(opt)
require.NoError(t, err)
for i := 0; i < 8; i++ {
key := []byte(fmt.Sprintf("key%d", i))
require.NoError(t, kv.View(func(txn *Txn) error {
_, err := txn.Get(key)
require.Equal(t, ErrKeyNotFound, err)
return nil
}))
}
for i := 8; i < 16; i++ {
key := []byte(fmt.Sprintf("key%d", i))
require.NoError(t, kv.View(func(txn *Txn) error {
item, err := txn.Get(key)
require.NoError(t, err)
val := getItemValue(t, item)
require.NotNil(t, val)
require.Equal(t, string(val), fmt.Sprintf("value%d", i))
return nil
}))
}
require.NoError(t, kv.Close())
}
func TestPersistLFDiscardStats(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := getTestOptions(dir)
// Force more compaction by reducing the number of L0 tables.
opt.NumLevelZeroTables = 1
opt.ValueLogFileSize = 1 << 20
// Avoid compaction on close so that the discard map remains the same.
opt.CompactL0OnClose = false
opt.MemTableSize = 1 << 15
opt.ValueThreshold = 1 << 10
tChan := make(chan string, 100)
defer close(tChan)
opt.syncChan = tChan
db, err := Open(opt)
require.NoError(t, err)
capturedDiscardStats := make(map[uint64]uint64)
db.onCloseDiscardCapture = capturedDiscardStats
sz := 128 << 10 // 5 entries per value log file.
v := make([]byte, sz)
rand.Read(v[:rand.Intn(sz)])
txn := db.NewTransaction(true)
for i := 0; i < 500; i++ {
require.NoError(t, txn.SetEntry(NewEntry([]byte(fmt.Sprintf("key%d", i)), v)))
if i%3 == 0 {
require.NoError(t, txn.Commit())
txn = db.NewTransaction(true)
}
}
require.NoError(t, txn.Commit(), "error while committing txn")
for i := 0; i < 500; i++ {
// use Entry.WithDiscard() to delete entries, because this causes data to be flushed on
// disk, creating SSTs. Simple Delete was having data in Memtables only.
err = db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry([]byte(fmt.Sprintf("key%d", i)), v).WithDiscard())
})
require.NoError(t, err)
}
// Wait for invocation of updateDiscardStats at least once -- timeout after 60 seconds.
waitForMessage(tChan, updateDiscardStatsMsg, 1, 60, t)
db.vlog.discardStats.Lock()
require.True(t, db.vlog.discardStats.Len() > 1, "some discardStats should be generated")
db.vlog.discardStats.Unlock()
require.NoError(t, db.Close())
// Avoid running compactors on reopening badger.
opt.NumCompactors = 0
db, err = Open(opt)
require.NoError(t, err)
defer db.Close()
waitForMessage(tChan, endVLogInitMsg, 1, 60, t)
db.vlog.discardStats.Lock()
statsMap := make(map[uint64]uint64)
db.vlog.discardStats.Iterate(func(fid, val uint64) {
statsMap[fid] = val
})
require.Truef(t, reflect.DeepEqual(capturedDiscardStats, statsMap),
"Discard maps are not equal. On Close: %+v, After Reopen: %+v",
capturedDiscardStats, statsMap)
db.vlog.discardStats.Unlock()
}
func TestValueChecksums(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
// Set up SST with K1=V1
opts := getTestOptions(dir)
opts.ValueLogFileSize = 100 * 1024 * 1024 // 100Mb
opts.VerifyValueChecksum = true
kv, err := Open(opts)
require.NoError(t, err)
require.NoError(t, kv.Close())
var (
k0 = []byte("k0")
k1 = []byte("k1")
k2 = []byte("k2")
k3 = []byte("k3")
v0 = []byte("value0-012345678901234567890123012345678901234567890123")
v1 = []byte("value1-012345678901234567890123012345678901234567890123")
v2 = []byte("value2-012345678901234567890123012345678901234567890123")
v3 = []byte("value3-012345678901234567890123012345678901234567890123")
)
// Use a vlog with K0=V0 and a (corrupted) second transaction(k1,k2)
buf, offset := createMemFile(t, []*Entry{
{Key: k0, Value: v0},
{Key: k1, Value: v1},
{Key: k2, Value: v2},
})
buf[offset-1]++ // Corrupt last byte
require.NoError(t, os.WriteFile(kv.mtFilePath(1), buf, 0777))
// K1 should exist, but K2 shouldn't.
kv, err = Open(opts)
require.NoError(t, err)
require.NoError(t, kv.View(func(txn *Txn) error {
// Replay should have added K0.
item, err := txn.Get(k0)
require.NoError(t, err)
require.Equal(t, getItemValue(t, item), v0)
_, err = txn.Get(k1)
require.Equal(t, ErrKeyNotFound, err)
_, err = txn.Get(k2)
require.Equal(t, ErrKeyNotFound, err)
return nil
}))
// Write K3 at the end of the vlog.
txnSet(t, kv, k3, v3, 0)
require.NoError(t, kv.Close())
// The DB should contain K0 and K3 (K1 and k2 was lost when Badger started up
// last due to checksum failure).
kv, err = Open(opts)
require.NoError(t, err)
{
txn := kv.NewTransaction(false)
iter := txn.NewIterator(DefaultIteratorOptions)
iter.Seek(k0)
require.True(t, iter.Valid())
it := iter.Item()
require.Equal(t, it.Key(), k0)
require.Equal(t, getItemValue(t, it), v0)
iter.Next()
require.True(t, iter.Valid())
it = iter.Item()
require.Equal(t, it.Key(), k3)
require.Equal(t, getItemValue(t, it), v3)
iter.Close()
txn.Discard()
}
require.NoError(t, kv.Close())
}
// TODO: Do we need this test?
func TestPartialAppendToWAL(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
// Create skeleton files.
opts := getTestOptions(dir)
opts.ValueLogFileSize = 100 * 1024 * 1024 // 100Mb
opts.ValueThreshold = 32
kv, err := Open(opts)
require.NoError(t, err)
require.NoError(t, kv.Close())
var (
k0 = []byte("k0")
k1 = []byte("k1")
k2 = []byte("k2")
k3 = []byte("k3")
v0 = []byte("value0-01234567890123456789012012345678901234567890123")
v1 = []byte("value1-01234567890123456789012012345678901234567890123")
v2 = []byte("value2-01234567890123456789012012345678901234567890123")
v3 = []byte("value3-01234567890123456789012012345678901234567890123")
)
// Values need to be long enough to actually get written to value log.
require.True(t, int64(len(v3)) >= kv.vlog.db.valueThreshold())
// Create truncated vlog to simulate a partial append.
// k0 - single transaction, k1 and k2 in another transaction
buf, offset := createMemFile(t, []*Entry{
{Key: k0, Value: v0},
{Key: k1, Value: v1},
{Key: k2, Value: v2},
})
buf = buf[:offset-6]
require.NoError(t, os.WriteFile(kv.mtFilePath(1), buf, 0777))
// Badger should now start up
kv, err = Open(opts)
require.NoError(t, err)
require.NoError(t, kv.View(func(txn *Txn) error {
item, err := txn.Get(k0)
require.NoError(t, err)
require.Equal(t, v0, getItemValue(t, item))
_, err = txn.Get(k1)
require.Equal(t, ErrKeyNotFound, err)
_, err = txn.Get(k2)
require.Equal(t, ErrKeyNotFound, err)
return nil
}))
// When K3 is set, it should be persisted after a restart.
txnSet(t, kv, k3, v3, 0)
require.NoError(t, kv.Close())
kv, err = Open(opts)
require.NoError(t, err)
checkKeys(t, kv, [][]byte{k3})
// Replay value log from beginning, badger head is past k2.
require.NoError(t, kv.vlog.Close())
}
func TestReadOnlyOpenWithPartialAppendToWAL(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
// Create skeleton files.
opts := getTestOptions(dir)
opts.ValueLogFileSize = 100 * 1024 * 1024 // 100Mb
kv, err := Open(opts)
require.NoError(t, err)
require.NoError(t, kv.Close())
var (
k0 = []byte("k0")
k1 = []byte("k1")
k2 = []byte("k2")
v0 = []byte("value0-012345678901234567890123")
v1 = []byte("value1-012345678901234567890123")
v2 = []byte("value2-012345678901234567890123")
)
// Create truncated vlog to simulate a partial append.
// k0 - single transaction, k1 and k2 in another transaction
buf, offset := createMemFile(t, []*Entry{
{Key: k0, Value: v0},
{Key: k1, Value: v1},
{Key: k2, Value: v2},
})
buf = buf[:offset-6]
require.NoError(t, os.WriteFile(kv.mtFilePath(1), buf, 0777))
opts.ReadOnly = true
// Badger should fail a read-only open with values to replay
_, err = Open(opts)
require.Error(t, err)
require.Regexp(t, "Log truncate required", err.Error())
}
func TestValueLogTrigger(t *testing.T) {
t.Skip("Difficult to trigger compaction, so skipping. Re-enable after fixing #226")
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := getTestOptions(dir)
opt.ValueLogFileSize = 1 << 20
kv, err := Open(opt)
require.NoError(t, err)
// Write a lot of data, so it creates some work for valug log GC.
sz := 32 << 10
txn := kv.NewTransaction(true)
for i := 0; i < 100; i++ {
v := make([]byte, sz)
rand.Read(v[:rand.Intn(sz)])
require.NoError(t, txn.SetEntry(NewEntry([]byte(fmt.Sprintf("key%d", i)), v)))
if i%20 == 0 {
require.NoError(t, txn.Commit())
txn = kv.NewTransaction(true)
}
}
require.NoError(t, txn.Commit())
for i := 0; i < 45; i++ {
txnDelete(t, kv, []byte(fmt.Sprintf("key%d", i)))
}
require.NoError(t, kv.RunValueLogGC(0.5))
require.NoError(t, kv.Close())
err = kv.RunValueLogGC(0.5)
require.Equal(t, ErrRejected, err, "Error should be returned after closing DB.")
}
// createMemFile creates a new memFile and returns the last valid offset.
func createMemFile(t *testing.T, entries []*Entry) ([]byte, uint32) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opts := getTestOptions(dir)
opts.ValueLogFileSize = 100 * 1024 * 1024 // 100Mb
kv, err := Open(opts)
require.NoError(t, err)
defer kv.Close()
txnSet(t, kv, entries[0].Key, entries[0].Value, entries[0].meta)
entries = entries[1:]
txn := kv.NewTransaction(true)
for _, entry := range entries {
require.NoError(t, txn.SetEntry(NewEntry(entry.Key, entry.Value).WithMeta(entry.meta)))
}
require.NoError(t, txn.Commit())
filename := kv.mtFilePath(1)
buf, err := os.ReadFile(filename)
require.NoError(t, err)
return buf, kv.mt.wal.writeAt
}
// This test creates two mem files and corrupts the last bit of the first file.
func TestPenultimateMemCorruption(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := getTestOptions(dir)
db0, err := Open(opt)
require.NoError(t, err)
defer func() { require.NoError(t, db0.Close()) }()
h := testHelper{db: db0, t: t}
h.writeRange(0, 2) // 00001.mem
// Move the current memtable to the db.imm and create a new memtable so
// that we can have more than one mem files.
require.Zero(t, len(db0.imm))
db0.imm = append(db0.imm, db0.mt)
db0.mt, err = db0.newMemTable()
require.NoError(t, err)
h.writeRange(3, 7) // 00002.mem
// Verify we have all the data we wrote.
h.readRange(0, 7)
for i := 2; i >= 1; i-- {
fpath := db0.mtFilePath(i)
fi, err := os.Stat(fpath)
require.NoError(t, err)
require.True(t, fi.Size() > 0, "Empty file at log=%d", i)
if i == 1 {
// This should corrupt the last entry in the first memtable (that is entry number 2)
wal := db0.imm[0].wal
_, err = wal.Fd.WriteAt([]byte{0}, int64(wal.writeAt-1))
require.NoError(t, err)
// We have corrupted the file. We can remove it. If we don't remove
// the imm here, the db.close in defer will crash since db0.mt !=
// db0.imm[0]
db0.imm = db0.imm[:0]
}
}
// Simulate a crash by not closing db0, but releasing the locks.
if db0.dirLockGuard != nil {
require.NoError(t, db0.dirLockGuard.release())
db0.dirLockGuard = nil
}
if db0.valueDirGuard != nil {
require.NoError(t, db0.valueDirGuard.release())
db0.valueDirGuard = nil
}
db1, err := Open(opt)
require.NoError(t, err)
h.db = db1
// Only 2 should be gone because it is at the end of 0001.mem (first memfile).
h.readRange(0, 1)
h.readRange(3, 7)
err = db1.View(func(txn *Txn) error {
_, err := txn.Get(h.key(2)) // Verify that 2 is gone.
require.Equal(t, ErrKeyNotFound, err)
return nil
})
require.NoError(t, err)
require.NoError(t, db1.Close())
}
func checkKeys(t *testing.T, kv *DB, keys [][]byte) {
i := 0
txn := kv.NewTransaction(false)
defer txn.Discard()
iter := txn.NewIterator(IteratorOptions{})
defer iter.Close()
for iter.Seek(keys[0]); iter.Valid(); iter.Next() {
require.Equal(t, iter.Item().Key(), keys[i])
i++
}
require.Equal(t, i, len(keys))
}
type testHelper struct {
db *DB
t *testing.T
val []byte
}
func (th *testHelper) key(i int) []byte {
return []byte(fmt.Sprintf("%010d", i))
}
func (th *testHelper) value() []byte {
if len(th.val) > 0 {
return th.val
}
th.val = make([]byte, 100)
y.Check2(rand.Read(th.val))
return th.val
}
// writeRange [from, to].
func (th *testHelper) writeRange(from, to int) {
for i := from; i <= to; i++ {
err := th.db.Update(func(txn *Txn) error {
return txn.SetEntry(NewEntry(th.key(i), th.value()))
})
require.NoError(th.t, err)
}
}
func (th *testHelper) readRange(from, to int) {
for i := from; i <= to; i++ {
err := th.db.View(func(txn *Txn) error {
item, err := txn.Get(th.key(i))
if err != nil {
return err
}
return item.Value(func(val []byte) error {
require.Equal(th.t, val, th.value(), "key=%q", th.key(i))
return nil
})
})
require.NoError(th.t, err, "key=%q", th.key(i))
}
}
// Test Bug #578, which showed that if a value is moved during value log GC, an
// older version can end up at a higher level in the LSM tree than a newer
// version, causing the data to not be returned.
func TestBug578(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
y.Check(err)
defer removeDir(dir)
db, err := Open(DefaultOptions(dir).
WithValueLogMaxEntries(64).
WithBaseTableSize(1 << 13))
require.NoError(t, err)
h := testHelper{db: db, t: t}
// Let's run this whole thing a few times.
for j := 0; j < 10; j++ {
t.Logf("Cycle: %d\n", j)
h.writeRange(0, 32)
h.writeRange(0, 10)
h.writeRange(50, 72)
h.writeRange(40, 72)
h.writeRange(40, 72)
// Run value log GC a few times.
for i := 0; i < 5; i++ {
if err := db.RunValueLogGC(0.5); err != nil && !errors.Is(ErrNoRewrite, err) {
require.NoError(t, err)
}
}
h.readRange(0, 10)
}
require.NoError(t, db.Close())
}
func BenchmarkReadWrite(b *testing.B) {
rwRatio := []float32{
0.1, 0.2, 0.5, 1.0,
}
valueSize := []int{
64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384,
}
for _, vsz := range valueSize {
for _, rw := range rwRatio {
b.Run(fmt.Sprintf("%3.1f,%04d", rw, vsz), func(b *testing.B) {
dir, err := os.MkdirTemp("", "vlog-benchmark")
y.Check(err)
defer removeDir(dir)
opts := getTestOptions(dir)
opts.ValueThreshold = 0
db, err := Open(opts)
y.Check(err)
defer db.Close()
vl := &db.vlog
b.ResetTimer()
for i := 0; i < b.N; i++ {
e := new(Entry)
e.Key = make([]byte, 16)
e.Value = make([]byte, vsz)
bl := new(request)
bl.Entries = []*Entry{e}
var ptrs []valuePointer
_ = vl.write([]*request{bl})
ptrs = append(ptrs, bl.Ptrs...)
f := rand.Float32()
if f < rw {
_ = vl.write([]*request{bl})
} else {
ln := len(ptrs)
if ln == 0 {
b.Fatalf("Zero length of ptrs")
}
idx := rand.Intn(ln)
buf, lf, err := vl.readValueBytes(ptrs[idx])
if err != nil {
b.Fatalf("Benchmark Read: %v", err)
}
e, err := lf.decodeEntry(buf, ptrs[idx].Offset)
require.NoError(b, err)
if len(e.Key) != 16 {
b.Fatalf("Key is invalid")
}
if len(e.Value) != vsz {
b.Fatalf("Value is invalid")
}
runCallback(db.vlog.getUnlockCallback(lf))
}
}
})
}
}
}
// Regression test for https://github.com/dgraph-io/badger/issues/817
// This test verifies if fully corrupted memtables are deleted on reopen.
func TestValueLogTruncate(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
// Initialize the data directory.
db, err := Open(DefaultOptions(dir))
require.NoError(t, err)
// Insert 1 entry so that we have valid data in first mem file
require.NoError(t, db.Update(func(txn *Txn) error {
return txn.Set([]byte("foo"), nil)
}))
fileCountBeforeCorruption := 1
require.NoError(t, db.Close())
// Create two mem files with corrupted data. These will be truncated when DB starts next time
require.NoError(t, os.WriteFile(db.mtFilePath(2), []byte("foo"), 0664))
require.NoError(t, os.WriteFile(db.mtFilePath(3), []byte("foo"), 0664))
db, err = Open(DefaultOptions(dir))
require.NoError(t, err)
// Ensure we have only one SST file.
require.Equal(t, 1, len(db.Tables()))
// Ensure mem file with ID 4 is zero.
require.Equal(t, 4, int(db.mt.wal.fid))
fileStat, err := db.mt.wal.Fd.Stat()
require.NoError(t, err)
require.Equal(t, 2*db.opt.MemTableSize, fileStat.Size())
fileCountAfterCorruption := len(db.Tables()) + len(db.imm) + 1 // +1 for db.mt
// We should have one memtable and one sst file.
require.Equal(t, fileCountBeforeCorruption+1, fileCountAfterCorruption)
// maxFid will be 2 because we increment the max fid on DB open every time.
require.Equal(t, 2, int(db.vlog.maxFid))
require.NoError(t, db.Close())
}
func TestSafeEntry(t *testing.T) {
var s safeRead
s.lf = &logFile{}
e := NewEntry([]byte("foo"), []byte("bar"))
buf := bytes.NewBuffer(nil)
_, err := s.lf.encodeEntry(buf, e, 0)
require.NoError(t, err)
ne, err := s.Entry(buf)
require.NoError(t, err)
require.Equal(t, e.Key, ne.Key, "key mismatch")
require.Equal(t, e.Value, ne.Value, "value mismatch")
require.Equal(t, e.meta, ne.meta, "meta mismatch")
require.Equal(t, e.UserMeta, ne.UserMeta, "usermeta mismatch")
require.Equal(t, e.ExpiresAt, ne.ExpiresAt, "expiresAt mismatch")
}
func TestValueEntryChecksum(t *testing.T) {
k := []byte("KEY")
v := []byte(fmt.Sprintf("val%100d", 10))
t.Run("ok", func(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := getTestOptions(dir)
opt.VerifyValueChecksum = true
opt.ValueThreshold = 32
db, err := Open(opt)
require.NoError(t, err)
require.Greater(t, int64(len(v)), db.vlog.db.valueThreshold())
txnSet(t, db, k, v, 0)
require.NoError(t, db.Close())
db, err = Open(opt)
require.NoError(t, err)
txn := db.NewTransaction(false)
entry, err := txn.Get(k)
require.NoError(t, err)
x, err := entry.ValueCopy(nil)
require.NoError(t, err)
require.Equal(t, v, x)
require.NoError(t, db.Close())
})
// Regression test for https://github.com/dgraph-io/badger/issues/1049
t.Run("Corruption", func(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := getTestOptions(dir)
opt.VerifyValueChecksum = true
opt.ValueThreshold = 32
db, err := Open(opt)
require.NoError(t, err)
require.Greater(t, int64(len(v)), db.vlog.db.valueThreshold())
txnSet(t, db, k, v, 0)
path := db.vlog.fpath(1)
require.NoError(t, db.Close())
file, err := os.OpenFile(path, os.O_RDWR, 0644)
require.NoError(t, err)
offset := 50
orig := make([]byte, 1)
_, err = file.ReadAt(orig, int64(offset))
require.NoError(t, err)
// Corrupt a single bit.
_, err = file.WriteAt([]byte{7}, int64(offset))
require.NoError(t, err)
require.NoError(t, file.Close())
db, err = Open(opt)
require.NoError(t, err)
txn := db.NewTransaction(false)
entry, err := txn.Get(k)
require.NoError(t, err)
// TODO(ibrahim): This test is broken since we're not returning errors
// in case we cannot read the values. This is incorrect behavior but
// we're doing this to debug an issue where the values are being read
// from old vlog files.
_, _ = entry.ValueCopy(nil)
// require.Error(t, err)
// require.Contains(t, err.Error(), "ErrEOF")
// require.Nil(t, x)
require.NoError(t, db.Close())
})
}
func TestValidateWrite(t *testing.T) {
// Mocking the file size, so that we don't allocate big memory while running test.
maxVlogFileSize = 400
defer func() {
maxVlogFileSize = math.MaxUint32
}()
bigBuf := make([]byte, maxVlogFileSize+1)
log := &valueLog{
opt: DefaultOptions("."),
}
// Sending a request with big values which will overflow uint32.
key := []byte("HelloKey")
req := &request{
Entries: []*Entry{
{
Key: key,
Value: bigBuf,
},
{
Key: key,
Value: bigBuf,
},
{
Key: key,
Value: bigBuf,
},
},
}
err := log.validateWrites([]*request{req})
require.Error(t, err)
// Testing with small values.
smallBuf := make([]byte, 4)
req1 := &request{
Entries: []*Entry{
{
Key: key,
Value: smallBuf,
},
{
Key: key,
Value: smallBuf,
},
{
Key: key,
Value: smallBuf,
},
},
}
err = log.validateWrites([]*request{req1})
require.NoError(t, err)
// Batching small and big request.
err = log.validateWrites([]*request{req1, req})
require.Error(t, err)
}
func TestValueLogMeta(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
y.Check(err)
defer removeDir(dir)
opt := getTestOptions(dir).WithValueThreshold(16)
db, _ := Open(opt)
defer db.Close()
txn := db.NewTransaction(true)
for i := 0; i < 10; i++ {
k := []byte(fmt.Sprintf("key=%d", i))
v := []byte(fmt.Sprintf("val=%020d", i))
require.NoError(t, txn.SetEntry(NewEntry(k, v)))
}
require.NoError(t, txn.Commit())
fids := db.vlog.sortedFids()
require.Equal(t, 1, len(fids))
// vlog entries must not have txn meta.
_, err = db.vlog.filesMap[fids[0]].iterate(true, 0, func(e Entry, vp valuePointer) error {
require.Zero(t, e.meta&(bitTxn|bitFinTxn))
return nil
})
require.NoError(t, err)
// Entries in LSM tree must have txn bit of meta set
txn = db.NewTransaction(false)
defer txn.Discard()
iopt := DefaultIteratorOptions
key := []byte("key")
iopt.Prefix = key
itr := txn.NewIterator(iopt)
defer itr.Close()
var count int
for itr.Seek(key); itr.ValidForPrefix(key); itr.Next() {
item := itr.Item()
require.Equal(t, bitTxn, item.meta&(bitTxn|bitFinTxn))
count++
}
require.Equal(t, 10, count)
}
// This tests asserts the condition that vlog fids start from 1.
// TODO(naman): should this be changed to assert instead?
func TestFirstVlogFile(t *testing.T) {
dir, err := os.MkdirTemp("", "badger-test")
require.NoError(t, err)
defer removeDir(dir)
opt := DefaultOptions(dir)
db, err := Open(opt)
require.NoError(t, err)
defer db.Close()
fids := db.vlog.sortedFids()
require.NotZero(t, len(fids))
require.Equal(t, uint32(1), fids[0])
}
================================================
FILE: watermark_edge_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package badger
import (
"crypto/rand"
"errors"
"fmt"
"math/big"
"sync"
"testing"
"time"
)
func TestWaterMarkEdgeCase(t *testing.T) {
const N = 1_000
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
eg := make(chan error, N)
defer close(eg)
var wg sync.WaitGroup
wg.Add(N)
for i := 0; i < N; i++ {
go func(j int) {
defer wg.Done()
if err := doWork(db, j); errors.Is(err, ErrConflict) {
eg <- nil
} else {
eg <- fmt.Errorf("expected conflict not found, err: %v, i = %v", err, j)
}
}(i)
}
wg.Wait()
for i := 0; i < N; i++ {
if err := <-eg; err != nil {
t.Fatal(err)
}
}
})
}
func doWork(db *DB, i int) error {
delay()
key1 := fmt.Sprintf("v:%d:%s", i, generateRandomBytes())
key2 := fmt.Sprintf("v:%d:%s", i, generateRandomBytes())
tx1 := db.NewTransaction(true)
defer tx1.Discard()
tx2 := db.NewTransaction(true)
defer tx2.Discard()
getValue(tx2, key1)
getValue(tx2, key2)
getValue(tx1, key1)
getValue(tx2, key1)
setValue(tx2, key1, "value1")
setValue(tx2, key2, "value2")
if err := tx2.Commit(); err != nil {
return fmt.Errorf("tx2 failed: %w (key1 = %s, key2 = %s)", err, key1, key2)
}
setValue(tx1, key1, "value1-second")
getValue(tx1, key1)
setValue(tx1, key1, "value1-third")
delay()
if err := tx1.Commit(); err != nil {
return fmt.Errorf("tx1 failed: %w (key1 = %s, key2 = %s)", err, key1, key2)
}
return nil
}
func generateRandomBytes() []byte {
b := make([]byte, 20)
if _, err := rand.Read(b); err != nil {
panic(err)
}
return b
}
func getValue(txn *Txn, key string) {
if _, err := txn.Get([]byte(key)); err != nil {
if !errors.Is(err, ErrKeyNotFound) {
panic(err)
}
}
}
func setValue(txn *Txn, key, value string) {
if err := txn.Set([]byte(key), []byte(value)); err != nil {
panic(err)
}
}
func delay() {
jitter, err := rand.Int(rand.Reader, big.NewInt(100))
if err != nil {
panic(err)
}
<-time.After(time.Duration(jitter.Int64()) * time.Millisecond)
}
================================================
FILE: y/bloom.go
================================================
// Copyright 2013 The LevelDB-Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package y
import "math"
// Filter is an encoded set of []byte keys.
type Filter []byte
func (f Filter) MayContainKey(k []byte) bool {
return f.MayContain(Hash(k))
}
// MayContain returns whether the filter may contain given key. False positives
// are possible, where it returns true for keys not in the original set.
func (f Filter) MayContain(h uint32) bool {
if len(f) < 2 {
return false
}
k := f[len(f)-1]
if k > 30 {
// This is reserved for potentially new encodings for short Bloom filters.
// Consider it a match.
return true
}
nBits := uint32(8 * (len(f) - 1))
delta := h>>17 | h<<15
for j := uint8(0); j < k; j++ {
bitPos := h % nBits
if f[bitPos/8]&(1<<(bitPos%8)) == 0 {
return false
}
h += delta
}
return true
}
// NewFilter returns a new Bloom filter that encodes a set of []byte keys with
// the given number of bits per key, approximately.
//
// A good bitsPerKey value is 10, which yields a filter with ~ 1% false
// positive rate.
func NewFilter(keys []uint32, bitsPerKey int) Filter {
return Filter(appendFilter(nil, keys, bitsPerKey))
}
// BloomBitsPerKey returns the bits per key required by bloomfilter based on
// the false positive rate.
func BloomBitsPerKey(numEntries int, fp float64) int {
size := -1 * float64(numEntries) * math.Log(fp) / math.Pow(float64(0.69314718056), 2)
locs := math.Ceil(float64(0.69314718056) * size / float64(numEntries))
return int(locs)
}
func appendFilter(buf []byte, keys []uint32, bitsPerKey int) []byte {
if bitsPerKey < 0 {
bitsPerKey = 0
}
// 0.69 is approximately ln(2).
k := uint32(float64(bitsPerKey) * 0.69)
if k < 1 {
k = 1
}
if k > 30 {
k = 30
}
nBits := len(keys) * bitsPerKey
// For small len(keys), we can see a very high false positive rate. Fix it
// by enforcing a minimum bloom filter length.
if nBits < 64 {
nBits = 64
}
nBytes := (nBits + 7) / 8
nBits = nBytes * 8
buf, filter := extend(buf, nBytes+1)
for _, h := range keys {
delta := h>>17 | h<<15
for j := uint32(0); j < k; j++ {
bitPos := h % uint32(nBits)
filter[bitPos/8] |= 1 << (bitPos % 8)
h += delta
}
}
filter[nBytes] = uint8(k)
return buf
}
// extend appends n zero bytes to b. It returns the overall slice (of length
// n+len(originalB)) and the slice of n trailing zeroes.
func extend(b []byte, n int) (overall, trailer []byte) {
want := n + len(b)
if want <= cap(b) {
overall = b[:want]
trailer = overall[len(b):]
for i := range trailer {
trailer[i] = 0
}
} else {
// Grow the capacity exponentially, with a 1KiB minimum.
c := 1024
for c < want {
c += c / 4
}
overall = make([]byte, want, c)
trailer = overall[len(b):]
copy(overall, b)
}
return overall, trailer
}
// hash implements a hashing algorithm similar to the Murmur hash.
func Hash(b []byte) uint32 {
const (
seed = 0xbc9f1d34
m = 0xc6a4a793
)
h := uint32(seed) ^ uint32(len(b))*m
for ; len(b) >= 4; b = b[4:] {
h += uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
h *= m
h ^= h >> 16
}
switch len(b) {
case 3:
h += uint32(b[2]) << 16
fallthrough
case 2:
h += uint32(b[1]) << 8
fallthrough
case 1:
h += uint32(b[0])
h *= m
h ^= h >> 24
}
return h
}
// FilterPolicy implements the db.FilterPolicy interface from the leveldb/db
// package.
//
// The integer value is the approximate number of bits used per key. A good
// value is 10, which yields a filter with ~ 1% false positive rate.
//
// It is valid to use the other API in this package (leveldb/bloom) without
// using this type or the leveldb/db package.
// type FilterPolicy int
// // Name implements the db.FilterPolicy interface.
// func (p FilterPolicy) Name() string {
// // This string looks arbitrary, but its value is written to LevelDB .ldb
// // files, and should be this exact value to be compatible with those files
// // and with the C++ LevelDB code.
// return "leveldb.BuiltinBloomFilter2"
// }
// // AppendFilter implements the db.FilterPolicy interface.
// func (p FilterPolicy) AppendFilter(dst []byte, keys [][]byte) []byte {
// return appendFilter(dst, keys, int(p))
// }
// // MayContain implements the db.FilterPolicy interface.
// func (p FilterPolicy) MayContain(filter, key []byte) bool {
// return Filter(filter).MayContain(key)
// }
================================================
FILE: y/bloom_test.go
================================================
// Copyright 2013 The LevelDB-Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package y
import (
"testing"
)
func (f Filter) String() string {
s := make([]byte, 8*len(f))
for i, x := range f {
for j := 0; j < 8; j++ {
if x&(1<> 0)
b[1] = uint8(uint32(i) >> 8)
b[2] = uint8(uint32(i) >> 16)
b[3] = uint8(uint32(i) >> 24)
return b
}
nMediocreFilters, nGoodFilters := 0, 0
loop:
for length := 1; length <= 10000; length = nextLength(length) {
keys := make([][]byte, 0, length)
for i := 0; i < length; i++ {
keys = append(keys, le32(i))
}
var hashes []uint32
for _, key := range keys {
hashes = append(hashes, Hash(key))
}
f := NewFilter(hashes, 10)
if len(f) > (length*10/8)+40 {
t.Errorf("length=%d: len(f)=%d is too large", length, len(f))
continue
}
// All added keys must match.
for _, key := range keys {
if !f.MayContainKey(key) {
t.Errorf("length=%d: did not contain key %q", length, key)
continue loop
}
}
// Check false positive rate.
nFalsePositive := 0
for i := 0; i < 10000; i++ {
if f.MayContainKey(le32(1e9 + i)) {
nFalsePositive++
}
}
if nFalsePositive > 0.02*10000 {
t.Errorf("length=%d: %d false positives in 10000", length, nFalsePositive)
continue
}
if nFalsePositive > 0.0125*10000 {
nMediocreFilters++
} else {
nGoodFilters++
}
}
if nMediocreFilters > nGoodFilters/5 {
t.Errorf("%d mediocre filters but only %d good filters", nMediocreFilters, nGoodFilters)
}
}
func TestHash(t *testing.T) {
// The magic want numbers come from running the C++ leveldb code in hash.cc.
testCases := []struct {
s string
want uint32
}{
{"", 0xbc9f1d34},
{"g", 0xd04a8bda},
{"go", 0x3e0b0745},
{"gop", 0x0c326610},
{"goph", 0x8c9d6390},
{"gophe", 0x9bfd4b0a},
{"gopher", 0xa78edc7c},
{"I had a dream it would end this way.", 0xe14a9db9},
}
for _, tc := range testCases {
if got := Hash([]byte(tc.s)); got != tc.want {
t.Errorf("s=%q: got 0x%08x, want 0x%08x", tc.s, got, tc.want)
}
}
}
================================================
FILE: y/checksum.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package y
import (
stderrors "errors"
"hash/crc32"
"github.com/cespare/xxhash/v2"
"github.com/dgraph-io/badger/v4/pb"
)
// ErrChecksumMismatch is returned at checksum mismatch.
var ErrChecksumMismatch = stderrors.New("checksum mismatch")
// CalculateChecksum calculates checksum for data using ct checksum type.
func CalculateChecksum(data []byte, ct pb.Checksum_Algorithm) uint64 {
switch ct {
case pb.Checksum_CRC32C:
return uint64(crc32.Checksum(data, CastagnoliCrcTable))
case pb.Checksum_XXHash64:
return xxhash.Sum64(data)
default:
panic("checksum type not supported")
}
}
// VerifyChecksum validates the checksum for the data against the given expected checksum.
func VerifyChecksum(data []byte, expected *pb.Checksum) error {
actual := CalculateChecksum(data, expected.Algo)
if actual != expected.Sum {
return Wrapf(ErrChecksumMismatch, "actual: %d, expected: %d", actual, expected.Sum)
}
return nil
}
================================================
FILE: y/checksum_test.go
================================================
package y
import (
"hash/crc32"
"testing"
"github.com/cespare/xxhash/v2"
"github.com/dgraph-io/badger/v4/pb"
"github.com/stretchr/testify/require"
)
func TestCalculateChecksum_CRC32C(t *testing.T) {
data := []byte("hello world")
expected := uint64(crc32.Checksum(data, CastagnoliCrcTable))
got := CalculateChecksum(data, pb.Checksum_CRC32C)
require.Equal(t, expected, got)
// empty input
expectedEmpty := uint64(crc32.Checksum([]byte{}, CastagnoliCrcTable))
gotEmpty := CalculateChecksum([]byte{}, pb.Checksum_CRC32C)
require.Equal(t, expectedEmpty, gotEmpty)
}
func TestCalculateChecksum_XXHash64(t *testing.T) {
data := []byte("hello world")
expected := xxhash.Sum64(data)
got := CalculateChecksum(data, pb.Checksum_XXHash64)
require.Equal(t, expected, got)
}
func TestVerifyChecksum_Success(t *testing.T) {
data := []byte("hello world")
c1 := &pb.Checksum{Algo: pb.Checksum_CRC32C, Sum: CalculateChecksum(data, pb.Checksum_CRC32C)}
require.NoError(t, VerifyChecksum(data, c1))
c2 := &pb.Checksum{Algo: pb.Checksum_XXHash64, Sum: CalculateChecksum(data, pb.Checksum_XXHash64)}
require.NoError(t, VerifyChecksum(data, c2))
}
func TestVerifyChecksum_Mismatch(t *testing.T) {
data := []byte("x")
c := &pb.Checksum{Algo: pb.Checksum_CRC32C, Sum: 0}
err := VerifyChecksum(data, c)
require.Error(t, err)
require.Contains(t, err.Error(), "checksum mismatch")
}
func TestCalculateChecksum_UnsupportedAlgoPanics(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Fatalf("expected panic for unsupported algorithm")
}
}()
_ = CalculateChecksum([]byte("x"), pb.Checksum_Algorithm(999))
}
================================================
FILE: y/encrypt.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package y
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"io"
)
// XORBlock encrypts the given data with AES and XOR's with IV.
// Can be used for both encryption and decryption. IV is of
// AES block size.
func XORBlock(dst, src, key, iv []byte) error {
block, err := aes.NewCipher(key)
if err != nil {
return err
}
stream := cipher.NewCTR(block, iv)
stream.XORKeyStream(dst, src)
return nil
}
func XORBlockAllocate(src, key, iv []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
stream := cipher.NewCTR(block, iv)
dst := make([]byte, len(src))
stream.XORKeyStream(dst, src)
return dst, nil
}
func XORBlockStream(w io.Writer, src, key, iv []byte) error {
block, err := aes.NewCipher(key)
if err != nil {
return err
}
stream := cipher.NewCTR(block, iv)
sw := cipher.StreamWriter{S: stream, W: w}
_, err = io.Copy(sw, bytes.NewReader(src))
return Wrapf(err, "XORBlockStream")
}
// GenerateIV generates IV.
func GenerateIV() ([]byte, error) {
iv := make([]byte, aes.BlockSize)
_, err := rand.Read(iv)
return iv, err
}
================================================
FILE: y/encrypt_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package y
import (
"crypto/aes"
"crypto/rand"
"testing"
"github.com/stretchr/testify/require"
)
func TestXORBlock(t *testing.T) {
key := make([]byte, 32)
_, _ = rand.Read(key)
var iv []byte
{
b, err := aes.NewCipher(key)
require.NoError(t, err)
iv = make([]byte, b.BlockSize())
_, _ = rand.Read(iv)
t.Logf("Using %d size IV\n", len(iv))
}
src := make([]byte, 1024)
_, _ = rand.Read(src)
dst := make([]byte, 1024)
err := XORBlock(dst, src, key, iv)
require.NoError(t, err)
act := make([]byte, 1024)
err = XORBlock(act, dst, key, iv)
require.NoError(t, err)
require.Equal(t, src, act)
// Now check if we can use the same byte slice as src and dst. While this is useful to know that
// we can use src and dst as the same slice, this isn't applicable to Badger because we're
// reading data right off mmap. We should not modify that data, so we have to use a different
// slice for dst anyway.
cp := append([]byte{}, src...)
err = XORBlock(cp, cp, key, iv)
require.NoError(t, err)
require.Equal(t, dst, cp)
err = XORBlock(cp, cp, key, iv)
require.NoError(t, err)
require.Equal(t, src, cp)
}
================================================
FILE: y/error.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package y
// This file contains some functions for error handling. Note that we are moving
// towards using x.Trace, i.e., rpc tracing using net/tracer. But for now, these
// functions are useful for simple checks logged on one machine.
// Some common use cases are:
// (1) You receive an error from external lib, and would like to check/log fatal.
// For this, use x.Check, x.Checkf. These will check for err != nil, which is
// more common in Go. If you want to check for boolean being true, use
// x.Assert, x.Assertf.
// (2) You receive an error from external lib, and would like to pass on with some
// stack trace information. In this case, use x.Wrap or x.Wrapf.
// (3) You want to generate a new error with stack trace info. Use x.Errorf.
import (
"errors"
"fmt"
"log"
)
var debugMode = false
// Check logs fatal if err != nil.
func Check(err error) {
if err != nil {
log.Fatalf("%+v", Wrap(err, ""))
}
}
// Check2 acts as convenience wrapper around Check, using the 2nd argument as error.
func Check2(_ interface{}, err error) {
Check(err)
}
// AssertTrue asserts that b is true. Otherwise, it would log fatal.
func AssertTrue(b bool) {
if !b {
log.Fatalf("%+v", errors.New("Assert failed"))
}
}
// AssertTruef is AssertTrue with extra info.
func AssertTruef(b bool, format string, args ...interface{}) {
if !b {
log.Fatalf("%+v", fmt.Errorf(format, args...))
}
}
// Wrap wraps errors from external lib.
func Wrap(err error, msg string) error {
if !debugMode {
if err == nil {
return nil
}
return fmt.Errorf("%s err: %+v", msg, err)
}
return fmt.Errorf("%s: %w", msg, err)
}
// Wrapf is Wrap with extra info.
func Wrapf(err error, format string, args ...interface{}) error {
return Wrap(err, fmt.Sprintf(format, args...))
}
func CombineErrors(one, other error) error {
if one != nil && other != nil {
return fmt.Errorf("%v; %v", one, other)
}
if one != nil && other == nil {
return fmt.Errorf("%v", one)
}
if one == nil && other != nil {
return fmt.Errorf("%v", other)
}
return nil
}
================================================
FILE: y/error_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package y
import (
"errors"
"testing"
"github.com/stretchr/testify/require"
)
func TestCombineWithBothErrorsPresent(t *testing.T) {
combinedError := CombineErrors(errors.New("one"), errors.New("two"))
require.Equal(t, "one; two", combinedError.Error())
}
func TestCombineErrorsWithOneErrorPresent(t *testing.T) {
combinedError := CombineErrors(errors.New("one"), nil)
require.Equal(t, "one", combinedError.Error())
}
func TestCombineErrorsWithOtherErrorPresent(t *testing.T) {
combinedError := CombineErrors(nil, errors.New("other"))
require.Equal(t, "other", combinedError.Error())
}
func TestCombineErrorsWithBothErrorsAsNil(t *testing.T) {
combinedError := CombineErrors(nil, nil)
require.NoError(t, combinedError)
}
================================================
FILE: y/file_dsync.go
================================================
//go:build !dragonfly && !freebsd && !windows && !plan9 && !js && !wasip1
// +build !dragonfly,!freebsd,!windows,!plan9,!js,!wasip1
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package y
import "golang.org/x/sys/unix"
func init() {
datasyncFileFlag = unix.O_DSYNC
}
================================================
FILE: y/file_nodsync.go
================================================
//go:build dragonfly || freebsd || windows || plan9
// +build dragonfly freebsd windows plan9
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package y
import "syscall"
func init() {
datasyncFileFlag = syscall.O_SYNC
}
================================================
FILE: y/iterator.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package y
import (
"bytes"
"encoding/binary"
)
// ValueStruct represents the value info that can be associated with a key, but also the internal
// Meta field.
type ValueStruct struct {
Meta byte
UserMeta byte
ExpiresAt uint64
Value []byte
Version uint64 // This field is not serialized. Only for internal usage.
}
func sizeVarint(x uint64) (n int) {
for {
n++
x >>= 7
if x == 0 {
break
}
}
return n
}
// EncodedSize is the size of the ValueStruct when encoded
func (v *ValueStruct) EncodedSize() uint32 {
sz := len(v.Value) + 2 // meta, usermeta.
enc := sizeVarint(v.ExpiresAt)
return uint32(sz + enc)
}
// Decode uses the length of the slice to infer the length of the Value field.
func (v *ValueStruct) Decode(b []byte) {
v.Meta = b[0]
v.UserMeta = b[1]
var sz int
v.ExpiresAt, sz = binary.Uvarint(b[2:])
v.Value = b[2+sz:]
}
// Encode expects a slice of length at least v.EncodedSize().
func (v *ValueStruct) Encode(b []byte) uint32 {
b[0] = v.Meta
b[1] = v.UserMeta
sz := binary.PutUvarint(b[2:], v.ExpiresAt)
n := copy(b[2+sz:], v.Value)
return uint32(2 + sz + n)
}
// EncodeTo should be kept in sync with the Encode function above. The reason
// this function exists is to avoid creating byte arrays per key-value pair in
// table/builder.go.
func (v *ValueStruct) EncodeTo(buf *bytes.Buffer) {
buf.WriteByte(v.Meta)
buf.WriteByte(v.UserMeta)
var enc [binary.MaxVarintLen64]byte
sz := binary.PutUvarint(enc[:], v.ExpiresAt)
buf.Write(enc[:sz])
buf.Write(v.Value)
}
// Iterator is an interface for a basic iterator.
type Iterator interface {
Next()
Rewind()
Seek(key []byte)
Key() []byte
Value() ValueStruct
Valid() bool
// All iterators should be closed so that file garbage collection works.
Close() error
}
================================================
FILE: y/metrics.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package y
import (
"expvar"
)
const (
BADGER_METRIC_PREFIX = "badger_"
)
var (
// lsmSize has size of the LSM in bytes
lsmSize *expvar.Map
// vlogSize has size of the value log in bytes
vlogSize *expvar.Map
// pendingWrites tracks the number of pending writes.
pendingWrites *expvar.Map
// These are cumulative
// VLOG METRICS
// numReads has cumulative number of reads from vlog
numReadsVlog *expvar.Int
// numWrites has cumulative number of writes into vlog
numWritesVlog *expvar.Int
// numBytesRead has cumulative number of bytes read from VLOG
numBytesReadVlog *expvar.Int
// numBytesVlogWritten has cumulative number of bytes written into VLOG
numBytesVlogWritten *expvar.Int
// LSM METRICS
// numBytesRead has cumulative number of bytes read from LSM tree
numBytesReadLSM *expvar.Int
// numBytesWrittenToL0 has cumulative number of bytes written into LSM Tree
numBytesWrittenToL0 *expvar.Int
// numLSMGets is number of LSM gets
numLSMGets *expvar.Map
// numBytesCompactionWritten is the number of bytes written in the lsm tree due to compaction
numBytesCompactionWritten *expvar.Map
// numLSMBloomHits is number of LMS bloom hits
numLSMBloomHits *expvar.Map
// DB METRICS
// numGets is number of gets -> Number of get requests made
numGets *expvar.Int
// number of get queries in which we actually get a result
numGetsWithResults *expvar.Int
// number of iterators created, these would be the number of range queries
numIteratorsCreated *expvar.Int
// numPuts is number of puts -> Number of puts requests made
numPuts *expvar.Int
// numMemtableGets is number of memtable gets -> Number of get requests made on memtable
numMemtableGets *expvar.Int
// numCompactionTables is the number of tables being compacted
numCompactionTables *expvar.Int
// Total writes by a user in bytes
numBytesWrittenUser *expvar.Int
)
// These variables are global and have cumulative values for all kv stores.
// Naming convention of metrics: {badger_version}_{singular operation}_{granularity}_{component}
func init() {
numReadsVlog = expvar.NewInt(BADGER_METRIC_PREFIX + "read_num_vlog")
numBytesReadVlog = expvar.NewInt(BADGER_METRIC_PREFIX + "read_bytes_vlog")
numWritesVlog = expvar.NewInt(BADGER_METRIC_PREFIX + "write_num_vlog")
numBytesVlogWritten = expvar.NewInt(BADGER_METRIC_PREFIX + "write_bytes_vlog")
numBytesReadLSM = expvar.NewInt(BADGER_METRIC_PREFIX + "read_bytes_lsm")
numBytesWrittenToL0 = expvar.NewInt(BADGER_METRIC_PREFIX + "write_bytes_l0")
numBytesCompactionWritten = expvar.NewMap(BADGER_METRIC_PREFIX + "write_bytes_compaction")
numLSMGets = expvar.NewMap(BADGER_METRIC_PREFIX + "get_num_lsm")
numLSMBloomHits = expvar.NewMap(BADGER_METRIC_PREFIX + "hit_num_lsm_bloom_filter")
numMemtableGets = expvar.NewInt(BADGER_METRIC_PREFIX + "get_num_memtable")
// User operations
numGets = expvar.NewInt(BADGER_METRIC_PREFIX + "get_num_user")
numPuts = expvar.NewInt(BADGER_METRIC_PREFIX + "put_num_user")
numBytesWrittenUser = expvar.NewInt(BADGER_METRIC_PREFIX + "write_bytes_user")
// Required for Enabled
numGetsWithResults = expvar.NewInt(BADGER_METRIC_PREFIX + "get_with_result_num_user")
numIteratorsCreated = expvar.NewInt(BADGER_METRIC_PREFIX + "iterator_num_user")
// Sizes
lsmSize = expvar.NewMap(BADGER_METRIC_PREFIX + "size_bytes_lsm")
vlogSize = expvar.NewMap(BADGER_METRIC_PREFIX + "size_bytes_vlog")
pendingWrites = expvar.NewMap(BADGER_METRIC_PREFIX + "write_pending_num_memtable")
numCompactionTables = expvar.NewInt(BADGER_METRIC_PREFIX + "compaction_current_num_lsm")
}
func NumIteratorsCreatedAdd(enabled bool, val int64) {
addInt(enabled, numIteratorsCreated, val)
}
func NumGetsWithResultsAdd(enabled bool, val int64) {
addInt(enabled, numGetsWithResults, val)
}
func NumReadsVlogAdd(enabled bool, val int64) {
addInt(enabled, numReadsVlog, val)
}
func NumBytesWrittenUserAdd(enabled bool, val int64) {
addInt(enabled, numBytesWrittenUser, val)
}
func NumWritesVlogAdd(enabled bool, val int64) {
addInt(enabled, numWritesVlog, val)
}
func NumBytesReadsVlogAdd(enabled bool, val int64) {
addInt(enabled, numBytesReadVlog, val)
}
func NumBytesReadsLSMAdd(enabled bool, val int64) {
addInt(enabled, numBytesReadLSM, val)
}
func NumBytesWrittenVlogAdd(enabled bool, val int64) {
addInt(enabled, numBytesVlogWritten, val)
}
func NumBytesWrittenToL0Add(enabled bool, val int64) {
addInt(enabled, numBytesWrittenToL0, val)
}
func NumBytesCompactionWrittenAdd(enabled bool, key string, val int64) {
addToMap(enabled, numBytesCompactionWritten, key, val)
}
func NumGetsAdd(enabled bool, val int64) {
addInt(enabled, numGets, val)
}
func NumPutsAdd(enabled bool, val int64) {
addInt(enabled, numPuts, val)
}
func NumMemtableGetsAdd(enabled bool, val int64) {
addInt(enabled, numMemtableGets, val)
}
func NumCompactionTablesAdd(enabled bool, val int64) {
addInt(enabled, numCompactionTables, val)
}
func LSMSizeSet(enabled bool, key string, val expvar.Var) {
storeToMap(enabled, lsmSize, key, val)
}
func VlogSizeSet(enabled bool, key string, val expvar.Var) {
storeToMap(enabled, vlogSize, key, val)
}
func PendingWritesSet(enabled bool, key string, val expvar.Var) {
storeToMap(enabled, pendingWrites, key, val)
}
func NumLSMBloomHitsAdd(enabled bool, key string, val int64) {
addToMap(enabled, numLSMBloomHits, key, val)
}
func NumLSMGetsAdd(enabled bool, key string, val int64) {
addToMap(enabled, numLSMGets, key, val)
}
func LSMSizeGet(enabled bool, key string) expvar.Var {
return getFromMap(enabled, lsmSize, key)
}
func VlogSizeGet(enabled bool, key string) expvar.Var {
return getFromMap(enabled, vlogSize, key)
}
func addInt(enabled bool, metric *expvar.Int, val int64) {
if !enabled {
return
}
metric.Add(val)
}
func addToMap(enabled bool, metric *expvar.Map, key string, val int64) {
if !enabled {
return
}
metric.Add(key, val)
}
func storeToMap(enabled bool, metric *expvar.Map, key string, val expvar.Var) {
if !enabled {
return
}
metric.Set(key, val)
}
func getFromMap(enabled bool, metric *expvar.Map, key string) expvar.Var {
if !enabled {
return nil
}
return metric.Get(key)
}
================================================
FILE: y/watermark.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package y
import (
"container/heap"
"context"
"sync/atomic"
"github.com/dgraph-io/ristretto/v2/z"
)
type uint64Heap []uint64
func (u uint64Heap) Len() int { return len(u) }
func (u uint64Heap) Less(i, j int) bool { return u[i] < u[j] }
func (u uint64Heap) Swap(i, j int) { u[i], u[j] = u[j], u[i] }
func (u *uint64Heap) Push(x interface{}) { *u = append(*u, x.(uint64)) }
func (u *uint64Heap) Pop() interface{} {
old := *u
n := len(old)
x := old[n-1]
*u = old[0 : n-1]
return x
}
// mark contains one of more indices, along with a done boolean to indicate the
// status of the index: begin or done. It also contains waiters, who could be
// waiting for the watermark to reach >= a certain index.
type mark struct {
// Either this is an (index, waiter) pair or (index, done) or (indices, done).
index uint64
waiter chan struct{}
indices []uint64
done bool // Set to true if the index is done.
}
// WaterMark is used to keep track of the minimum un-finished index. Typically, an index k becomes
// finished or "done" according to a WaterMark once Done(k) has been called
// 1. as many times as Begin(k) has, AND
// 2. a positive number of times.
//
// An index may also become "done" by calling SetDoneUntil at a time such that it is not
// inter-mingled with Begin/Done calls.
//
// Since doneUntil and lastIndex addresses are passed to sync/atomic packages, we ensure that they
// are 64-bit aligned by putting them at the beginning of the structure.
type WaterMark struct {
doneUntil atomic.Uint64
lastIndex atomic.Uint64
Name string
markCh chan mark
}
// Init initializes a WaterMark struct. MUST be called before using it.
func (w *WaterMark) Init(closer *z.Closer) {
w.markCh = make(chan mark, 100)
go w.process(closer)
}
// Begin sets the last index to the given value.
func (w *WaterMark) Begin(index uint64) {
w.lastIndex.Store(index)
w.markCh <- mark{index: index, done: false}
}
// BeginMany works like Begin but accepts multiple indices.
func (w *WaterMark) BeginMany(indices []uint64) {
w.lastIndex.Store(indices[len(indices)-1])
w.markCh <- mark{index: 0, indices: indices, done: false}
}
// Done sets a single index as done.
func (w *WaterMark) Done(index uint64) {
w.markCh <- mark{index: index, done: true}
}
// DoneMany works like Done but accepts multiple indices.
func (w *WaterMark) DoneMany(indices []uint64) {
w.markCh <- mark{index: 0, indices: indices, done: true}
}
// DoneUntil returns the maximum index that has the property that all indices
// less than or equal to it are done.
func (w *WaterMark) DoneUntil() uint64 {
return w.doneUntil.Load()
}
// SetDoneUntil sets the maximum index that has the property that all indices
// less than or equal to it are done.
func (w *WaterMark) SetDoneUntil(val uint64) {
w.doneUntil.Store(val)
}
// LastIndex returns the last index for which Begin has been called.
func (w *WaterMark) LastIndex() uint64 {
return w.lastIndex.Load()
}
// WaitForMark waits until the given index is marked as done.
func (w *WaterMark) WaitForMark(ctx context.Context, index uint64) error {
if w.DoneUntil() >= index {
return nil
}
waitCh := make(chan struct{})
w.markCh <- mark{index: index, waiter: waitCh}
select {
case <-ctx.Done():
return ctx.Err()
case <-waitCh:
return nil
}
}
// process is used to process the Mark channel. This is not thread-safe,
// so only run one goroutine for process. One is sufficient, because
// all goroutine ops use purely memory and cpu.
// Each index has to emit at least one begin watermark in serial order otherwise waiters
// can get blocked idefinitely. Example: We had an watermark at 100 and a waiter at 101,
// if no watermark is emitted at index 101 then waiter would get stuck indefinitely as it
// can't decide whether the task at 101 has decided not to emit watermark or it didn't get
// scheduled yet.
func (w *WaterMark) process(closer *z.Closer) {
defer closer.Done()
var indices uint64Heap
// pending maps raft proposal index to the number of pending mutations for this proposal.
pending := make(map[uint64]int)
waiters := make(map[uint64][]chan struct{})
heap.Init(&indices)
processOne := func(index uint64, done bool) {
// If not already done, then set. Otherwise, don't undo a done entry.
prev, present := pending[index]
if !present {
heap.Push(&indices, index)
}
delta := 1
if done {
delta = -1
}
pending[index] = prev + delta
// Update mark by going through all indices in order; and checking if they have
// been done. Stop at the first index, which isn't done.
doneUntil := w.DoneUntil()
if doneUntil > index {
AssertTruef(false, "Name: %s doneUntil: %d. Index: %d", w.Name, doneUntil, index)
}
until := doneUntil
loops := 0
for len(indices) > 0 {
min := indices[0]
if done := pending[min]; done > 0 {
break // len(indices) will be > 0.
}
// Even if done is called multiple times causing it to become
// negative, we should still pop the index.
heap.Pop(&indices)
delete(pending, min)
until = min
loops++
}
if until != doneUntil {
AssertTrue(w.doneUntil.CompareAndSwap(doneUntil, until))
}
notifyAndRemove := func(idx uint64, toNotify []chan struct{}) {
for _, ch := range toNotify {
close(ch)
}
delete(waiters, idx) // Release the memory back.
}
if until-doneUntil <= uint64(len(waiters)) {
// Issue #908 showed that if doneUntil is close to 2^60, while until is zero, this loop
// can hog up CPU just iterating over integers creating a busy-wait loop. So, only do
// this path if until - doneUntil is less than the number of waiters.
for idx := doneUntil + 1; idx <= until; idx++ {
if toNotify, ok := waiters[idx]; ok {
notifyAndRemove(idx, toNotify)
}
}
} else {
for idx, toNotify := range waiters {
if idx <= until {
notifyAndRemove(idx, toNotify)
}
}
} // end of notifying waiters.
}
for {
select {
case <-closer.HasBeenClosed():
return
case mark := <-w.markCh:
if mark.waiter != nil {
doneUntil := w.doneUntil.Load()
if doneUntil >= mark.index {
close(mark.waiter)
} else {
ws, ok := waiters[mark.index]
if !ok {
waiters[mark.index] = []chan struct{}{mark.waiter}
} else {
waiters[mark.index] = append(ws, mark.waiter)
}
}
} else {
// it is possible that mark.index is zero. We need to handle that case as well.
if mark.index > 0 || (mark.index == 0 && len(mark.indices) == 0) {
processOne(mark.index, mark.done)
}
for _, index := range mark.indices {
processOne(index, mark.done)
}
}
}
}
}
================================================
FILE: y/y.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package y
import (
"bytes"
"encoding/binary"
stderrors "errors"
"fmt"
"hash/crc32"
"io"
"math"
"os"
"reflect"
"strconv"
"sync"
"time"
"unsafe"
"github.com/dgraph-io/badger/v4/pb"
"github.com/dgraph-io/ristretto/v2/z"
)
var (
// ErrEOF indicates an end of file when trying to read from a memory mapped file
// and encountering the end of slice.
ErrEOF = stderrors.New("ErrEOF: End of file")
// ErrCommitAfterFinish indicates that write batch commit was called after
// finish
ErrCommitAfterFinish = stderrors.New("Batch commit not permitted after finish")
)
type Flags int
const (
// Sync indicates that O_DSYNC should be set on the underlying file,
// ensuring that data writes do not return until the data is flushed
// to disk.
Sync Flags = 1 << iota
// ReadOnly opens the underlying file on a read-only basis.
ReadOnly
)
var (
// This is O_DSYNC (datasync) on platforms that support it -- see file_unix.go
datasyncFileFlag = 0x0
// CastagnoliCrcTable is a CRC32 polynomial table
CastagnoliCrcTable = crc32.MakeTable(crc32.Castagnoli)
)
// OpenExistingFile opens an existing file, errors if it doesn't exist.
func OpenExistingFile(filename string, flags Flags) (*os.File, error) {
openFlags := os.O_RDWR
if flags&ReadOnly != 0 {
openFlags = os.O_RDONLY
}
if flags&Sync != 0 {
openFlags |= datasyncFileFlag
}
return os.OpenFile(filename, openFlags, 0)
}
// CreateSyncedFile creates a new file (using O_EXCL), errors if it already existed.
func CreateSyncedFile(filename string, sync bool) (*os.File, error) {
flags := os.O_RDWR | os.O_CREATE | os.O_EXCL
if sync {
flags |= datasyncFileFlag
}
return os.OpenFile(filename, flags, 0600)
}
// OpenSyncedFile creates the file if one doesn't exist.
func OpenSyncedFile(filename string, sync bool) (*os.File, error) {
flags := os.O_RDWR | os.O_CREATE
if sync {
flags |= datasyncFileFlag
}
return os.OpenFile(filename, flags, 0600)
}
// OpenTruncFile opens the file with O_RDWR | O_CREATE | O_TRUNC
func OpenTruncFile(filename string, sync bool) (*os.File, error) {
flags := os.O_RDWR | os.O_CREATE | os.O_TRUNC
if sync {
flags |= datasyncFileFlag
}
return os.OpenFile(filename, flags, 0600)
}
// SafeCopy does append(a[:0], src...).
func SafeCopy(a, src []byte) []byte {
b := append(a[:0], src...)
if b == nil {
return []byte{}
}
return b
}
// Copy copies a byte slice and returns the copied slice.
func Copy(a []byte) []byte {
b := make([]byte, len(a))
copy(b, a)
return b
}
// KeyWithTs generates a new key by appending ts to key.
func KeyWithTs(key []byte, ts uint64) []byte {
out := make([]byte, len(key)+8)
copy(out, key)
binary.BigEndian.PutUint64(out[len(key):], math.MaxUint64-ts)
return out
}
// ParseTs parses the timestamp from the key bytes.
func ParseTs(key []byte) uint64 {
if len(key) <= 8 {
return 0
}
return math.MaxUint64 - binary.BigEndian.Uint64(key[len(key)-8:])
}
// CompareKeys checks the key without timestamp and checks the timestamp if keyNoTs
// is same.
// a would be sorted higher than aa if we use bytes.compare
// All keys should have timestamp.
func CompareKeys(key1, key2 []byte) int {
if cmp := bytes.Compare(key1[:len(key1)-8], key2[:len(key2)-8]); cmp != 0 {
return cmp
}
return bytes.Compare(key1[len(key1)-8:], key2[len(key2)-8:])
}
// ParseKey parses the actual key from the key bytes.
func ParseKey(key []byte) []byte {
if len(key) < 8 {
return nil
}
return key[:len(key)-8]
}
// SameKey checks for key equality ignoring the version timestamp suffix.
func SameKey(src, dst []byte) bool {
if len(src) != len(dst) {
return false
}
return bytes.Equal(ParseKey(src), ParseKey(dst))
}
// Slice holds a reusable buf, will reallocate if you request a larger size than ever before.
// One problem is with n distinct sizes in random order it'll reallocate log(n) times.
type Slice struct {
buf []byte
}
// Resize reuses the Slice's buffer (or makes a new one) and returns a slice in that buffer of
// length sz.
func (s *Slice) Resize(sz int) []byte {
if cap(s.buf) < sz {
s.buf = make([]byte, sz)
}
return s.buf[0:sz]
}
// FixedDuration returns a string representation of the given duration with the
// hours, minutes, and seconds.
func FixedDuration(d time.Duration) string {
str := fmt.Sprintf("%02ds", int(d.Seconds())%60)
if d >= time.Minute {
str = fmt.Sprintf("%02dm", int(d.Minutes())%60) + str
}
if d >= time.Hour {
str = fmt.Sprintf("%02dh", int(d.Hours())) + str
}
return str
}
// Throttle allows a limited number of workers to run at a time. It also
// provides a mechanism to check for errors encountered by workers and wait for
// them to finish.
type Throttle struct {
once sync.Once
wg sync.WaitGroup
ch chan struct{}
errCh chan error
finishErr error
}
// NewThrottle creates a new throttle with a max number of workers.
func NewThrottle(max int) *Throttle {
return &Throttle{
ch: make(chan struct{}, max),
errCh: make(chan error, max),
}
}
// Do should be called by workers before they start working. It blocks if there
// are already maximum number of workers working. If it detects an error from
// previously Done workers, it would return it.
func (t *Throttle) Do() error {
for {
select {
case t.ch <- struct{}{}:
t.wg.Add(1)
return nil
case err := <-t.errCh:
if err != nil {
return err
}
}
}
}
// Done should be called by workers when they finish working. They can also
// pass the error status of work done.
func (t *Throttle) Done(err error) {
if err != nil {
t.errCh <- err
}
select {
case <-t.ch:
default:
panic("Throttle Do Done mismatch")
}
t.wg.Done()
}
// Finish waits until all workers have finished working. It would return any error passed by Done.
// If Finish is called multiple time, it will wait for workers to finish only once(first time).
// From next calls, it will return same error as found on first call.
func (t *Throttle) Finish() error {
t.once.Do(func() {
t.wg.Wait()
close(t.ch)
close(t.errCh)
for err := range t.errCh {
if err != nil {
t.finishErr = err
return
}
}
})
return t.finishErr
}
// U16ToBytes converts the given Uint16 to bytes
func U16ToBytes(v uint16) []byte {
var uBuf [2]byte
binary.BigEndian.PutUint16(uBuf[:], v)
return uBuf[:]
}
// BytesToU16 converts the given byte slice to uint16
func BytesToU16(b []byte) uint16 {
return binary.BigEndian.Uint16(b)
}
// U32ToBytes converts the given Uint32 to bytes
func U32ToBytes(v uint32) []byte {
var uBuf [4]byte
binary.BigEndian.PutUint32(uBuf[:], v)
return uBuf[:]
}
// BytesToU32 converts the given byte slice to uint32
func BytesToU32(b []byte) uint32 {
return binary.BigEndian.Uint32(b)
}
// U32SliceToBytes converts the given Uint32 slice to byte slice
func U32SliceToBytes(u32s []uint32) []byte {
if len(u32s) == 0 {
return nil
}
var b []byte
hdr := (*reflect.SliceHeader)(unsafe.Pointer(&b))
hdr.Len = len(u32s) * 4
hdr.Cap = hdr.Len
hdr.Data = uintptr(unsafe.Pointer(&u32s[0]))
return b
}
// BytesToU32Slice converts the given byte slice to uint32 slice
func BytesToU32Slice(b []byte) []uint32 {
if len(b) == 0 {
return nil
}
var u32s []uint32
hdr := (*reflect.SliceHeader)(unsafe.Pointer(&u32s))
hdr.Len = len(b) / 4
hdr.Cap = hdr.Len
hdr.Data = uintptr(unsafe.Pointer(&b[0]))
return u32s
}
// U64ToBytes converts the given Uint64 to bytes
func U64ToBytes(v uint64) []byte {
var uBuf [8]byte
binary.BigEndian.PutUint64(uBuf[:], v)
return uBuf[:]
}
// BytesToU64 converts the given byte slice to uint64
func BytesToU64(b []byte) uint64 {
return binary.BigEndian.Uint64(b)
}
// U64SliceToBytes converts the given Uint64 slice to byte slice
func U64SliceToBytes(u64s []uint64) []byte {
if len(u64s) == 0 {
return nil
}
var b []byte
hdr := (*reflect.SliceHeader)(unsafe.Pointer(&b))
hdr.Len = len(u64s) * 8
hdr.Cap = hdr.Len
hdr.Data = uintptr(unsafe.Pointer(&u64s[0]))
return b
}
// BytesToU64Slice converts the given byte slice to uint64 slice
func BytesToU64Slice(b []byte) []uint64 {
if len(b) == 0 {
return nil
}
var u64s []uint64
hdr := (*reflect.SliceHeader)(unsafe.Pointer(&u64s))
hdr.Len = len(b) / 8
hdr.Cap = hdr.Len
hdr.Data = uintptr(unsafe.Pointer(&b[0]))
return u64s
}
// page struct contains one underlying buffer.
type page struct {
buf []byte
}
// PageBuffer consists of many pages. A page is a wrapper over []byte. PageBuffer can act as a
// replacement of bytes.Buffer. Instead of having single underlying buffer, it has multiple
// underlying buffers. Hence it avoids any copy during relocation(as happens in bytes.Buffer).
// PageBuffer allocates memory in pages. Once a page is full, it will allocate page with double the
// size of previous page. Its function are not thread safe.
type PageBuffer struct {
pages []*page
length int // Length of PageBuffer.
nextPageSize int // Size of next page to be allocated.
}
// NewPageBuffer returns a new PageBuffer with first page having size pageSize.
func NewPageBuffer(pageSize int) *PageBuffer {
b := &PageBuffer{}
b.pages = append(b.pages, &page{buf: make([]byte, 0, pageSize)})
b.nextPageSize = pageSize * 2
return b
}
// Write writes data to PageBuffer b. It returns number of bytes written and any error encountered.
func (b *PageBuffer) Write(data []byte) (int, error) {
dataLen := len(data)
for {
cp := b.pages[len(b.pages)-1] // Current page.
n := copy(cp.buf[len(cp.buf):cap(cp.buf)], data)
cp.buf = cp.buf[:len(cp.buf)+n]
b.length += n
if len(data) == n {
break
}
data = data[n:]
b.pages = append(b.pages, &page{buf: make([]byte, 0, b.nextPageSize)})
b.nextPageSize *= 2
}
return dataLen, nil
}
// WriteByte writes data byte to PageBuffer and returns any encountered error.
func (b *PageBuffer) WriteByte(data byte) error {
_, err := b.Write([]byte{data})
return err
}
// Len returns length of PageBuffer.
func (b *PageBuffer) Len() int {
return b.length
}
// pageForOffset returns pageIdx and startIdx for the offset.
func (b *PageBuffer) pageForOffset(offset int) (int, int) {
AssertTrue(offset < b.length)
var pageIdx, startIdx, sizeNow int
for i := 0; i < len(b.pages); i++ {
cp := b.pages[i]
if sizeNow+len(cp.buf)-1 < offset {
sizeNow += len(cp.buf)
} else {
pageIdx = i
startIdx = offset - sizeNow
break
}
}
return pageIdx, startIdx
}
// Truncate truncates PageBuffer to length n.
func (b *PageBuffer) Truncate(n int) {
pageIdx, startIdx := b.pageForOffset(n)
// For simplicity of the code reject extra pages. These pages can be kept.
b.pages = b.pages[:pageIdx+1]
cp := b.pages[len(b.pages)-1]
cp.buf = cp.buf[:startIdx]
b.length = n
}
// Bytes returns whole Buffer data as single []byte.
func (b *PageBuffer) Bytes() []byte {
buf := make([]byte, b.length)
written := 0
for i := 0; i < len(b.pages); i++ {
written += copy(buf[written:], b.pages[i].buf)
}
return buf
}
// WriteTo writes whole buffer to w. It returns number of bytes written and any error encountered.
func (b *PageBuffer) WriteTo(w io.Writer) (int64, error) {
written := int64(0)
for i := 0; i < len(b.pages); i++ {
n, err := w.Write(b.pages[i].buf)
written += int64(n)
if err != nil {
return written, err
}
}
return written, nil
}
// NewReaderAt returns a reader which starts reading from offset in page buffer.
func (b *PageBuffer) NewReaderAt(offset int) *PageBufferReader {
pageIdx, startIdx := b.pageForOffset(offset)
return &PageBufferReader{
buf: b,
pageIdx: pageIdx,
startIdx: startIdx,
}
}
// PageBufferReader is a reader for PageBuffer.
type PageBufferReader struct {
buf *PageBuffer // Underlying page buffer.
pageIdx int // Idx of page from where it will start reading.
startIdx int // Idx inside page - buf.pages[pageIdx] from where it will start reading.
}
// Read reads upto len(p) bytes. It returns number of bytes read and any error encountered.
func (r *PageBufferReader) Read(p []byte) (int, error) {
// Check if there is enough to Read.
pc := len(r.buf.pages)
read := 0
for r.pageIdx < pc && read < len(p) {
cp := r.buf.pages[r.pageIdx] // Current Page.
endIdx := len(cp.buf) // Last Idx up to which we can read from this page.
n := copy(p[read:], cp.buf[r.startIdx:endIdx])
read += n
r.startIdx += n
// Instead of len(cp.buf), we comparing with cap(cp.buf). This ensures that we move to next
// page only when we have read all data. Reading from last page is an edge case. We don't
// want to move to next page until last page is full to its capacity.
if r.startIdx >= cap(cp.buf) {
// We should move to next page.
r.pageIdx++
r.startIdx = 0
continue
}
// When last page in not full to its capacity and we have read all data up to its
// length, just break out of the loop.
if r.pageIdx == pc-1 {
break
}
}
if read == 0 && len(p) > 0 {
return read, io.EOF
}
return read, nil
}
const kvsz = int(unsafe.Sizeof(pb.KV{}))
func NewKV(alloc *z.Allocator) *pb.KV {
if alloc == nil {
return &pb.KV{}
}
b := alloc.AllocateAligned(kvsz)
return (*pb.KV)(unsafe.Pointer(&b[0]))
}
// IBytesToString converts size in bytes to human readable format.
// The code is taken from humanize library and changed to provide
// value upto custom decimal precision.
// IBytesToString(12312412, 1) -> 11.7 MiB
func IBytesToString(size uint64, precision int) string {
sizes := []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"}
base := float64(1024)
if size < 10 {
return fmt.Sprintf("%d B", size)
}
e := math.Floor(math.Log(float64(size)) / math.Log(base))
suffix := sizes[int(e)]
val := float64(size) / math.Pow(base, e)
f := "%." + strconv.Itoa(precision) + "f %s"
return fmt.Sprintf(f, val, suffix)
}
type RateMonitor struct {
start time.Time
lastSent uint64
lastCapture time.Time
rates []float64
idx int
}
func NewRateMonitor(numSamples int) *RateMonitor {
return &RateMonitor{
start: time.Now(),
rates: make([]float64, numSamples),
}
}
const minRate = 0.0001
// Capture captures the current number of sent bytes. This number should be monotonically
// increasing.
func (rm *RateMonitor) Capture(sent uint64) {
diff := sent - rm.lastSent
dur := time.Since(rm.lastCapture)
rm.lastCapture, rm.lastSent = time.Now(), sent
rate := float64(diff) / dur.Seconds()
if rate < minRate {
rate = minRate
}
rm.rates[rm.idx] = rate
rm.idx = (rm.idx + 1) % len(rm.rates)
}
// Rate returns the average rate of transmission smoothed out by the number of samples.
func (rm *RateMonitor) Rate() uint64 {
var total float64
var den float64
for _, r := range rm.rates {
if r < minRate {
// Ignore this. We always set minRate, so this is a zero.
// Typically at the start of the rate monitor, we'd have zeros.
continue
}
total += r
den += 1.0
}
if den < minRate {
return 0
}
return uint64(total / den)
}
================================================
FILE: y/y_test.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package y
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"math/rand"
"testing"
"time"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto"
"github.com/dgraph-io/badger/v4/pb"
"github.com/dgraph-io/ristretto/v2/z"
)
func BenchmarkBuffer(b *testing.B) {
var btw [1024]byte
rand.Read(btw[:])
pageSize := 1024
b.Run("bytes-buffer", func(b *testing.B) {
buf := new(bytes.Buffer)
buf.Grow(pageSize)
for i := 0; i < b.N; i++ {
buf.Write(btw[:])
}
})
b.Run("page-buffer", func(b *testing.B) {
b.Run(fmt.Sprintf("page-size-%d", pageSize), func(b *testing.B) {
pageBuffer := NewPageBuffer(pageSize)
for i := 0; i < b.N; i++ {
_, _ = pageBuffer.Write(btw[:])
}
})
})
}
func TestPageBuffer(t *testing.T) {
rand.Seed(time.Now().Unix())
var bytesBuffer bytes.Buffer // This is just for verifying result.
bytesBuffer.Grow(512)
pageBuffer := NewPageBuffer(512)
// Writer small []byte
var smallBytes [256]byte
rand.Read(smallBytes[:])
var bigBytes [1024]byte
rand.Read(bigBytes[:])
_, err := pageBuffer.Write(smallBytes[:])
require.NoError(t, err, "unable to write data to page buffer")
_, err = pageBuffer.Write(bigBytes[:])
require.NoError(t, err, "unable to write data to page buffer")
// Write data to bytesBuffer also, just to match result.
bytesBuffer.Write(smallBytes[:])
bytesBuffer.Write(bigBytes[:])
require.True(t, bytes.Equal(pageBuffer.Bytes(), bytesBuffer.Bytes()))
}
func TestBufferWrite(t *testing.T) {
rand.Seed(time.Now().Unix())
var wb [128]byte
rand.Read(wb[:])
pb := NewPageBuffer(32)
bb := new(bytes.Buffer)
end := 32
for i := 0; i < 3; i++ {
n, err := pb.Write(wb[:end])
require.NoError(t, err, "unable to write bytes to buffer")
require.Equal(t, n, end, "length of buffer and length written should be equal")
// append to bb also for testing.
bb.Write(wb[:end])
require.True(t, bytes.Equal(pb.Bytes(), bb.Bytes()), "Both bytes should match")
end = end * 2
}
}
func TestPagebufferTruncate(t *testing.T) {
rand.Seed(time.Now().Unix())
var wb [1024]byte
rand.Read(wb[:])
b := NewPageBuffer(32)
n, err := b.Write(wb[:])
require.Equal(t, n, len(wb), "length of buffer and length written should be equal")
require.NoError(t, err, "unable to write bytes to buffer")
require.True(t, bytes.Equal(wb[:], b.Bytes()), "bytes written and read should be equal")
// Truncate to 512.
b.Truncate(512)
require.True(t, bytes.Equal(b.Bytes(), wb[:512]))
// Again write wb.
n, err = b.Write(wb[:])
require.Equal(t, n, len(wb), "length of buffer and length written should be equal")
require.NoError(t, err, "unable to write bytes to buffer")
// Truncate to 1000.
b.Truncate(1000)
require.True(t, bytes.Equal(b.Bytes(), append(wb[:512], wb[:]...)[:1000]))
}
// Test PageBufferReader using large buffers.
func TestPagebufferReader(t *testing.T) {
rand.Seed(time.Now().Unix())
var wb [1024]byte
rand.Read(wb[:])
b := NewPageBuffer(32)
n, err := b.Write(wb[:])
require.Equal(t, n, len(wb), "length of buffer and length written should be equal")
require.NoError(t, err, "unable to write bytes to buffer")
// Also append some bytes so that last page is not full.
n, err = b.Write(wb[:10])
require.Equal(t, n, 10, "length of buffer and length written should be equal")
require.NoError(t, err, "unable to write bytes to buffer")
reader := b.NewReaderAt(0)
// Read first 512 bytes.
var rb [512]byte
n, err = reader.Read(rb[:])
require.NoError(t, err, "unable to read error")
require.True(t, n == len(rb), "length read should be equal")
// Match if read bytes are correct or not.
rb2 := b.Bytes()[:512]
require.True(t, bytes.Equal(rb[:], rb2))
// Next read using reader.
n, err = reader.Read(rb[:])
require.NoError(t, err, "unable to read error")
require.True(t, n == len(rb), "length read should be equal")
// Read same number of bytes using Bytes method.
rb2 = b.Bytes()[512:1024]
require.True(t, bytes.Equal(rb[:], rb2))
// Next read using reader for reading last 10 bytes.
n, err = reader.Read(rb[:10])
require.NoError(t, err, "unable to read error")
require.True(t, n == 10, "length read should be equal")
// Read same number of bytes using Bytes method.
rb2 = b.Bytes()[1024 : 1024+10]
require.True(t, bytes.Equal(rb[:10], rb2))
// Check if EOF is returned at end or not.
n, err = reader.Read(rb[:10])
require.Equal(t, err, io.EOF, "EOF should be returned at end")
require.Zero(t, n, "read length should be 0")
}
// Test PageBuffer by reading at random offset, random length.
func TestPagebufferReader2(t *testing.T) {
rand.Seed(time.Now().Unix())
var wb [1024]byte
rand.Read(wb[:])
b := NewPageBuffer(32)
n, err := b.Write(wb[:])
require.Equal(t, n, len(wb), "length of buffer and length written should be equal")
require.NoError(t, err, "unable to write bytes to buffer")
// Also append some bytes so that last page is not full.
n, err = b.Write(wb[:10])
require.Equal(t, n, 10, "length of buffer and length written should be equal")
require.NoError(t, err, "unable to write bytes to buffer")
randOffset := int(rand.Int31n(int32(b.length) - 1))
randLength := int(rand.Int31n(int32(b.length - randOffset)))
reader := b.NewReaderAt(randOffset)
// Read randLength bytes.
rb := make([]byte, randLength)
n, err = reader.Read(rb[:])
require.NoError(t, err, "unable to read error")
require.True(t, n == len(rb), "length read should be equal")
// Read same number of bytes using Bytes method.
rb2 := b.Bytes()[randOffset : randOffset+randLength]
require.True(t, bytes.Equal(rb[:], rb2))
}
// Test PageBuffer while reading multiple chunks. Chunks are smaller than pages of PageBuffer.
func TestPagebufferReader3(t *testing.T) {
rand.Seed(time.Now().Unix())
var wb [1000]byte
rand.Read(wb[:])
b := NewPageBuffer(32)
n, err := b.Write(wb[:])
require.Equal(t, n, len(wb), "length of buffer and length written should be equal")
require.NoError(t, err, "unable to write bytes to buffer")
reader := b.NewReaderAt(0)
chunk := 10 // Read 10 bytes in loop.
readBuf := make([]byte, chunk)
currentOffset := 0
for i := 0; i < len(wb)/chunk; i++ {
n, err = reader.Read(readBuf)
require.NoError(t, err, "unable to read from reader")
require.Equal(t, chunk, n, "length read should be equal to chunk")
require.True(t, bytes.Equal(readBuf, wb[currentOffset:currentOffset+chunk]))
rb := b.Bytes()[currentOffset : currentOffset+chunk]
require.True(t, bytes.Equal(wb[currentOffset:currentOffset+chunk], rb))
currentOffset += chunk
}
// Read EOF.
n, err = reader.Read(readBuf)
require.Equal(t, err, io.EOF, "should return EOF")
require.Equal(t, n, 0)
// Read EOF again.
n, err = reader.Read(readBuf)
require.Equal(t, err, io.EOF, "should return EOF")
require.Equal(t, n, 0)
}
// Test when read buffer is larger than PageBuffer.
func TestPagebufferReader4(t *testing.T) {
rand.Seed(time.Now().Unix())
var wb [20]byte
rand.Read(wb[:])
b := NewPageBuffer(32)
n, err := b.Write(wb[:])
require.Equal(t, n, len(wb), "length of buffer and length written should be equal")
require.NoError(t, err, "unable to write bytes to buffer")
reader := b.NewReaderAt(0)
readBuf := make([]byte, 100)
n, err = reader.Read(readBuf)
require.NoError(t, err, "unable to read from reader")
require.Equal(t, 20, n, "length read should be equal to chunk")
// Read EOF.
n, err = reader.Read(readBuf)
require.Equal(t, err, io.EOF, "should return EOF")
require.Equal(t, n, 0)
}
// Test when reading into 0 length readBuffer
func TestPagebufferReader5(t *testing.T) {
b := NewPageBuffer(32)
var wb [20]byte
rand.Read(wb[:])
n, err := b.Write(wb[:])
require.Equal(t, n, len(wb), "length of buffer and length written should be equal")
require.NoError(t, err, "unable to write bytes to buffer")
reader := b.NewReaderAt(0)
readBuffer := []byte{} // Intentionally empty readBuffer.
n, err = reader.Read(readBuffer)
require.NoError(t, err, "reading into empty buffer should return no error")
require.Equal(t, 0, n, "read into empty buffer should return 0 bytes")
}
func TestSizeVarintForZero(t *testing.T) {
siz := sizeVarint(0)
require.Equal(t, 1, siz)
}
func TestEncodedSize(t *testing.T) {
valBufSize := uint32(rand.Int31n(1e5))
expiry := rand.Uint64()
expiryVarintBuf := make([]byte, 64)
expVarintSize := uint32(binary.PutUvarint(expiryVarintBuf, expiry))
valBuf := make([]byte, valBufSize)
_, _ = rand.Read(valBuf)
valStruct := &ValueStruct{
Value: valBuf,
ExpiresAt: expiry,
}
require.Equal(t, valBufSize+uint32(2)+expVarintSize, valStruct.EncodedSize())
}
func TestAllocatorReuse(t *testing.T) {
a := z.NewAllocator(1024, "test")
defer a.Release()
N := 1024
buf := make([]byte, 4096)
rand.Read(buf)
for i := 0; i < N; i++ {
a.Reset()
var list pb.KVList
for j := 0; j < N; j++ {
kv := NewKV(a)
sz := rand.Intn(1024)
kv.Key = a.Copy(buf[:sz])
kv.Value = a.Copy(buf[:4*sz])
kv.Meta = a.Copy([]byte{1})
kv.Version = uint64(sz)
list.Kv = append(list.Kv, kv)
}
_, err := proto.Marshal(&list)
require.NoError(t, err)
}
t.Logf("Allocator: %s\n", a)
}
func TestSafeCopy_Issue2067(t *testing.T) {
type args struct {
a []byte
src []byte
}
tests := []struct {
name string
args args
want []byte
}{
{
name: "Nil src should return empty slice not nil",
args: args{a: nil, src: nil},
want: []byte{},
},
{
name: "Empty src should return empty slice not nil",
args: args{a: nil, src: []byte{}},
want: []byte{},
},
{
name: "Normal src should return src content",
args: args{a: nil, src: []byte("hello")},
want: []byte("hello"),
},
{
name: "Buffer reuse with nil src should return empty slice",
args: args{a: make([]byte, 10), src: nil},
want: []byte{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := SafeCopy(tt.args.a, tt.args.src)
require.Equal(t, tt.want, got)
// Explicit check for nil vs empty slice distinction
if len(tt.want) == 0 {
require.NotNil(t, got, "SafeCopy returned nil, but we expected an empty slice []byte{}")
}
})
}
}
================================================
FILE: y/zstd.go
================================================
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package y
import (
"sync"
"github.com/klauspost/compress/zstd"
)
var (
decoder *zstd.Decoder
encoder *zstd.Encoder
encOnce, decOnce sync.Once
)
// ZSTDDecompress decompresses a block using ZSTD algorithm.
func ZSTDDecompress(dst, src []byte) ([]byte, error) {
decOnce.Do(func() {
var err error
decoder, err = zstd.NewReader(nil)
Check(err)
})
return decoder.DecodeAll(src, dst[:0])
}
// ZSTDCompress compresses a block using ZSTD algorithm.
func ZSTDCompress(dst, src []byte, compressionLevel int) ([]byte, error) {
encOnce.Do(func() {
var err error
level := zstd.EncoderLevelFromZstd(compressionLevel)
encoder, err = zstd.NewWriter(nil, zstd.WithEncoderLevel(level))
Check(err)
})
return encoder.EncodeAll(src, dst[:0]), nil
}
// ZSTDCompressBound returns the worst case size needed for a destination buffer.
// Klauspost ZSTD library does not provide any API for Compression Bound. This
// calculation is based on the DataDog ZSTD library.
// See https://pkg.go.dev/github.com/DataDog/zstd#CompressBound
func ZSTDCompressBound(srcSize int) int {
lowLimit := 128 << 10 // 128 kB
var margin int
if srcSize < lowLimit {
margin = (lowLimit - srcSize) >> 11
}
return srcSize + (srcSize >> 8) + margin
}