Repository: spacejam/sled Branch: main Commit: 05b42c17ea14 Files: 63 Total size: 521.3 KB Directory structure: gitextract_hgnzatql/ ├── .github/ │ ├── FUNDING.yml │ ├── ISSUE_TEMPLATE/ │ │ ├── blank_issue.md │ │ ├── bugs.md │ │ ├── config.yml │ │ └── feature_request.md │ ├── dependabot.yml │ └── workflows/ │ └── test.yml ├── .gitignore ├── .rustfmt.toml ├── ARCHITECTURE.md ├── CHANGELOG.md ├── CONTRIBUTING.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── RELEASE_CHECKLIST.md ├── SAFETY.md ├── SECURITY.md ├── art/ │ └── CREDITS ├── code-of-conduct.md ├── examples/ │ └── bench.rs ├── fuzz/ │ ├── .gitignore │ ├── Cargo.toml │ └── fuzz_targets/ │ └── fuzz_model.rs ├── scripts/ │ ├── cgtest.sh │ ├── cross_compile.sh │ ├── execution_explorer.py │ ├── instructions │ ├── sanitizers.sh │ ├── shufnice.sh │ └── ubuntu_bench ├── src/ │ ├── alloc.rs │ ├── block_checker.rs │ ├── config.rs │ ├── db.rs │ ├── event_verifier.rs │ ├── flush_epoch.rs │ ├── heap.rs │ ├── id_allocator.rs │ ├── leaf.rs │ ├── lib.rs │ ├── metadata_store.rs │ ├── object_cache.rs │ ├── object_location_mapper.rs │ └── tree.rs └── tests/ ├── 00_regression.rs ├── common/ │ └── mod.rs ├── concurrent_batch_atomicity.rs ├── crash_tests/ │ ├── crash_batches.rs │ ├── crash_heap.rs │ ├── crash_iter.rs │ ├── crash_metadata_store.rs │ ├── crash_object_cache.rs │ ├── crash_sequential_writes.rs │ ├── crash_tx.rs │ └── mod.rs ├── test_crash_recovery.rs ├── test_quiescent.rs ├── test_space_leaks.rs ├── test_tree.rs ├── test_tree_failpoints.rs └── tree/ └── mod.rs ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ # These are supported funding model platforms github: spacejam # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] patreon: # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: # Replace with a single Ko-fi username tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] ================================================ FILE: .github/ISSUE_TEMPLATE/blank_issue.md ================================================ --- name: Blank Issue (do not use this for bug reports or feature requests) about: Create an issue with a blank template. --- ================================================ FILE: .github/ISSUE_TEMPLATE/bugs.md ================================================ --- name: Bug Report about: Report a correctness issue or violated expectation labels: bug --- Bug reports must include all following items: 1. expected result 1. actual result 1. sled version 1. rustc version 1. operating system 1. minimal code sample that helps to reproduce the issue 1. logs, panic messages, stack traces Incomplete bug reports will be closed. Do not open bug reports for documentation issues. Please just open a PR with the proposed documentation change. Thank you for understanding :) ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ blank_issues_enabled: true contact_links: - name: sled discord url: https://discord.gg/Z6VsXds about: Please ask questions in the discord server here. ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.md ================================================ --- name: Feature Request about: Request a feature for sled labels: feature --- #### Use Case: #### Proposed Change: #### Who Benefits From The Change(s)? #### Alternative Approaches ================================================ FILE: .github/dependabot.yml ================================================ version: 2 updates: - package-ecosystem: cargo directory: "/" schedule: interval: daily time: "10:00" open-pull-requests-limit: 10 ignore: - dependency-name: crdts versions: - ">= 2.a, < 3" - dependency-name: zerocopy versions: - 0.4.0 ================================================ FILE: .github/workflows/test.yml ================================================ name: Rust on: pull_request: branches: - main jobs: clippy_check: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - uses: actions-rs/toolchain@v1 with: toolchain: nightly components: clippy override: true - run: rustup component add clippy - uses: actions-rs/clippy-check@v1 with: token: ${{ secrets.GITHUB_TOKEN }} args: --all-features default: name: Cargo Test on ${{ matrix.os }} env: RUST_BACKTRACE: 1 runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: [ubuntu-latest, macos-latest, windows-latest] steps: - uses: actions/checkout@v1 - name: Cache target uses: actions/cache@v2 env: cache-name: cache-default-target-and-lockfile with: path: | target Cargo.lock ~/.rustup key: ${{ runner.os }}-${{ env.cache-name }}-${{ hashFiles('**/Cargo.toml') }} - name: linux coredump setup if: ${{ runner.os == 'linux' }} run: | ulimit -c unlimited echo "$PWD/core-dumps/corefile-%e-%p-%t" | sudo tee /proc/sys/kernel/core_pattern mkdir core-dumps - name: cargo test run: | rustup update --no-self-update cargo test --release --no-default-features --features=for-internal-testing-only -- --nocapture - uses: actions/upload-artifact@v4 if: ${{ failure() && runner.os == 'linux' }} with: name: linux-core-dumps path: | ./core-dumps/* ./target/release/deps/test_* examples: name: Example Tests runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - name: Cache target uses: actions/cache@v2 env: cache-name: cache-examples-target-and-lockfile with: path: | target Cargo.lock ~/.rustup key: ${{ runner.os }}-${{ env.cache-name }}-${{ hashFiles('**/Cargo.toml') }} - name: example tests run: | rustup update --no-self-update cargo run --example playground cargo run --example structured cross-compile: name: Cross Compile runs-on: macos-latest steps: - uses: actions/checkout@v1 - name: cross compile run: | set -eo pipefail echo "cross build" scripts/cross_compile.sh burn-in: name: Burn In env: RUST_BACKTRACE: 1 runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - name: Cache target uses: actions/cache@v2 env: cache-name: cache-stress2-asan-target-and-lockfile with: path: | benchmarks/stress2/target benchmarks/stress2/Cargo.lock ~/.rustup key: ${{ runner.os }}-${{ env.cache-name }}-${{ hashFiles('**/Cargo.toml') }} - name: burn in run: | set -eo pipefail pushd benchmarks/stress2 ulimit -c unlimited echo "$PWD/core-dumps/corefile-%e-%p-%t" | sudo tee /proc/sys/kernel/core_pattern mkdir core-dumps rustup toolchain install nightly rustup toolchain install nightly --component rust-src rustup update rm -rf default.sled || true export RUSTFLAGS="-Z sanitizer=address" export ASAN_OPTIONS="detect_odr_violation=0" cargo +nightly build --release --target x86_64-unknown-linux-gnu target/x86_64-unknown-linux-gnu/release/stress2 --duration=240 rm -rf default.sled - name: print backtraces with gdb if: ${{ failure() }} run: | sudo apt-get update sudo apt-get install gdb pushd benchmarks/stress2 echo "first backtrace:" gdb target/release/stress2 core-dumps/* -batch -ex 'bt -frame-info source-and-location' echo "" echo "" echo "" echo "all backtraces:" gdb target/release/stress2 core-dumps/* -batch -ex 't a a bt -frame-info source-and-location' - uses: actions/upload-artifact@v4 if: ${{ failure() }} with: name: linux-core-dumps path: | ./benchmarks/stress2/core-dumps/* ./benchmarks/stress2/target/release/stress2 sanitizers: name: Sanitizers env: RUST_BACKTRACE: 1 runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - name: Cache rustup uses: actions/cache@v2 env: cache-name: cache-sanitizers-target-and-lockfile with: path: | ~/.rustup benchmarks/stress2/target benchmarks/stress2/Cargo.lock key: ${{ runner.os }}-${{ env.cache-name }}-${{ hashFiles('**/Cargo.toml') }} - name: sanitizers run: | set -eo pipefail scripts/sanitizers.sh ================================================ FILE: .gitignore ================================================ CLAUDE.md fuzz-*.log default.sled timing_test* *db crash_test_files *conf *snap.* *grind.out* vgcore* *.bk *orig tags perf* *folded *out *perf *svg *txt experiments target Cargo.lock *swp *swo *.proptest-regressions corpus artifacts .idea cargo-timing* ================================================ FILE: .rustfmt.toml ================================================ version = "Two" use_small_heuristics = "Max" reorder_imports = true max_width = 80 wrap_comments = true combine_control_expr = true report_todo = "Always" ================================================ FILE: ARCHITECTURE.md ================================================
key value
buy a coffee for us to convert into databases
documentation
chat about databases with us

# sled 1.0 architecture ## in-memory * Lock-free B+ tree index, extracted into the [`concurrent-map`](https://github.com/komora-io/concurrent-map) crate. * The lowest key from each leaf is stored in this in-memory index. * To read any leaf that is not already cached in memory, at most one disk read will be required. * RwLock-backed leaves, using the ArcRwLock from the [`parking_lot`](https://github.com/Amanieu/parking_lot) crate. As a `Db` grows, leaf contention tends to go down in most use cases. But this may be revisited over time if many users have issues with RwLock-related contention. Avoiding full RCU for updates on the leaves results in many of the performance benefits over sled 0.34, with significantly lower memory pressure. * A simple but very high performance epoch-based reclamation technique is used for safely deferring frees of in-memory index data and reuse of on-disk heap slots, extracted into the [`ebr`](https://github.com/komora-io/ebr) crate. * A scan-resistant LRU is used for handling eviction. By default, 20% of the cache is reserved for leaves that are accessed at most once. This is configurable via `Config.entry_cache_percent`. This is handled by the extracted [`cache-advisor`](https://github.com/komora-io/cache-advisor) crate. The overall cache size is set by the `Config.cache_size` configurable. ## write path * This is where things get interesting. There is no traditional WAL. There is no LSM. Only metadata is logged atomically after objects are written in parallel. * The important guarantees are: * all previous writes are durable after a call to `Db::flush` (This is also called periodically in the background by a flusher thread) * all write batches written using `Db::apply_batch` are either 100% visible or 0% visible after crash recovery. If it was followed by a flush that returned `Ok(())` it is guaranteed to be present. * Atomic ([linearizable](https://jepsen.io/consistency/models/linearizable)) durability is provided by marking dirty leaves as participants in "flush epochs" and performing atomic batch writes of the full epoch at a time, in order. Each call to `Db::flush` advances the current flush epoch by 1. * The atomic write consists in the following steps: 1. User code or the background flusher thread calls `Db::flush`. 1. In parallel (via [rayon](https://docs.rs/rayon)) serialize and compress each dirty leaf with zstd (configurable via `Config.zstd_compression_level`). 1. Based on the size of the bytes for each object, choose the smallest heap file slot that can hold the full set of bytes. This is an on-disk slab allocator. 1. Slab slots are not power-of-two sized, but tend to increase in size by around 20% from one to the next, resulting in far lower fragmentation than typical page-oriented heaps with either constant-size or power-of-two sized leaves. 1. Write the object to the allocated slot from the rayon threadpool. 1. After all writes, fsync the heap files that were written to. 1. If any writes were written to the end of the heap file, causing it to grow, fsync the directory that stores all heap files. 1. After the writes are stable, it is now safe to write an atomic metadata batch that records the location of each written leaf in the heap. This is a simple framed batch of `(low_key, slab_slot)` tuples that are initially written to a log, but eventually merged into a simple snapshot file for the metadata store once the log becomes larger than the snapshot file. 1. Fsync of the metadata log file. 1. Fsync of the metadata log directory. 1. After the atomic metadata batch write, the previously occupied slab slots are marked for future reuse with the epoch-based reclamation system. After all threads that may have witnessed the previous location have finished their work, the slab slot is added to the free `BinaryHeap` of the slot that it belongs to so that it may be reused in future atomic write batches. 1. Return `Ok(())` to the caller of `Db::flush`. * Writing objects before the metadata write is random, but modern SSDs handle this well. Even though the SSD's FTL will be working harder to defragment things periodically than if we wrote a few megabytes sequentially with each write, the data that the FTL will be copying will be mostly live due to the eager leaf write-backs. ## recovery * Recovery involves simply reading the atomic metadata store that records the low key for each written leaf as well as its location and mapping it into the in-memory index. Any gaps in the slabs are then used as free slots. * Any write that failed to complete its entire atomic writebatch is treated as if it never happened, because no user-visible flush ever returned successfully. * Rayon is also used here for parallelizing reads of this metadata. In general, this is extremely fast compared to the previous sled recovery process. ## tuning * The larger the `LEAF_FANOUT` const generic on the high-level `Db` struct (default `1024`), the smaller the in-memory leaf index and the better the compression ratio of the on-disk file, but the more expensive it will be to read the entire leaf off of disk and decompress it. * You can choose to turn the `LEAF_FANOUT` relatively low to make the system behave more like an Index+Log architecture, but overall disk size will grow and write performance will decrease. * NB: changing `LEAF_FANOUT` after writing data is not supported. ================================================ FILE: CHANGELOG.md ================================================ # Unreleased ## New Features * #1178 batches and transactions are now unified for subscribers. * #1231 `Tree::get_zero_copy` allows for reading a value directly in-place without making an `IVec` first. * #1250 the global `print_profile` function has been added which is enabled when compiling with the `metrics` feature. * #1254 `IVec` data will now always have an alignment of 8, which may enable interesting architecture-specific use cases. * #1307 & #1315 `Db::contains_tree` can be used to see if a `Tree` with a given name already exists. ## Improvements * #1214 a new slab-style storage engine has been added which replaces the previous file-per-blob technique for storing large pages. * #1231 tree nodes now get merged into a single-allocation representation that is able to dynamically avoid various overheads, resulting in significant efficiency improvements. ## Breaking Changes * #1400 Bump MSRV to 1.57. * #1399 Thread support is now required on all platforms. * #1135 The "no_metrics" anti-feature has been replaced with the "metrics" positive feature. * #1178 the `Event` enum has become a unified struct that allows subscribers to iterate over each (Tree, key, optional value) involved in single key operations, batches, or transactions in a unified way. * #1178 the `Event::key` method has been removed in favor of the new more comprehensive `iter` method. * #1214 The deprecated `Config::build` method has been removed. * #1248 The deprecated `Tree::set` method has been removed. * #1248 The deprecated `Tree::del` method has been removed. * #1250 The `Config::print_profile_on_drop` method has been removed in favor of the global `print_profile` function. * #1252 The deprecated `Db::open` method has been removed. * #1252 The deprecated `Config::segment_cleanup_skew` method has been removed. * #1252 The deprecated `Config::segment_cleanup_threshold` method has been removed. * #1252 The deprecated `Config::snapshot_path` method has been removed. * #1253 The `IVec::subslice` method has been removed. * #1275 Keys and values are now limited to 128gb on 64-bit platforms and 512mb on 32-bit platforms. * #1281 `Config`'s `cache_capacity` is now a usize, as u64 doesn't make sense for things that must fit in memory anyway. * #1314 `Subscriber::next_timeout` now requires a mutable self reference. * #1349 The "measure_allocs" feature has been removed. * #1354 `Error` has been modified to be Copy, removing all heap-allocated variants. ## Bug Fixes * #1202 Fix a space leak where blobs were not removed when replaced by another blob. * #1229 the powerful ALICE crash consistency tool has been used to discover several crash vulnerabilities, now fixed. # 0.34.7 ## Bug Fixes * #1314 Fix a bug in Subscriber's Future impl. # 0.34.6 ## Improvements * documentation improved # 0.34.5 ## Improvements * #1164 widen some trait bounds on trees and batches # 0.34.4 ## New Features * #1151 `Send` is implemented for `Iter` * #1167 added `Tree::first` and `Tree::last` functions to retrieve the first or last items in a `Tree`, unless the `Tree` is empty. ## Bug Fixes * #1159 dropping a `Db` instance will no-longer prematurely shut-down the background flusher thread. * #1168 fixed an issue that was causing panics during recovery in 32-bit code. * #1170 when encountering corrupted storage data, the recovery process will panic less often. # 0.34.3 ## New Features * #1146 added `TransactionalTree::generate_id` # 0.34.2 ## Improvements * #1133 transactions and writebatch performance has been significantly improved by removing a bottleneck in the atomic batch stability tracking code. # 0.34.1 ## New Features * #1136 Added the `TransactionalTree::flush` method to flush the underlying database after the transaction commits and before the transaction returns. # 0.34 ## Improvements * #1132 implemented From for io::Error to reduce friction in some situations. ## Breaking Changes * #1131 transactions performed on `Tree`s from different `Db`s will now safely fail. * #1131 transactions may now only be performed on tuples of up to 14 elements. For higher numbers, please use slices. # 0.33 ## Breaking Changes * #1125 the backtrace crate has been made optional, which cuts several seconds off compilation time, but may cause breakage if you interacted with the backtrace field of corruption-related errors. ## Bug Fixes * #1128 `Tree::pop_min` and `Tree::pop_max` had a bug where they were not atomic. # 0.32.1 ## New Features * #1116 `IVec::subslice` has been added to facilitate creating zero-copy subsliced `IVec`s that are backed by the same data. ## Bug Fixes * #1120 Fixed a use-after-free caused by missing `ref` keyword on a `Copy` type in a pattern match in `IVec::as_mut`. * #1108 conversions from `Box<[u8]>` to `IVec` are fixed. # 0.32 ## New Features * #1079 `Transactional` is now implemented for `[&Tree]` and `[Tree]` so you can avoid the previous friction of using tuples, as was necessary previously. * #1058 The minimum supported Rust version (MSRV) is now 1.39.0. * #1037 `Subscriber` now implements `Future` (non-fused) so prefix watching may now be iterated over via `while let Some(event) = (&mut subscriber).await {}` ## Improvements * #965 concurrency control is now dynamically enabled for atomic point operations, so that it may be avoided unless transactional functionality is being used in the system. This significantly increases performance for workloads that do not use transactions. * A number of memory optimizations have been implemented. * Disk usage has been significantly reduced for many workloads. * #1016 On 64-bit systems, we can now store 1-2 trillion items. * #993 Added DerefMut and AsMut<[u8]> for `IVec` where it works similarly to a `Cow`, making a private copy if the backing `Arc`'s strong count is not 1. * #1020 The sled wiki has been moved into the documentation itself, and is accessible through the `doc` module exported in lib. ## Breaking Changes * #975 Changed the default `segment_size` from 8m to 512k. This will result in far smaller database files due to better file garbage collection granularity. * #975 deprecated several `Config` options that will be removed over time. * #1000 rearranged some transaction-related imports, and moved them to the `transaction` module away from the library root to keep the top level docs clean. * #1015 `TransactionalTree::apply_batch` now accepts its argument by reference instead of by value. * `Event` has been changed to make the inner fields named instead of anonymous. * #1057 read-only mode has been removed due to not having the resources to properly keep it tested while making progress on high priority issues. This may be correctly implemented in the future if resources permit. * The conversion between `Box<[u8]>` and `IVec` has been temporarily removed. This is re-added in 0.32.1. # 0.31 ## Improvements * #947 dramatic read and recovery optimizations * #921 reduced the reliance on locks while performing multithreaded IO on windows. * #928 use `sync_file_range` on linux instead of a full fsync for most writes. * #946 io_uring support changed to the `rio` crate * #939 reduced memory consumption during zstd decompression ## Breaking Changes * #927 use SQLite-style varints for serializing `u64`. This dramatically reduces the written bytes for databases that store small keys and values. * #943 use varints for most of the fields in message headers, causing an additional large space reduction. combined with #927, these changes reduce bytes written by 68% for workloads writing small items. # 0.30.3 * Documentation-only release # 0.30.2 ## New Features * Added the `open` function for quickly opening a database at a path with default configuration. # 0.30.1 ## Bugfixes * Fixed an issue where an idle threadpool worker would spin in a hot loop until work arrived # 0.30 ## Breaking Changes * Migrated to a new storage format ## Bugfixes * Fixed a bug where cache was not being evicted. * Fixed a bug with using transactions with compression. # 0.29.2 ## New Features * The `create_new` option has been added to `Config`, allowing the user to specify that a database should only be freshly created, rather than re-opened. # 0.29.1 ## Bugfixes * Fixed a bug where prefix encoding could be incorrectly handled when merging nodes together. # 0.29 ## New Features * The `Config::open` method has been added to give `Config` a similar feel to std's `fs::OpenOptions`. The `Config::build` and `Db::start` methods are now deprecated in favor of calling `Config::open` directly. * A `checksum` method has been added to Tree and Db for use in verifying backups and migrations. * Transactions may now involve up to 69 different tables. Nice. * The `TransactionError::Abort` variant has had a generic member added that can be returned as a way to return information from a manually-aborted transaction. An `abort` helper function has been added to reduce the boiler- plate required to return aborted results. ## Breaking Changes * The `ConfigBuilder` structure has been removed in favor of a simplified `Config` structure with the same functionality. * The way that sled versions are detected at initialization time is now independent of serde. * The `cas` method is deprecated in favor of the new `compare_and_swap` method which now returns the proposed value that failed to be applied. * Tree nodes now have constant prefix encoding lengths. * The `io_buf_size` configurable renamed to `segment_size`. * The `io_buf_size` configurable method has been removed from ConfigBuilder. This can be manually set by setting the attribute directly on the ConfigBuilder, but this is discouraged. Additionally, this must now be a power of 2. * The `page_consolidation_threshold` method has been removed from ConfigBuilder, and this is now a constant of 10. # 0.28 ## Breaking Changes * `Iter` no longer has a lifetime parameter. * `Db::open_tree` now returns a `Tree` instead of an `Arc`. `Tree` now has an inner type that uses an `Arc`, so you don't need to think about it. ## Bug Fixes * A bug with prefix encoding has been fixed that led to nodes with keys longer than 256 bytes being stored incorrectly, which led to them being inaccessible and also leading to infinite loops during iteration. * Several cases of incorrect unsafe code were removed from the sled crate. No bugs are known to have been encountered, but they may have resulted in incorrect optimizations in future refactors. # 0.27 ## Breaking Changes * `Event::Set` has been renamed to `Event::Insert` and `Event::Del` has been renamed to `Event::Remove`. These names better align with the methods of BTreeMap from the standard library. ## Bug Fixes * A deadlock was possible in very high write volume situations when the segment accountant lock was taken by all IO threads while a task was blocked trying to submit a file truncation request to the threadpool while holding the segment accountant lock. ## New Features * `flush_async` has been added to perform time-intensive flushing in an asynchronous manner, returning a Future. # 0.26.1 ## Improvements * std::thread is no longer used on platforms other than linux, macos, and windows, which increases portability. # 0.26 ## New Features * Transactions! You may now call `Tree::transaction` and perform reads, writes, and deletes within a provided closure with a `TransactionalTree` argument. This closure may be called multiple times if the transaction encounters a concurrent update in the process of its execution. Transactions may also be used on tuples of `Tree` objects, where the closure will then be parameterized on `TransactionalTree` instances providing access to each of the provided `Tree` instances. This allows you to atomically read and modify multiple `Tree` instances in a single atomic operation. These transactions are serializable, fully ACID, and optimistic. * `Tree::apply_batch` allows you to apply a `Batch` * `TransactionalTree::apply_batch` allow you to apply a `Batch` from within a transaction. ## Breaking Changes * `Tree::batch` has been removed. Now you can directly create a `Batch` with `Batch::default()` and then apply it to a `Tree` with `Tree::apply_batch` or during a transaction using `TransactionalTree::apply_batch`. This facilitates multi-`Tree` batches via transactions. * `Event::Merge` has been removed, and `Tree::merge` will now send a complete `Event::Set` item to be distributed to all listening subscribers. ================================================ FILE: CONTRIBUTING.md ================================================ # Welcome to the Project :) * Don't be a jerk - here's our [code of conduct](./code-of-conduct.md). We have a track record of defending our community from harm. There are at least three great ways to contribute to sled: * [financial contribution](https://github.com/sponsors/spacejam) * coding * conversation #### Coding Considerations: Please don't waste your time or ours by implementing things that we do not want to introduce and maintain. Please discuss in an issue or on chat before submitting a PR with: * public API changes * new functionality of any sort * additional unsafe code * significant refactoring The above changes are unlikely to be merged or receive timely attention without prior discussion. PRs that generally require less coordination beforehand: * Anything addressing a correctness issue. * Better docs: whatever you find confusing! * Small code changes with big performance implications, substantiated with [responsibly-gathered metrics](https://sled.rs/perf#experiment-checklist). * FFI submodule changes: these are generally less well maintained than the Rust core, and benefit more from public assistance. * Generally any new kind of test that avoids biases inherent in the others. #### All PRs block on failing tests! sled has intense testing, including crash tests, multi-threaded tests with delay injection, a variety of mechanically-generated tests that combine fault injection with concurrency in interesting ways, cross-compilation and minimum supported Rust version checks, LLVM sanitizers, and more. It can sometimes be challenging to understand why something is failing these intense tests. For better understanding test failures, please: 1. read the failing test name and output log for clues 1. try to reproduce the failed test locally by running its associated command from the [test script](https://github.com/spacejam/sled/blob/main/.github/workflows/test.yml) 1. If it is not clear why your test is failing, feel free to request help with understanding it either on discord or requesting help on the PR, and we will do our best to help. Want to help sled but don't have time for individual contributions? Contribute via [GitHub Sponsors](https://github.com/sponsors/spacejam) to support the people pushing the project forward! ================================================ FILE: Cargo.toml ================================================ [package] name = "sled" version = "1.0.0-alpha.124" edition = "2024" authors = ["Tyler Neely "] documentation = "https://docs.rs/sled/" description = "Lightweight high-performance pure-rust transactional embedded database." license = "MIT OR Apache-2.0" homepage = "https://github.com/spacejam/sled" repository = "https://github.com/spacejam/sled" keywords = ["redis", "mongo", "sqlite", "lmdb", "rocksdb"] categories = ["database-implementations", "concurrency", "data-structures", "algorithms", "caching"] readme = "README.md" exclude = ["benchmarks", "examples", "bindings", "scripts", "experiments"] [features] # initializes allocated memory to 0xa1, writes 0xde to deallocated memory before freeing it testing-shred-allocator = [] # use a counting global allocator that provides the sled::alloc::{allocated, freed, resident, reset} functions testing-count-allocator = [] for-internal-testing-only = [] # turn off re-use of object IDs and heap slots, disable tree leaf merges, disable heap file truncation. monotonic-behavior = [] [profile.release] debug = true opt-level = 3 overflow-checks = true panic = "abort" [profile.test] debug = true overflow-checks = true panic = "abort" [dependencies] bincode = "1.3.3" cache-advisor = "1.0.16" concurrent-map = { version = "5.0.31", features = ["serde"] } crc32fast = "1.3.2" ebr = "0.2.13" inline-array = { version = "0.1.13", features = ["serde", "concurrent_map_minimum"] } fs2 = "0.4.3" log = "0.4.19" pagetable = "0.4.5" parking_lot = { version = "0.12.1", features = ["arc_lock"] } rayon = "1.7.0" serde = { version = "1.0", features = ["derive"] } stack-map = { version = "1.0.5", features = ["serde"] } zstd = "0.12.4" fnv = "1.0.7" fault-injection = "1.0.10" crossbeam-queue = "0.3.8" crossbeam-channel = "0.5.8" tempdir = "0.3.7" [dev-dependencies] env_logger = "0.10.0" num-format = "0.4.4" # heed = "0.11.0" # rocksdb = "0.21.0" # rusqlite = "0.29.0" # old_sled = { version = "0.34", package = "sled" } rand = "0.9" quickcheck = "1.0.3" rand_distr = "0.5" libc = "0.2.147" [[test]] name = "test_crash_recovery" path = "tests/test_crash_recovery.rs" harness = false ================================================ FILE: LICENSE-APACHE ================================================ 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 APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2015 Tyler Neely Copyright 2016 Tyler Neely Copyright 2017 Tyler Neely Copyright 2018 Tyler Neely Copyright 2019 Tyler Neely Copyright 2020 Tyler Neely Copyright 2021 Tyler Neely Copyright 2022 Tyler Neely Copyright 2023 Tyler Neely Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: LICENSE-MIT ================================================ Copyright (c) 2015 Tyler Neely Copyright (c) 2016 Tyler Neely Copyright (c) 2017 Tyler Neely Copyright (c) 2018 Tyler Neely Copyright (c) 2019 Tyler Neely Copyright (c) 2020 Tyler Neely Copyright (c) 2021 Tyler Neely Copyright (c) 2022 Tyler Neely Copyright (c) 2023 Tyler Neely Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================
key value
documentation
chat about databases with us

# sled - ~~it's all downhill from here!!!~~ An embedded database. ```rust let tree = sled::open("/tmp/welcome-to-sled")?; // insert and get, similar to std's BTreeMap let old_value = tree.insert("key", "value")?; assert_eq!( tree.get(&"key")?, Some(sled::IVec::from("value")), ); // range queries for kv_result in tree.range("key_1".."key_9") {} // deletion let old_value = tree.remove(&"key")?; // atomic compare and swap tree.compare_and_swap( "key", Some("current_value"), Some("new_value"), )?; // block until all operations are stable on disk // (flush_async also available to get a Future) tree.flush()?; ``` $${\color{red}This \space README \space is \space out \space of \space sync \space with \space the \space main \space branch \space which \space contains \space a \space large \space in-progress \space rewrite }$$ If you would like to work with structured data without paying expensive deserialization costs, check out the [structured](examples/structured.rs) example! # features * [API](https://docs.rs/sled) similar to a threadsafe `BTreeMap<[u8], [u8]>` * serializable (ACID) [transactions](https://docs.rs/sled/latest/sled/struct.Tree.html#method.transaction) for atomically reading and writing to multiple keys in multiple keyspaces. * fully atomic single-key operations, including [compare and swap](https://docs.rs/sled/latest/sled/struct.Tree.html#method.compare_and_swap) * zero-copy reads * [write batches](https://docs.rs/sled/latest/sled/struct.Tree.html#method.apply_batch) * [subscribe to changes on key prefixes](https://docs.rs/sled/latest/sled/struct.Tree.html#method.watch_prefix) * [multiple keyspaces](https://docs.rs/sled/latest/sled/struct.Db.html#method.open_tree) * [merge operators](https://docs.rs/sled/latest/sled/doc/merge_operators/index.html) * forward and reverse iterators over ranges of items * a crash-safe monotonic [ID generator](https://docs.rs/sled/latest/sled/struct.Db.html#method.generate_id) capable of generating 75-125 million unique ID's per second * [zstd](https://github.com/facebook/zstd) compression (use the `compression` build feature, disabled by default) * cpu-scalable lock-free implementation * flash-optimized log-structured storage * uses modern b-tree techniques such as prefix encoding and suffix truncation for reducing the storage costs of long keys with shared prefixes. If keys are the same length and sequential then the system can avoid storing 99%+ of the key data in most cases, essentially acting like a learned index # expectations, gotchas, advice * Maybe one of the first things that seems weird is the `IVec` type. This is an inlinable `Arc`ed slice that makes some things more efficient. * Durability: **sled automatically fsyncs every 500ms by default**, which can be configured with the `flush_every_ms` configurable, or you may call `flush` / `flush_async` manually after operations. * **Transactions are optimistic** - do not interact with external state or perform IO from within a transaction closure unless it is [idempotent](https://en.wikipedia.org/wiki/Idempotent). * Internal tree node optimizations: sled performs prefix encoding on long keys with similar prefixes that are grouped together in a range, as well as suffix truncation to further reduce the indexing costs of long keys. Nodes will skip potentially expensive length and offset pointers if keys or values are all the same length (tracked separately, don't worry about making keys the same length as values), so it may improve space usage slightly if you use fixed-length keys or values. This also makes it easier to use [structured access](examples/structured.rs) as well. * sled does not support multiple open instances for the time being. Please keep sled open for the duration of your process's lifespan. It's totally safe and often quite convenient to use a global lazy_static sled instance, modulo the normal global variable trade-offs. Every operation is threadsafe, and most are implemented under the hood with lock-free algorithms that avoid blocking in hot paths. # performance * [LSM tree](https://en.wikipedia.org/wiki/Log-structured_merge-tree)-like write performance with [traditional B+ tree](https://en.wikipedia.org/wiki/B%2B_tree)-like read performance * over a billion operations in under a minute at 95% read 5% writes on 16 cores on a small dataset * measure your own workloads rather than relying on some marketing for contrived workloads # a note on lexicographic ordering and endianness If you want to store numerical keys in a way that will play nicely with sled's iterators and ordered operations, please remember to store your numerical items in big-endian form. Little endian (the default of many things) will often appear to be doing the right thing until you start working with more than 256 items (more than 1 byte), causing lexicographic ordering of the serialized bytes to diverge from the lexicographic ordering of their deserialized numerical form. * Rust integral types have built-in `to_be_bytes` and `from_be_bytes` [methods](https://doc.rust-lang.org/std/primitive.u64.html#method.from_be_bytes). * bincode [can be configured](https://docs.rs/bincode/1.2.0/bincode/struct.Config.html#method.big_endian) to store integral types in big-endian form. # interaction with async If your dataset resides entirely in cache (achievable at startup by setting the cache to a large enough value and performing a full iteration) then all reads and writes are non-blocking and async-friendly, without needing to use Futures or an async runtime. To asynchronously suspend your async task on the durability of writes, we support the [`flush_async` method](https://docs.rs/sled/latest/sled/struct.Tree.html#method.flush_async), which returns a Future that your async tasks can await the completion of if they require high durability guarantees and you are willing to pay the latency costs of fsync. Note that sled automatically tries to sync all data to disk several times per second in the background without blocking user threads. We support async subscription to events that happen on key prefixes, because the `Subscriber` struct implements `Future>`: ```rust let sled = sled::open("my_db").unwrap(); let mut sub = sled.watch_prefix(""); sled.insert(b"a", b"a").unwrap(); extreme::run(async move { while let Some(event) = (&mut sub).await { println!("got event {:?}", event); } }); ``` # minimum supported Rust version (MSRV) We support Rust 1.62 and up. # architecture lock-free tree on a lock-free pagecache on a lock-free log. the pagecache scatters partial page fragments across the log, rather than rewriting entire pages at a time as B+ trees for spinning disks historically have. on page reads, we concurrently scatter-gather reads across the log to materialize the page from its fragments. check out the [architectural outlook](https://github.com/spacejam/sled/wiki/sled-architectural-outlook) for a more detailed overview of where we're at and where we see things going! # philosophy 1. don't make the user think. the interface should be obvious. 1. don't surprise users with performance traps. 1. don't wake up operators. bring reliability techniques from academia into real-world practice. 1. don't use so much electricity. our data structures should play to modern hardware's strengths. # known issues, warnings * if reliability is your primary constraint, use SQLite. sled is beta. * if storage price performance is your primary constraint, use RocksDB. sled uses too much space sometimes. * if you have a multi-process workload that rarely writes, use LMDB. sled is architected for use with long-running, highly-concurrent workloads such as stateful services or higher-level databases. * quite young, should be considered unstable for the time being. * the on-disk format is going to change in ways that require [manual migrations](https://docs.rs/sled/latest/sled/struct.Db.html#method.export) before the `1.0.0` release! # priorities 1. A full rewrite of sled's storage subsystem is happening on a modular basis as part of the [komora project](https://github.com/komora-io), in particular the marble storage engine. This will dramatically lower both the disk space usage (space amplification) and garbage collection overhead (write amplification) of sled. 2. The memory layout of tree nodes is being completely rewritten to reduce fragmentation and eliminate serialization costs. 3. The merge operator feature will change into a trigger feature that resembles traditional database triggers, allowing state to be modified as part of the same atomic writebatch that triggered it for retaining serializability with reactive semantics. # fund feature development Like what we're doing? Help us out via [GitHub Sponsors](https://github.com/sponsors/spacejam)! ================================================ FILE: RELEASE_CHECKLIST.md ================================================ # Release Checklist This checklist must be completed before publishing a release of any kind. Over time, anything in this list that can be turned into an automated test should be, but there are still some big blind spots. ## API stability - [ ] rust-flavored semver respected ## Performance - [ ] micro-benchmark regressions should not happen unless newly discovered correctness criteria demands them - [ ] mixed point operation latency distribution should narrow over time - [ ] sequential operation average throughput should increase over time - [ ] workloads should pass TSAN and ASAN on macOS. Linux should additionally pass LSAN & MSAN. - [ ] workload write and space amplification thresholds should see no regressions ## Concurrency Audit - [ ] any new `Guard` objects are dropped inside the rayon threadpool - [ ] no new EBR `Collector`s, as they destroy causality. These will be optimized in-bulk in the future. - [ ] no code assumes a recently read page pointer will remain unchanged (transactions may change this if reads are inline) - [ ] no calls to `rand::thread_rng` from a droppable function (anything in the SegmentAccountant) ## Burn-In - [ ] fuzz tests should run at least 24 hours each with zero crashes - [ ] sequential and point workloads run at least 24 hours in constrained docker container without OOM / out of disk ================================================ FILE: SAFETY.md ================================================ # sled safety model This document applies [STPA](http://psas.scripts.mit.edu/home/get_file.php?name=STPA_handbook.pdf)-style hazard analysis to the sled embedded database for the purpose of guiding design and testing efforts to prevent unacceptable losses. Outline * [purpose of analysis](#purpose-of-analysis) * [losses](#losses) * [system boundary](#system-boundary) * [hazards](#hazards) * [leading indicators](#leading-indicators) * [constraints](#constraints) * [model of control structure](#model-of-control-structure) * [identify unsafe control actions](#identify-unsafe-control-actions) * [identify loss scenarios][#identify-loss-scenarios) * [resources for learning more about STAMP, STPA, and CAST](#resources) # Purpose of Analysis ## Losses We wish to prevent the following undesirable situations: * data loss * inconsistent (non-linearizable) data access * process crash * resource exhaustion ## System Boundary We draw the line between system and environment where we can reasonably invest our efforts to prevent losses. Inside the boundary: * codebase * put safe control actions into place that prevent losses * documentation * show users how to use sled safely * recommend hardware, kernels, user code Outside the boundary: * Direct changes to hardware, kernels, user code ## Hazards These hazards can result in the above losses: * data may be lost if * bugs in the logging system * `Db::flush` fails to make previous writes durable * bugs in the GC system * the old location is overwritten before the defragmented location becomes durable * bugs in the recovery system * hardare failures * consistency violations may be caused by * transaction concurrency control failure to enforce linearizability (strict serializability) * non-linearizable lock-free single-key operations * panic * of user threads * IO threads * flusher & GC thread * indexing * unwraps/expects * failed TryInto/TryFrom + unwrap * persistent storage exceeding (2 + N concurrent writers) * logical data size * in-memory cache exceeding the configured cache size * caused by incorrect calculation of cache * use-after-free * data race * memory leak * integer overflow * buffer overrun * uninitialized memory access ## Constraints # Models of Control Structures for each control action we have, consider: 1. what hazards happen when we fail to apply it / it does not exist? 2. what hazards happen when we do apply it 3. what hazards happen when we apply it too early or too late? 4. what hazards happen if we apply it for too long or not long enough? durability model * recovery * LogIter::max_lsn * return None if last_lsn_in_batch >= self.max_lsn * batch requirement set to last reservation base + inline len - 1 * reserve bumps * bump_atomic_lsn(&self.iobufs.max_reserved_lsn, reservation_lsn + inline_buf_len as Lsn - 1); lock-free linearizability model transactional linearizability (strict serializability) model panic model memory usage model storage usage model ================================================ FILE: SECURITY.md ================================================ # Security Policy ## Reporting a Vulnerability sled uses some unsafe functionality in the core lock-free algorithms, and in a few places to more efficiently copy data. Please contact [Tyler Neely](mailto:tylerneely@gmail.com?subject=sled%20security%20issue) immediately if you find any vulnerability, and I will work with you to fix the issue rapidly and coordinate public disclosure with an expedited release including the fix. If you are a bug hunter or a person with a security interest, here is my mental model of memory corruption risk in the sled codebase: 1. memory issues relating to the lock-free data structures in their colder failure paths. these have been tested a bit by injecting delays into random places, but this is still an area with elevated risk 1. anywhere the `unsafe` keyword is used ================================================ FILE: art/CREDITS ================================================ original tree logo with face: https://twitter.com/daiyitastic anti-transphobia additions: spacejam ================================================ FILE: code-of-conduct.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, 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. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers 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, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at tylerneely@gmail.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org ================================================ FILE: examples/bench.rs ================================================ use std::path::Path; use std::sync::Barrier; use std::thread::scope; use std::time::{Duration, Instant}; use std::{fs, io}; use num_format::{Locale, ToFormattedString}; use sled::{Config, Db as SledDb}; type Db = SledDb<1024>; const N_WRITES_PER_THREAD: u32 = 4 * 1024 * 1024; const MAX_CONCURRENCY: u32 = 4; const CONCURRENCY: &[usize] = &[/*1, 2, 4,*/ MAX_CONCURRENCY as _]; const BYTES_PER_ITEM: u32 = 8; trait Databench: Clone + Send { type READ: AsRef<[u8]>; const NAME: &'static str; const PATH: &'static str; fn open() -> Self; fn remove_generic(&self, key: &[u8]); fn insert_generic(&self, key: &[u8], value: &[u8]); fn get_generic(&self, key: &[u8]) -> Option; fn flush_generic(&self); fn print_stats(&self); } impl Databench for Db { type READ = sled::InlineArray; const NAME: &'static str = "sled 1.0.0-alpha"; const PATH: &'static str = "timing_test.sled-new"; fn open() -> Self { sled::Config { path: Self::PATH.into(), zstd_compression_level: 3, cache_capacity_bytes: 1024 * 1024 * 1024, entry_cache_percent: 20, flush_every_ms: Some(200), ..Config::default() } .open() .unwrap() } fn insert_generic(&self, key: &[u8], value: &[u8]) { self.insert(key, value).unwrap(); } fn remove_generic(&self, key: &[u8]) { self.remove(key).unwrap(); } fn get_generic(&self, key: &[u8]) -> Option { self.get(key).unwrap() } fn flush_generic(&self) { self.flush().unwrap(); } fn print_stats(&self) { dbg!(self.stats()); } } /* impl Databench for old_sled::Db { type READ = old_sled::IVec; const NAME: &'static str = "sled 0.34.7"; const PATH: &'static str = "timing_test.sled-old"; fn open() -> Self { old_sled::open(Self::PATH).unwrap() } fn insert_generic(&self, key: &[u8], value: &[u8]) { self.insert(key, value).unwrap(); } fn get_generic(&self, key: &[u8]) -> Option { self.get(key).unwrap() } fn flush_generic(&self) { self.flush().unwrap(); } } */ /* impl Databench for Arc { type READ = Vec; const NAME: &'static str = "rocksdb 0.21.0"; const PATH: &'static str = "timing_test.rocksdb"; fn open() -> Self { Arc::new(rocksdb::DB::open_default(Self::PATH).unwrap()) } fn insert_generic(&self, key: &[u8], value: &[u8]) { self.put(key, value).unwrap(); } fn get_generic(&self, key: &[u8]) -> Option { self.get(key).unwrap() } fn flush_generic(&self) { self.flush().unwrap(); } } */ /* struct Lmdb { env: heed::Env, db: heed::Database< heed::types::UnalignedSlice, heed::types::UnalignedSlice, >, } impl Clone for Lmdb { fn clone(&self) -> Lmdb { Lmdb { env: self.env.clone(), db: self.db.clone() } } } impl Databench for Lmdb { type READ = Vec; const NAME: &'static str = "lmdb"; const PATH: &'static str = "timing_test.lmdb"; fn open() -> Self { let _ = std::fs::create_dir_all(Self::PATH); let env = heed::EnvOpenOptions::new() .map_size(1024 * 1024 * 1024) .open(Self::PATH) .unwrap(); let db = env.create_database(None).unwrap(); Lmdb { env, db } } fn insert_generic(&self, key: &[u8], value: &[u8]) { let mut wtxn = self.env.write_txn().unwrap(); self.db.put(&mut wtxn, key, value).unwrap(); wtxn.commit().unwrap(); } fn get_generic(&self, key: &[u8]) -> Option { let rtxn = self.env.read_txn().unwrap(); let ret = self.db.get(&rtxn, key).unwrap().map(Vec::from); rtxn.commit().unwrap(); ret } fn flush_generic(&self) { // NOOP } } */ /* struct Sqlite { connection: rusqlite::Connection, } impl Clone for Sqlite { fn clone(&self) -> Sqlite { Sqlite { connection: rusqlite::Connection::open(Self::PATH).unwrap() } } } impl Databench for Sqlite { type READ = Vec; const NAME: &'static str = "sqlite"; const PATH: &'static str = "timing_test.sqlite"; fn open() -> Self { let connection = rusqlite::Connection::open(Self::PATH).unwrap(); connection .execute( "create table if not exists bench ( key integer primary key, val integer not null )", [], ) .unwrap(); Sqlite { connection } } fn insert_generic(&self, key: &[u8], value: &[u8]) { loop { let res = self.connection.execute( "insert or ignore into bench (key, val) values (?1, ?2)", [ format!("{}", u32::from_be_bytes(key.try_into().unwrap())), format!( "{}", u32::from_be_bytes(value.try_into().unwrap()) ), ], ); if res.is_ok() { break; } } } fn get_generic(&self, key: &[u8]) -> Option { let mut stmt = self .connection .prepare("SELECT b.val from bench b WHERE key = ?1") .unwrap(); let mut rows = stmt.query([u32::from_be_bytes(key.try_into().unwrap())]).unwrap(); let value = rows.next().unwrap()?; value.get(0).ok() } fn flush_generic(&self) { // NOOP } } */ fn allocated() -> usize { #[cfg(feature = "testing-count-allocator")] { return sled::alloc::allocated(); } 0 } fn freed() -> usize { #[cfg(feature = "testing-count-allocator")] { return sled::alloc::freed(); } 0 } fn resident() -> usize { #[cfg(feature = "testing-count-allocator")] { return sled::alloc::resident(); } 0 } fn inserts(store: &D) -> Vec { println!("{} inserts", D::NAME); let mut i = 0_u32; let factory = move || { i += 1; (store.clone(), i - 1) }; let f = |state: (D, u32)| { let (store, offset) = state; let start = N_WRITES_PER_THREAD * offset; let end = N_WRITES_PER_THREAD * (offset + 1); for i in start..end { let k: &[u8] = &i.to_be_bytes(); store.insert_generic(k, k); } }; let mut ret = vec![]; for concurrency in CONCURRENCY { let insert_elapsed = execute_lockstep_concurrent(factory, f, *concurrency); let flush_timer = Instant::now(); store.flush_generic(); let wps = (N_WRITES_PER_THREAD * *concurrency as u32) as u64 * 1_000_000_u64 / u64::try_from(insert_elapsed.as_micros().max(1)) .unwrap_or(u64::MAX); ret.push(InsertStats { thread_count: *concurrency, inserts_per_second: wps, }); println!( "{} inserts/s with {concurrency} threads over {:?}, then {:?} to flush {}", wps.to_formatted_string(&Locale::en), insert_elapsed, flush_timer.elapsed(), D::NAME, ); } ret } fn removes(store: &D) -> Vec { println!("{} removals", D::NAME); let mut i = 0_u32; let factory = move || { i += 1; (store.clone(), i - 1) }; let f = |state: (D, u32)| { let (store, offset) = state; let start = N_WRITES_PER_THREAD * offset; let end = N_WRITES_PER_THREAD * (offset + 1); for i in start..end { let k: &[u8] = &i.to_be_bytes(); store.remove_generic(k); } }; let mut ret = vec![]; for concurrency in CONCURRENCY { let remove_elapsed = execute_lockstep_concurrent(factory, f, *concurrency); let flush_timer = Instant::now(); store.flush_generic(); let wps = (N_WRITES_PER_THREAD * *concurrency as u32) as u64 * 1_000_000_u64 / u64::try_from(remove_elapsed.as_micros().max(1)) .unwrap_or(u64::MAX); ret.push(RemoveStats { thread_count: *concurrency, removes_per_second: wps, }); println!( "{} removes/s with {concurrency} threads over {:?}, then {:?} to flush {}", wps.to_formatted_string(&Locale::en), remove_elapsed, flush_timer.elapsed(), D::NAME, ); } ret } fn gets(store: &D) -> Vec { println!("{} reads", D::NAME); let factory = || store.clone(); let f = |store: D| { let start = 0; let end = N_WRITES_PER_THREAD * MAX_CONCURRENCY; for i in start..end { let k: &[u8] = &i.to_be_bytes(); store.get_generic(k); } }; let mut ret = vec![]; for concurrency in CONCURRENCY { let get_stone_elapsed = execute_lockstep_concurrent(factory, f, *concurrency); let rps = (N_WRITES_PER_THREAD * MAX_CONCURRENCY * *concurrency as u32) as u64 * 1_000_000_u64 / u64::try_from(get_stone_elapsed.as_micros().max(1)) .unwrap_or(u64::MAX); ret.push(GetStats { thread_count: *concurrency, gets_per_second: rps }); println!( "{} gets/s with concurrency of {concurrency}, {:?} total reads {}", rps.to_formatted_string(&Locale::en), get_stone_elapsed, D::NAME ); } ret } fn execute_lockstep_concurrent< State: Send, Factory: FnMut() -> State, F: Sync + Fn(State), >( mut factory: Factory, f: F, concurrency: usize, ) -> Duration { let barrier = &Barrier::new(concurrency + 1); let f = &f; scope(|s| { let mut threads = vec![]; for _ in 0..concurrency { let state = factory(); let thread = s.spawn(move || { barrier.wait(); f(state); }); threads.push(thread); } barrier.wait(); let get_stone = Instant::now(); for thread in threads.into_iter() { thread.join().unwrap(); } get_stone.elapsed() }) } #[derive(Debug, Clone, Copy)] struct InsertStats { thread_count: usize, inserts_per_second: u64, } #[derive(Debug, Clone, Copy)] struct GetStats { thread_count: usize, gets_per_second: u64, } #[derive(Debug, Clone, Copy)] struct RemoveStats { thread_count: usize, removes_per_second: u64, } #[allow(unused)] #[derive(Debug, Clone)] struct Stats { post_insert_disk_space: u64, post_remove_disk_space: u64, allocated_memory: usize, freed_memory: usize, resident_memory: usize, insert_stats: Vec, get_stats: Vec, remove_stats: Vec, } impl Stats { fn print_report(&self) { println!( "bytes on disk after inserts: {}", self.post_insert_disk_space.to_formatted_string(&Locale::en) ); println!( "bytes on disk after removes: {}", self.post_remove_disk_space.to_formatted_string(&Locale::en) ); println!( "bytes in memory: {}", self.resident_memory.to_formatted_string(&Locale::en) ); for stats in &self.insert_stats { println!( "{} threads {} inserts per second", stats.thread_count, stats.inserts_per_second.to_formatted_string(&Locale::en) ); } for stats in &self.get_stats { println!( "{} threads {} gets per second", stats.thread_count, stats.gets_per_second.to_formatted_string(&Locale::en) ); } for stats in &self.remove_stats { println!( "{} threads {} removes per second", stats.thread_count, stats.removes_per_second.to_formatted_string(&Locale::en) ); } } } fn bench() -> Stats { let store = D::open(); let insert_stats = inserts(&store); let before_flush = Instant::now(); store.flush_generic(); println!("final flush took {:?} for {}", before_flush.elapsed(), D::NAME); let post_insert_disk_space = du(D::PATH.as_ref()).unwrap(); let get_stats = gets(&store); let remove_stats = removes(&store); store.print_stats(); Stats { post_insert_disk_space, post_remove_disk_space: du(D::PATH.as_ref()).unwrap(), allocated_memory: allocated(), freed_memory: freed(), resident_memory: resident(), insert_stats, get_stats, remove_stats, } } fn du(path: &Path) -> io::Result { fn recurse(mut dir: fs::ReadDir) -> io::Result { dir.try_fold(0, |acc, file| { let file = file?; let size = match file.metadata()? { data if data.is_dir() => recurse(fs::read_dir(file.path())?)?, data => data.len(), }; Ok(acc + size) }) } recurse(fs::read_dir(path)?) } fn main() { let _ = env_logger::try_init(); let new_stats = bench::(); println!( "raw data size: {}", (MAX_CONCURRENCY * N_WRITES_PER_THREAD * BYTES_PER_ITEM) .to_formatted_string(&Locale::en) ); println!("sled 1.0 space stats:"); new_stats.print_report(); /* let old_stats = bench::(); dbg!(old_stats); let new_sled_vs_old_sled_storage_ratio = new_stats.disk_space as f64 / old_stats.disk_space as f64; let new_sled_vs_old_sled_allocated_memory_ratio = new_stats.allocated_memory as f64 / old_stats.allocated_memory as f64; let new_sled_vs_old_sled_freed_memory_ratio = new_stats.freed_memory as f64 / old_stats.freed_memory as f64; let new_sled_vs_old_sled_resident_memory_ratio = new_stats.resident_memory as f64 / old_stats.resident_memory as f64; dbg!(new_sled_vs_old_sled_storage_ratio); dbg!(new_sled_vs_old_sled_allocated_memory_ratio); dbg!(new_sled_vs_old_sled_freed_memory_ratio); dbg!(new_sled_vs_old_sled_resident_memory_ratio); let rocksdb_stats = bench::>(); bench::(); bench::(); */ /* let new_sled_vs_rocksdb_storage_ratio = new_stats.disk_space as f64 / rocksdb_stats.disk_space as f64; let new_sled_vs_rocksdb_allocated_memory_ratio = new_stats.allocated_memory as f64 / rocksdb_stats.allocated_memory as f64; let new_sled_vs_rocksdb_freed_memory_ratio = new_stats.freed_memory as f64 / rocksdb_stats.freed_memory as f64; let new_sled_vs_rocksdb_resident_memory_ratio = new_stats.resident_memory as f64 / rocksdb_stats.resident_memory as f64; dbg!(new_sled_vs_rocksdb_storage_ratio); dbg!(new_sled_vs_rocksdb_allocated_memory_ratio); dbg!(new_sled_vs_rocksdb_freed_memory_ratio); dbg!(new_sled_vs_rocksdb_resident_memory_ratio); */ /* let scan = Instant::now(); let count = stone.iter().count(); assert_eq!(count as u64, N_WRITES_PER_THREAD); let scan_elapsed = scan.elapsed(); println!( "{} scanned items/s, total {:?}", (N_WRITES_PER_THREAD * 1_000_000) / u64::try_from(scan_elapsed.as_micros().max(1)).unwrap_or(u64::MAX), scan_elapsed ); */ /* let scan_rev = Instant::now(); let count = stone.range(..).rev().count(); assert_eq!(count as u64, N_WRITES_PER_THREAD); let scan_rev_elapsed = scan_rev.elapsed(); println!( "{} reverse-scanned items/s, total {:?}", (N_WRITES_PER_THREAD * 1_000_000) / u64::try_from(scan_rev_elapsed.as_micros().max(1)).unwrap_or(u64::MAX), scan_rev_elapsed ); */ } ================================================ FILE: fuzz/.gitignore ================================================ target corpus artifacts ================================================ FILE: fuzz/Cargo.toml ================================================ [package] name = "bloodstone-fuzz" version = "0.0.0" authors = ["Automatically generated"] publish = false edition = "2018" [package.metadata] cargo-fuzz = true [dependencies.libfuzzer-sys] version = "0.4.0" features = ["arbitrary-derive"] [dependencies] arbitrary = { version = "1.0.3", features = ["derive"] } tempfile = "3.5.0" [dependencies.sled] path = ".." features = [] # Prevent this from interfering with workspaces [workspace] members = ["."] [[bin]] name = "fuzz_model" path = "fuzz_targets/fuzz_model.rs" test = false doc = false ================================================ FILE: fuzz/fuzz_targets/fuzz_model.rs ================================================ #![no_main] #[macro_use] extern crate libfuzzer_sys; extern crate arbitrary; extern crate sled; use arbitrary::Arbitrary; use sled::{Config, Db as SledDb, InlineArray}; type Db = SledDb<3>; const KEYSPACE: u64 = 128; #[derive(Debug)] enum Op { Get { key: InlineArray }, Insert { key: InlineArray, value: InlineArray }, Reboot, Remove { key: InlineArray }, Cas { key: InlineArray, old: Option, new: Option }, Range { start: InlineArray, end: InlineArray }, } fn keygen( u: &mut arbitrary::Unstructured<'_>, ) -> arbitrary::Result { let key_i: u64 = u.int_in_range(0..=KEYSPACE)?; Ok(key_i.to_be_bytes().as_ref().into()) } impl<'a> Arbitrary<'a> for Op { fn arbitrary( u: &mut arbitrary::Unstructured<'a>, ) -> arbitrary::Result { Ok(if u.ratio(1, 2)? { Op::Insert { key: keygen(u)?, value: keygen(u)? } } else if u.ratio(1, 2)? { Op::Get { key: keygen(u)? } } else if u.ratio(1, 2)? { Op::Reboot } else if u.ratio(1, 2)? { Op::Remove { key: keygen(u)? } } else if u.ratio(1, 2)? { Op::Cas { key: keygen(u)?, old: if u.ratio(1, 2)? { Some(keygen(u)?) } else { None }, new: if u.ratio(1, 2)? { Some(keygen(u)?) } else { None }, } } else { let start = u.int_in_range(0..=KEYSPACE)?; let end = (start + 1).max(u.int_in_range(0..=KEYSPACE)?); Op::Range { start: start.to_be_bytes().as_ref().into(), end: end.to_be_bytes().as_ref().into(), } }) } } fuzz_target!(|ops: Vec| { let tmp_dir = tempfile::TempDir::new().unwrap(); let tmp_path = tmp_dir.path().to_owned(); let config = Config::new().path(tmp_path); let mut tree: Db = config.open().unwrap(); let mut model = std::collections::BTreeMap::new(); for (_i, op) in ops.into_iter().enumerate() { match op { Op::Insert { key, value } => { assert_eq!( tree.insert(key.clone(), value.clone()).unwrap(), model.insert(key, value) ); } Op::Get { key } => { assert_eq!(tree.get(&key).unwrap(), model.get(&key).cloned()); } Op::Reboot => { drop(tree); tree = config.open().unwrap(); } Op::Remove { key } => { assert_eq!(tree.remove(&key).unwrap(), model.remove(&key)); } Op::Range { start, end } => { let mut model_iter = model.range::(&start..&end); let mut tree_iter = tree.range(start..end); for (k1, v1) in &mut model_iter { let (k2, v2) = tree_iter .next() .expect("None returned from iter when Some expected") .expect("IO issue encountered"); assert_eq!((k1, v1), (&k2, &v2)); } assert!(tree_iter.next().is_none()); } Op::Cas { key, old, new } => { let succ = if old == model.get(&key).cloned() { if let Some(n) = &new { model.insert(key.clone(), n.clone()); } else { model.remove(&key); } true } else { false }; let res = tree .compare_and_swap(key, old.as_ref(), new) .expect("hit IO error"); if succ { assert!(res.is_ok()); } else { assert!(res.is_err()); } } }; for (key, value) in &model { assert_eq!(tree.get(key).unwrap().unwrap(), value); } for kv_res in &tree { let (key, value) = kv_res.unwrap(); assert_eq!(model.get(&key), Some(&value)); } } let mut model_iter = model.iter(); let mut tree_iter = tree.iter(); for (k1, v1) in &mut model_iter { let (k2, v2) = tree_iter.next().unwrap().unwrap(); assert_eq!((k1, v1), (&k2, &v2)); } assert!(tree_iter.next().is_none()); }); ================================================ FILE: scripts/cgtest.sh ================================================ #!/bin/sh set -e cgdelete memory:sledTest || true cgcreate -g memory:sledTest echo 100M > /sys/fs/cgroup/memory/sledTest/memory.limit_in_bytes su $SUDO_USER -c 'cargo build --release --features=testing' for test in target/release/deps/test*; do if [[ -x $test ]] then echo running test: $test cgexec -g memory:sledTest $test --test-threads=1 rm $test fi done ================================================ FILE: scripts/cross_compile.sh ================================================ #!/bin/sh set -e # checks sled's compatibility using several targets targets="wasm32-wasi wasm32-unknown-unknown aarch64-fuchsia aarch64-linux-android \ i686-linux-android i686-unknown-linux-gnu \ x86_64-linux-android x86_64-fuchsia \ mips-unknown-linux-musl aarch64-apple-ios" rustup update --no-self-update RUSTFLAGS="--cfg miri" cargo check rustup toolchain install 1.62 --no-self-update cargo clean rm Cargo.lock cargo +1.62 check for target in $targets; do echo "setting up $target..." rustup target add $target echo "checking $target..." cargo check --target $target done ================================================ FILE: scripts/execution_explorer.py ================================================ #!/usr/bin/gdb --command """ a simple python GDB script for running multithreaded programs in a way that is "deterministic enough" to tease out and replay interesting bugs. Tyler Neely 25 Sept 2017 t@jujit.su references: https://sourceware.org/gdb/onlinedocs/gdb/All_002dStop-Mode.html https://sourceware.org/gdb/onlinedocs/gdb/Non_002dStop-Mode.html https://sourceware.org/gdb/onlinedocs/gdb/Threads-In-Python.html https://sourceware.org/gdb/onlinedocs/gdb/Events-In-Python.html https://blog.0x972.info/index.php?tag=gdb.py """ import gdb import random ############################################################################### # config # ############################################################################### # set this to a number for reproducing results or None to explore randomly seed = 156112673742 # None # 951931004895 # set this to the number of valid threads in the program # {2, 3} assumes a main thread that waits on 2 workers. # {1, ... N} assumes all of the first N threads are to be explored threads_whitelist = {2, 3} # set this to the file of the binary to explore filename = "target/debug/binary" # set this to the place the threads should rendezvous before exploring entrypoint = "src/main.rs:8" # set this to after the threads are done exitpoint = "src/main.rs:12" # invariant unreachable points that should never be accessed unreachable = [ "panic_unwind::imp::panic" ] # set this to the locations you want to test interleavings for interesting = [ "src/main.rs:8", "src/main.rs:9" ] # uncomment this to output the specific commands issued to gdb gdb.execute("set trace-commands on") ############################################################################### ############################################################################### class UnreachableBreakpoint(gdb.Breakpoint): pass class DoneBreakpoint(gdb.Breakpoint): pass class InterestingBreakpoint(gdb.Breakpoint): pass class DeterministicExecutor: def __init__(self, seed=None): if seed: print("seeding with", seed) self.seed = seed random.seed(seed) else: # pick a random new seed if not provided with one self.reseed() gdb.execute("file " + filename) # non-stop is necessary to provide thread-specific # information when breakpoints are hit. gdb.execute("set non-stop on") gdb.execute("set confirm off") self.ready = set() self.finished = set() def reseed(self): random.seed() self.seed = random.randrange(1e12) print("reseeding with", self.seed) random.seed(self.seed) def restart(self): # reset inner state self.ready = set() self.finished = set() # disconnect callbacks gdb.events.stop.disconnect(self.scheduler_callback) gdb.events.exited.disconnect(self.exit_callback) # nuke all breakpoints gdb.execute("d") # end execution gdb.execute("k") # pick new seed self.reseed() self.run() def rendezvous_callback(self, event): try: self.ready.add(event.inferior_thread.num) if len(self.ready) == len(threads_whitelist): self.run_schedule() except Exception as e: # this will be thrown if breakpoint is not a part of event, # like when the event was stopped for another reason. print(e) def run(self): gdb.execute("b " + entrypoint) gdb.events.stop.connect(self.rendezvous_callback) gdb.events.exited.connect(self.exit_callback) gdb.execute("r") def run_schedule(self): print("running schedule") gdb.execute("d") gdb.events.stop.disconnect(self.rendezvous_callback) gdb.events.stop.connect(self.scheduler_callback) for bp in interesting: InterestingBreakpoint(bp) for bp in unreachable: UnreachableBreakpoint(bp) DoneBreakpoint(exitpoint) self.pick() def pick(self): threads = self.runnable_threads() if not threads: print("restarting execution after running out of valid threads") self.restart() return thread = random.choice(threads) gdb.execute("t " + str(thread.num)) gdb.execute("c") def scheduler_callback(self, event): if not isinstance(event, gdb.BreakpointEvent): print("WTF sched callback got", event.__dict__) return if isinstance(event.breakpoint, DoneBreakpoint): self.finished.add(event.inferior_thread.num) elif isinstance(event.breakpoint, UnreachableBreakpoint): print("!" * 80) print("unreachable breakpoint triggered with seed", self.seed) print("!" * 80) gdb.events.exited.disconnect(self.exit_callback) gdb.execute("q") else: print("thread", event.inferior_thread.num, "hit breakpoint at", event.breakpoint.location) self.pick() def runnable_threads(self): threads = gdb.selected_inferior().threads() def f(it): return (it.is_valid() and not it.is_exited() and it.num in threads_whitelist and it.num not in self.finished) good_threads = [it for it in threads if f(it)] good_threads.sort(key=lambda it: it.num) return good_threads def exit_callback(self, event): try: if event.exit_code != 0: print("!" * 80) print("interesting exit with seed", self.seed) print("!" * 80) else: print("happy exit") self.restart() gdb.execute("q") except Exception as e: pass de = DeterministicExecutor(seed) de.run() ================================================ FILE: scripts/instructions ================================================ #!/bin/sh # counts instructions for a standard workload set -e OUTFILE="cachegrind.stress2.`git describe --always --dirty`-`date +%s`" rm -rf default.sled || true cargo build \ --bin=stress2 \ --release # --tool=callgrind --dump-instr=yes --collect-jumps=yes --simulate-cache=yes \ # --callgrind-out-file="$OUTFILE" \ valgrind \ --tool=cachegrind \ --cachegrind-out-file="$OUTFILE" \ ./target/release/stress2 --total-ops=50000 --set-prop=1000000000000 --threads=1 LAST=`ls -t cachegrind.stress2.* | sed -n 2p` echo "comparing $LAST with new $OUTFILE" echo "--------------------------------------------------------------------------------" echo "change since last run:" echo " Ir I1mr ILmr Dr D1mr DLmr Dw D1mw DLmw" echo "--------------------------------------------------------------------------------" cg_diff $LAST $OUTFILE | tail -1 ================================================ FILE: scripts/sanitizers.sh ================================================ #!/bin/bash set -eo pipefail pushd benchmarks/stress2 rustup toolchain install nightly rustup toolchain install nightly --component rust-src rustup update export SLED_LOCK_FREE_DELAY_INTENSITY=2000 echo "msan" cargo clean export RUSTFLAGS="-Zsanitizer=memory -Zsanitizer-memory-track-origins" cargo +nightly build -Zbuild-std --target x86_64-unknown-linux-gnu sudo rm -rf default.sled sudo target/x86_64-unknown-linux-gnu/debug/stress2 --duration=30 --set-prop=100000000 --val-len=1000 --entries=100 --threads=100 sudo target/x86_64-unknown-linux-gnu/debug/stress2 --duration=30 --entries=100 sudo target/x86_64-unknown-linux-gnu/debug/stress2 --duration=30 unset MSAN_OPTIONS echo "asan" cargo clean export RUSTFLAGS="-Z sanitizer=address" export ASAN_OPTIONS="detect_odr_violation=0" cargo +nightly build --features=lock_free_delays --target x86_64-unknown-linux-gnu sudo rm -rf default.sled sudo target/x86_64-unknown-linux-gnu/debug/stress2 --duration=60 sudo target/x86_64-unknown-linux-gnu/debug/stress2 --duration=6 unset ASAN_OPTIONS echo "lsan" cargo clean export RUSTFLAGS="-Z sanitizer=leak" cargo +nightly build --features=lock_free_delays --target x86_64-unknown-linux-gnu sudo rm -rf default.sled sudo target/x86_64-unknown-linux-gnu/debug/stress2 --duration=60 sudo target/x86_64-unknown-linux-gnu/debug/stress2 --duration=6 echo "tsan" cargo clean export RUSTFLAGS="-Z sanitizer=thread" export TSAN_OPTIONS=suppressions=../../tsan_suppressions.txt sudo rm -rf default.sled cargo +nightly run --features=lock_free_delays --target x86_64-unknown-linux-gnu -- --duration=60 cargo +nightly run --features=lock_free_delays --target x86_64-unknown-linux-gnu -- --duration=6 unset RUSTFLAGS unset TSAN_OPTIONS ================================================ FILE: scripts/shufnice.sh ================================================ #!/bin/sh while true; do PID=`pgrep $1` TIDS=`ls /proc/$PID/task` TID=`echo $TIDS | tr " " "\n" | shuf -n1` NICE=$((`shuf -i 0-39 -n 1` - 20)) echo "renicing $TID to $NICE" renice -n $NICE -p $TID done ================================================ FILE: scripts/ubuntu_bench ================================================ #!/bin/sh sudo apt-get update sudo apt-get install htop dstat build-essential linux-tools-common linux-tools-generic linux-tools-`uname -r` curl https://sh.rustup.rs -sSf | sh source $HOME/.cargo/env cargo install flamegraph git clone https://github.com/spacejam/sled.git cd sled cores=$(grep -c ^processor /proc/cpuinfo) writers=(($cores / 5 + 1 )) readers=$(( ($cores / 5 + 1) * 4 )) cargo build --release --bin=stress2 --features=stress # we use sudo here to get access to symbols pushd benchmarks/stress2 cargo flamegraph --release -- --get=$readers --set=$writers ================================================ FILE: src/alloc.rs ================================================ #[cfg(any( feature = "testing-shred-allocator", feature = "testing-count-allocator" ))] pub use alloc::*; // the memshred feature causes all allocated and deallocated // memory to be set to a specific non-zero value of 0xa1 for // uninitialized allocations and 0xde for deallocated memory, // in the hope that it will cause memory errors to surface // more quickly. #[cfg(feature = "testing-shred-allocator")] mod alloc { use std::alloc::{Layout, System}; #[global_allocator] static ALLOCATOR: ShredAllocator = ShredAllocator; #[derive(Default, Debug, Clone, Copy)] struct ShredAllocator; unsafe impl std::alloc::GlobalAlloc for ShredAllocator { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { let ret = System.alloc(layout); assert_ne!(ret, std::ptr::null_mut()); std::ptr::write_bytes(ret, 0xa1, layout.size()); ret } unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { std::ptr::write_bytes(ptr, 0xde, layout.size()); System.dealloc(ptr, layout) } } } #[cfg(feature = "testing-count-allocator")] mod alloc { use std::alloc::{Layout, System}; #[global_allocator] static ALLOCATOR: CountingAllocator = CountingAllocator; static ALLOCATED: AtomicUsize = AtomicUsize::new(0); static FREED: AtomicUsize = AtomicUsize::new(0); static RESIDENT: AtomicUsize = AtomicUsize::new(0); fn allocated() -> usize { ALLOCATED.swap(0, Ordering::Relaxed) } fn freed() -> usize { FREED.swap(0, Ordering::Relaxed) } fn resident() -> usize { RESIDENT.load(Ordering::Relaxed) } #[derive(Default, Debug, Clone, Copy)] struct CountingAllocator; unsafe impl std::alloc::GlobalAlloc for CountingAllocator { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { let ret = System.alloc(layout); assert_ne!(ret, std::ptr::null_mut()); ALLOCATED.fetch_add(layout.size(), Ordering::Relaxed); RESIDENT.fetch_add(layout.size(), Ordering::Relaxed); std::ptr::write_bytes(ret, 0xa1, layout.size()); ret } unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { std::ptr::write_bytes(ptr, 0xde, layout.size()); FREED.fetch_add(layout.size(), Ordering::Relaxed); RESIDENT.fetch_sub(layout.size(), Ordering::Relaxed); System.dealloc(ptr, layout) } } } ================================================ FILE: src/block_checker.rs ================================================ use std::collections::BTreeMap; use std::panic::Location; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{LazyLock, Mutex}; static COUNTER: AtomicU64 = AtomicU64::new(0); static CHECK_INS: LazyLock = LazyLock::new(|| { std::thread::spawn(move || { let mut last_top_10 = Default::default(); loop { std::thread::sleep(std::time::Duration::from_secs(5)); last_top_10 = CHECK_INS.report(last_top_10); } }); BlockChecker::default() }); type LocationMap = BTreeMap>; #[derive(Default)] pub(crate) struct BlockChecker { state: Mutex, } impl BlockChecker { fn report(&self, last_top_10: LocationMap) -> LocationMap { let state = self.state.lock().unwrap(); println!("top 10 longest blocking sections:"); let top_10: LocationMap = state.iter().take(10).map(|(k, v)| (*k, *v)).collect(); for (id, location) in &top_10 { if last_top_10.contains_key(id) { println!("id: {}, location: {:?}", id, location); } } top_10 } fn check_in(&self, location: &'static Location) -> BlockGuard { let next_id = COUNTER.fetch_add(1, Ordering::Relaxed); let mut state = self.state.lock().unwrap(); state.insert(next_id, location); BlockGuard { id: next_id } } fn check_out(&self, id: u64) { let mut state = self.state.lock().unwrap(); state.remove(&id); } } pub(crate) struct BlockGuard { id: u64, } impl Drop for BlockGuard { fn drop(&mut self) { CHECK_INS.check_out(self.id) } } #[track_caller] pub(crate) fn track_blocks() -> BlockGuard { let caller = Location::caller(); CHECK_INS.check_in(caller) } ================================================ FILE: src/config.rs ================================================ use std::io; use std::path::{Path, PathBuf}; use std::sync::Arc; use fault_injection::{annotate, fallible}; use tempdir::TempDir; use crate::Db; macro_rules! builder { ($(($name:ident, $t:ty, $desc:expr)),*) => { $( #[doc=$desc] pub fn $name(mut self, to: $t) -> Self { self.$name = to; self } )* } } #[derive(Debug, Clone)] pub struct Config { /// The base directory for storing the database. pub path: PathBuf, /// Cache size in **bytes**. Default is 512mb. pub cache_capacity_bytes: usize, /// The percentage of the cache that is dedicated to the /// scan-resistant entry cache. pub entry_cache_percent: u8, /// Start a background thread that flushes data to disk /// every few milliseconds. Defaults to every 200ms. pub flush_every_ms: Option, /// The zstd compression level to use when writing data to disk. Defaults to 3. pub zstd_compression_level: i32, /// This is only set to `Some` for objects created via /// `Config::tmp`, and will remove the storage directory /// when the final Arc drops. pub tempdir_deleter: Option>, /// A float between 0.0 and 1.0 that controls how much fragmentation can /// exist in a file before GC attempts to recompact it. pub target_heap_file_fill_ratio: f32, /// Values larger than this configurable will be stored as separate blob pub max_inline_value_threshold: usize, } impl Default for Config { fn default() -> Config { Config { path: "bloodstone.default".into(), flush_every_ms: Some(200), cache_capacity_bytes: 512 * 1024 * 1024, entry_cache_percent: 20, zstd_compression_level: 3, tempdir_deleter: None, target_heap_file_fill_ratio: 0.9, max_inline_value_threshold: 4096, } } } impl Config { /// Returns a default `Config` pub fn new() -> Config { Config::default() } /// Returns a config with the `path` initialized to a system /// temporary directory that will be deleted when this `Config` /// is dropped. pub fn tmp() -> io::Result { let tempdir = fallible!(tempdir::TempDir::new("sled_tmp")); Ok(Config { path: tempdir.path().into(), tempdir_deleter: Some(Arc::new(tempdir)), ..Config::default() }) } /// Set the path of the database (builder). pub fn path>(mut self, path: P) -> Config { self.path = path.as_ref().to_path_buf(); self } builder!( (flush_every_ms, Option, "Start a background thread that flushes data to disk every few milliseconds. Defaults to every 200ms."), (cache_capacity_bytes, usize, "Cache size in **bytes**. Default is 512mb."), (entry_cache_percent, u8, "The percentage of the cache that is dedicated to the scan-resistant entry cache."), (zstd_compression_level, i32, "The zstd compression level to use when writing data to disk. Defaults to 3."), (target_heap_file_fill_ratio, f32, "A float between 0.0 and 1.0 that controls how much fragmentation can exist in a file before GC attempts to recompact it."), (max_inline_value_threshold, usize, "Values larger than this configurable will be stored as separate blob") ); pub fn open( &self, ) -> io::Result> { if LEAF_FANOUT < 3 { return Err(annotate!(io::Error::new( io::ErrorKind::Unsupported, "Db's LEAF_FANOUT const generic must be 3 or greater." ))); } Db::open_with_config(self) } } ================================================ FILE: src/db.rs ================================================ use std::collections::HashMap; use std::fmt; use std::io; use std::sync::{Arc, mpsc}; use std::time::{Duration, Instant}; use parking_lot::Mutex; use crate::*; /// sled 1.0 alpha :) /// /// One of the main differences between this and sled 0.34 is that /// `Db` and `Tree` now have a `LEAF_FANOUT` const generic parameter. /// This parameter is an interesting single-knob performance tunable /// that allows users to traverse the performance-vs-efficiency /// trade-off spectrum. The default value of `1024` causes keys and /// values to be more efficiently compressed when stored on disk, /// but for larger-than-memory random workloads it may be advantageous /// to lower `LEAF_FANOUT` to between `16` to `256`, depending on your /// efficiency requirements. A lower value will also cause contention /// to be reduced for frequently accessed data. This value cannot be /// changed after creating the database. /// /// As an alpha release, please do not expect this to be safe for /// business-critical use cases. However, if you would like this to /// serve your business-critical use cases over time, please give it /// a shot in a low-risk non-production environment and report any /// issues you encounter in a github issue. /// /// Note that `Db` implements `Deref` for the default `Tree` (sled's /// version of namespaces / keyspaces / buckets), but you can create /// and use others using `Db::open_tree`. #[derive(Clone)] pub struct Db { config: Config, _shutdown_dropper: Arc>, cache: ObjectCache, trees: Arc>>>, collection_id_allocator: Arc, collection_name_mapping: Tree, default_tree: Tree, was_recovered: bool, } impl std::ops::Deref for Db { type Target = Tree; fn deref(&self) -> &Tree { &self.default_tree } } impl IntoIterator for &Db { type Item = io::Result<(InlineArray, InlineArray)>; type IntoIter = crate::Iter; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl fmt::Debug for Db { fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result { let alternate = w.alternate(); let mut debug_struct = w.debug_struct(&format!("Db<{}>", LEAF_FANOUT)); if alternate { debug_struct .field("global_error", &self.check_error()) .field( "data", &format!("{:?}", self.iter().collect::>()), ) .finish() } else { debug_struct.field("global_error", &self.check_error()).finish() } } } fn flusher( cache: ObjectCache, shutdown_signal: mpsc::Receiver>, flush_every_ms: usize, ) { let interval = Duration::from_millis(flush_every_ms as _); let mut last_flush_duration = Duration::default(); let flush = || { let flush_res_res = std::panic::catch_unwind(|| cache.flush()); match flush_res_res { Ok(Ok(_)) => { // don't abort. return; } Ok(Err(flush_failure)) => { log::error!( "Db flusher encountered error while flushing: {:?}", flush_failure ); cache.set_error(&flush_failure); } Err(panicked) => { log::error!( "Db flusher panicked while flushing: {:?}", panicked ); cache.set_error(&io::Error::other( "Db flusher panicked while flushing".to_string(), )); } } std::process::abort(); }; loop { let recv_timeout = interval .saturating_sub(last_flush_duration) .max(Duration::from_millis(1)); if let Ok(shutdown_sender) = shutdown_signal.recv_timeout(recv_timeout) { flush(); // this is probably unnecessary but it will avoid issues // if egregious bugs get introduced that trigger it cache.set_error(&io::Error::other( "system has been shut down".to_string(), )); assert!(cache.is_clean()); drop(cache); if let Err(e) = shutdown_sender.send(()) { log::error!( "Db flusher could not ack shutdown to requestor: {e:?}" ); } log::debug!( "flush thread terminating after signalling to requestor" ); return; } let before_flush = Instant::now(); flush(); last_flush_duration = before_flush.elapsed(); } } impl Drop for Db { fn drop(&mut self) { if self.config.flush_every_ms.is_none() { if let Err(e) = self.flush() { log::error!("failed to flush Db on Drop: {e:?}"); } } else { // otherwise, it is expected that the flusher thread will // flush while shutting down the final Db/Tree instance } } } impl Db { #[cfg(feature = "for-internal-testing-only")] fn validate(&self) -> io::Result<()> { // for each tree, iterate over index, read node and assert low key matches // and assert first time we've ever seen node ID let mut ever_seen = std::collections::HashSet::new(); let before = std::time::Instant::now(); #[cfg(feature = "for-internal-testing-only")] let _b0 = crate::block_checker::track_blocks(); for (_cid, tree) in self.trees.lock().iter() { let mut hi_none_count = 0; let mut last_hi = None; for (low, node) in tree.index.iter() { // ensure we haven't reused the object_id across Trees assert!(ever_seen.insert(node.object_id)); let (read_low, node_mu, read_node) = tree.page_in(&low, self.cache.current_flush_epoch())?; assert_eq!(read_node.object_id, node.object_id); assert_eq!(node_mu.leaf.as_ref().unwrap().lo, low); assert_eq!(read_low, low); if let Some(hi) = &last_hi { assert_eq!(hi, &node_mu.leaf.as_ref().unwrap().lo); } if let Some(hi) = &node_mu.leaf.as_ref().unwrap().hi { last_hi = Some(hi.clone()); } else { assert_eq!(hi_none_count, 0); hi_none_count += 1; } } // each tree should have exactly one leaf with no max hi key assert_eq!(hi_none_count, 1); } log::debug!( "{} leaves looking good after {} micros", ever_seen.len(), before.elapsed().as_micros() ); Ok(()) } pub fn stats(&self) -> Stats { Stats { cache: self.cache.stats() } } pub fn size_on_disk(&self) -> io::Result { use std::fs::read_dir; fn recurse(mut dir: std::fs::ReadDir) -> io::Result { dir.try_fold(0, |acc, file| { let file = file?; let size = match file.metadata()? { data if data.is_dir() => recurse(read_dir(file.path())?)?, data => data.len(), }; Ok(acc + size) }) } recurse(read_dir(&self.cache.config.path)?) } /// Returns `true` if the database was /// recovered from a previous process. /// Note that database state is only /// guaranteed to be present up to the /// last call to `flush`! Otherwise state /// is synced to disk periodically if the /// `Config.sync_every_ms` configuration option /// is set to `Some(number_of_ms_between_syncs)` /// or if the IO buffer gets filled to /// capacity before being rotated. pub fn was_recovered(&self) -> bool { self.was_recovered } pub fn open_with_config(config: &Config) -> io::Result> { let (shutdown_tx, shutdown_rx) = mpsc::channel(); let (cache, indices, was_recovered) = ObjectCache::recover(config)?; let _shutdown_dropper = Arc::new(ShutdownDropper { shutdown_sender: Mutex::new(shutdown_tx), cache: Mutex::new(cache.clone()), }); let mut allocated_collection_ids = fnv::FnvHashSet::default(); let mut trees: HashMap> = indices .into_iter() .map(|(collection_id, index)| { assert!( allocated_collection_ids.insert(collection_id.0), "allocated_collection_ids already contained {:?}", collection_id ); ( collection_id, Tree::new( collection_id, cache.clone(), index, _shutdown_dropper.clone(), ), ) }) .collect(); let collection_name_mapping = trees.get(&NAME_MAPPING_COLLECTION_ID).unwrap().clone(); let default_tree = trees.get(&DEFAULT_COLLECTION_ID).unwrap().clone(); for kv_res in collection_name_mapping.iter() { let (_collection_name, collection_id_buf) = kv_res.unwrap(); let collection_id = CollectionId(u64::from_le_bytes( collection_id_buf.as_ref().try_into().unwrap(), )); if trees.contains_key(&collection_id) { continue; } // need to initialize tree leaf for empty collection assert!( allocated_collection_ids.insert(collection_id.0), "allocated_collection_ids already contained {:?}", collection_id ); let initial_low_key = InlineArray::default(); let empty_node = cache.allocate_default_node(collection_id); let index = Index::default(); assert!(index.insert(initial_low_key, empty_node).is_none()); let tree = Tree::new( collection_id, cache.clone(), index, _shutdown_dropper.clone(), ); trees.insert(collection_id, tree); } let collection_id_allocator = Arc::new(Allocator::from_allocated(&allocated_collection_ids)); assert_eq!(collection_name_mapping.len()? + 2, trees.len()); let ret = Db { config: config.clone(), cache: cache.clone(), default_tree, collection_name_mapping, collection_id_allocator, trees: Arc::new(Mutex::new(trees)), _shutdown_dropper, was_recovered, }; #[cfg(feature = "for-internal-testing-only")] ret.validate()?; if let Some(flush_every_ms) = ret.cache.config.flush_every_ms { let spawn_res = std::thread::Builder::new() .name("sled_flusher".into()) .spawn(move || flusher(cache, shutdown_rx, flush_every_ms)); if let Err(e) = spawn_res { return Err(io::Error::other(format!( "unable to spawn flusher thread for sled database: {:?}", e ))); } } Ok(ret) } /// A database export method for all collections in the `Db`, /// for use in sled version upgrades. Can be used in combination /// with the `import` method below on a database running a later /// version. /// /// # Panics /// /// Panics if any IO problems occur while trying /// to perform the export. /// /// # Examples /// /// If you want to migrate from one version of sled /// to another, you need to pull in both versions /// by using version renaming: /// /// `Cargo.toml`: /// /// ```toml /// [dependencies] /// sled = "0.32" /// old_sled = { version = "0.31", package = "sled" } /// ``` /// /// and in your code, remember that old versions of /// sled might have a different way to open them /// than the current `sled::open` method: /// /// ``` /// # use sled as old_sled; /// # fn main() -> Result<(), Box> { /// let old = old_sled::open("my_old_db_export")?; /// /// // may be a different version of sled, /// // the export type is version agnostic. /// let new = sled::open("my_new_db_export")?; /// /// let export = old.export(); /// new.import(export); /// /// assert_eq!(old.checksum()?, new.checksum()?); /// # drop(old); /// # drop(new); /// # let _ = std::fs::remove_dir_all("my_old_db_export"); /// # let _ = std::fs::remove_dir_all("my_new_db_export"); /// # Ok(()) } /// ``` pub fn export( &self, ) -> Vec<( CollectionType, CollectionName, impl Iterator>> + '_, )> { let trees = self.trees.lock(); let mut ret = vec![]; for kv_res in self.collection_name_mapping.iter() { let (collection_name, collection_id_buf) = kv_res.unwrap(); let collection_id = CollectionId(u64::from_le_bytes( collection_id_buf.as_ref().try_into().unwrap(), )); let tree = trees.get(&collection_id).unwrap().clone(); ret.push(( b"tree".to_vec(), collection_name.to_vec(), tree.iter().map(|kv_opt| { let kv = kv_opt.unwrap(); vec![kv.0.to_vec(), kv.1.to_vec()] }), )); } ret } /// Imports the collections from a previous database. /// /// # Panics /// /// Panics if any IO problems occur while trying /// to perform the import. /// /// # Examples /// /// If you want to migrate from one version of sled /// to another, you need to pull in both versions /// by using version renaming: /// /// `Cargo.toml`: /// /// ```toml /// [dependencies] /// sled = "0.32" /// old_sled = { version = "0.31", package = "sled" } /// ``` /// /// and in your code, remember that old versions of /// sled might have a different way to open them /// than the current `sled::open` method: /// /// ``` /// # use sled as old_sled; /// # fn main() -> Result<(), Box> { /// let old = old_sled::open("my_old_db_import")?; /// /// // may be a different version of sled, /// // the export type is version agnostic. /// let new = sled::open("my_new_db_import")?; /// /// let export = old.export(); /// new.import(export); /// /// assert_eq!(old.checksum()?, new.checksum()?); /// # drop(old); /// # drop(new); /// # let _ = std::fs::remove_dir_all("my_old_db_import"); /// # let _ = std::fs::remove_dir_all("my_new_db_import"); /// # Ok(()) } /// ``` pub fn import( &self, export: Vec<( CollectionType, CollectionName, impl Iterator>>, )>, ) { for (collection_type, collection_name, collection_iter) in export { match collection_type { ref t if t == b"tree" => { let tree = self .open_tree(collection_name) .expect("failed to open new tree during import"); for mut kv in collection_iter { let v = kv .pop() .expect("failed to get value from tree export"); let k = kv .pop() .expect("failed to get key from tree export"); let old = tree.insert(k, v).expect( "failed to insert value during tree import", ); assert!( old.is_none(), "import is overwriting existing data" ); } } other => panic!("unknown collection type {:?}", other), } } } pub fn contains_tree>(&self, name: V) -> io::Result { Ok(self.collection_name_mapping.get(name.as_ref())?.is_some()) } pub fn drop_tree>(&self, name: V) -> io::Result { let name_ref = name.as_ref(); let trees = self.trees.lock(); let tree = if let Some(collection_id_buf) = self.collection_name_mapping.get(name_ref)? { let collection_id = CollectionId(u64::from_le_bytes( collection_id_buf.as_ref().try_into().unwrap(), )); trees.get(&collection_id).unwrap() } else { return Ok(false); }; tree.clear()?; self.collection_name_mapping.remove(name_ref)?; Ok(true) } /// Open or create a new disk-backed [`Tree`] with its own keyspace, /// accessible from the `Db` via the provided identifier. pub fn open_tree>( &self, name: V, ) -> io::Result> { let name_ref = name.as_ref(); let mut trees = self.trees.lock(); if let Some(collection_id_buf) = self.collection_name_mapping.get(name_ref)? { let collection_id = CollectionId(u64::from_le_bytes( collection_id_buf.as_ref().try_into().unwrap(), )); let tree = trees.get(&collection_id).unwrap(); return Ok(tree.clone()); } let collection_id = CollectionId(self.collection_id_allocator.allocate()); let initial_low_key = InlineArray::default(); let empty_node = self.cache.allocate_default_node(collection_id); let index = Index::default(); assert!(index.insert(initial_low_key, empty_node).is_none()); let tree = Tree::new( collection_id, self.cache.clone(), index, self._shutdown_dropper.clone(), ); self.collection_name_mapping .insert(name_ref, &collection_id.0.to_le_bytes())?; trees.insert(collection_id, tree.clone()); Ok(tree) } } /// These types provide the information that allows an entire /// system to be exported and imported to facilitate /// major upgrades. It is comprised entirely /// of standard library types to be forward compatible. /// NB this definitions are expensive to change, because /// they impact the migration path. type CollectionType = Vec; type CollectionName = Vec; ================================================ FILE: src/event_verifier.rs ================================================ use std::collections::BTreeMap; use std::sync::Mutex; use crate::{FlushEpoch, ObjectId}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum State { Unallocated, Dirty, CooperativelySerialized, AddedToWriteBatch, Flushed, CleanPagedIn, PagedOut, } impl State { fn can_transition_within_epoch_to(&self, next: State) -> bool { match (self, next) { (State::Flushed, State::PagedOut) => true, (State::Flushed, _) => false, (State::AddedToWriteBatch, State::Flushed) => true, (State::AddedToWriteBatch, _) => false, (State::CleanPagedIn, State::AddedToWriteBatch) => false, (State::CleanPagedIn, State::Flushed) => false, (State::Dirty, State::AddedToWriteBatch) => true, (State::CooperativelySerialized, State::AddedToWriteBatch) => true, (State::CooperativelySerialized, _) => false, (State::Unallocated, State::AddedToWriteBatch) => true, (State::Unallocated, _) => false, (State::Dirty, State::Dirty) => true, (State::Dirty, State::CooperativelySerialized) => true, (State::Dirty, State::Unallocated) => true, (State::Dirty, _) => false, (State::CleanPagedIn, State::Dirty) => true, (State::CleanPagedIn, State::PagedOut) => true, (State::CleanPagedIn, State::CleanPagedIn) => true, (State::CleanPagedIn, State::Unallocated) => true, (State::CleanPagedIn, State::CooperativelySerialized) => true, (State::PagedOut, State::CleanPagedIn) => true, (State::PagedOut, _) => false, } } fn needs_flush(&self) -> bool { match self { State::CleanPagedIn => false, State::Flushed => false, State::PagedOut => false, _ => true, } } } #[derive(Debug, Default)] pub(crate) struct EventVerifier { flush_model: Mutex>>, } impl Drop for EventVerifier { fn drop(&mut self) { // assert that nothing is currently Dirty let flush_model = self.flush_model.lock().unwrap(); for ((oid, _epoch), history) in flush_model.iter() { if let Some((last_state, _at)) = history.last() { assert_ne!( *last_state, State::Dirty, "{oid:?} is Dirty when system shutting down" ); } } } } impl EventVerifier { pub(crate) fn mark( &self, object_id: ObjectId, epoch: FlushEpoch, state: State, at: &'static str, ) { if matches!(state, State::PagedOut) { let dirty_epochs = self.dirty_epochs(object_id); if !dirty_epochs.is_empty() { println!("{object_id:?} was paged out while having dirty epochs {dirty_epochs:?}"); self.print_debug_history_for_object(object_id); println!("{state:?} {epoch:?} {at}"); println!("invalid object state transition"); std::process::abort(); } } let mut flush_model = self.flush_model.lock().unwrap(); let history = flush_model.entry((object_id, epoch)).or_default(); if let Some((last_state, _at)) = history.last() { if !last_state.can_transition_within_epoch_to(state) { println!( "object_id {object_id:?} performed \ illegal state transition from {last_state:?} \ to {state:?} at {at} in epoch {epoch:?}." ); println!("history:"); history.push((state, at)); let active_epochs = flush_model.range( (object_id, FlushEpoch::MIN)..=(object_id, FlushEpoch::MAX), ); for ((_oid, epoch), history) in active_epochs { for (last_state, at) in history { println!("{last_state:?} {epoch:?} {at}"); } } println!("invalid object state transition"); std::process::abort(); } } history.push((state, at)); } /// Returns the FlushEpochs for which this ObjectId has unflushed /// dirty data for. fn dirty_epochs(&self, object_id: ObjectId) -> Vec { let mut dirty_epochs = vec![]; let flush_model = self.flush_model.lock().unwrap(); let active_epochs = flush_model .range((object_id, FlushEpoch::MIN)..=(object_id, FlushEpoch::MAX)); for ((_oid, epoch), history) in active_epochs { let (last_state, _at) = history.last().unwrap(); if last_state.needs_flush() { dirty_epochs.push(*epoch); } } dirty_epochs } pub(crate) fn print_debug_history_for_object(&self, object_id: ObjectId) { let flush_model = self.flush_model.lock().unwrap(); println!("history for object {:?}:", object_id); let active_epochs = flush_model .range((object_id, FlushEpoch::MIN)..=(object_id, FlushEpoch::MAX)); for ((_oid, epoch), history) in active_epochs { for (last_state, at) in history { println!("{last_state:?} {epoch:?} {at}"); } } } } ================================================ FILE: src/flush_epoch.rs ================================================ use std::num::NonZeroU64; use std::sync::atomic::{AtomicPtr, AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex}; const SEAL_BIT: u64 = 1 << 63; const SEAL_MASK: u64 = u64::MAX - SEAL_BIT; const MIN_EPOCH: u64 = 2; #[derive( Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialOrd, Ord, PartialEq, Eq, Hash, )] pub struct FlushEpoch(NonZeroU64); impl FlushEpoch { pub const MIN: FlushEpoch = FlushEpoch(NonZeroU64::MIN); #[allow(unused)] pub const MAX: FlushEpoch = FlushEpoch(NonZeroU64::MAX); pub fn increment(&self) -> FlushEpoch { FlushEpoch(NonZeroU64::new(self.0.get() + 1).unwrap()) } pub fn get(&self) -> u64 { self.0.get() } } impl concurrent_map::Minimum for FlushEpoch { const MIN: FlushEpoch = FlushEpoch::MIN; } #[derive(Debug)] pub(crate) struct FlushInvariants { max_flushed_epoch: AtomicU64, max_flushing_epoch: AtomicU64, } impl Default for FlushInvariants { fn default() -> FlushInvariants { FlushInvariants { max_flushed_epoch: (MIN_EPOCH - 1).into(), max_flushing_epoch: (MIN_EPOCH - 1).into(), } } } impl FlushInvariants { pub(crate) fn mark_flushed_epoch(&self, epoch: FlushEpoch) { let last = self.max_flushed_epoch.swap(epoch.get(), Ordering::SeqCst); assert_eq!(last + 1, epoch.get()); } pub(crate) fn mark_flushing_epoch(&self, epoch: FlushEpoch) { let last = self.max_flushing_epoch.swap(epoch.get(), Ordering::SeqCst); assert_eq!(last + 1, epoch.get()); } } #[derive(Clone, Debug)] pub(crate) struct Completion { mu: Arc>, cv: Arc, epoch: FlushEpoch, } impl Completion { pub fn epoch(&self) -> FlushEpoch { self.epoch } pub fn new(epoch: FlushEpoch) -> Completion { Completion { mu: Default::default(), cv: Default::default(), epoch } } pub fn wait_for_complete(self) -> FlushEpoch { let mut mu = self.mu.lock().unwrap(); while !*mu { mu = self.cv.wait(mu).unwrap(); } self.epoch } pub fn mark_complete(self) { self.mark_complete_inner(false); } fn mark_complete_inner(&self, previously_sealed: bool) { let mut mu = self.mu.lock().unwrap(); if !previously_sealed { // TODO reevaluate - assert!(!*mu); } log::trace!("marking epoch {:?} as complete", self.epoch); // it's possible for *mu to already be true due to this being // immediately dropped in the check_in method when we see that // the checked-in epoch has already been marked as sealed. *mu = true; drop(mu); self.cv.notify_all(); } #[cfg(test)] pub fn is_complete(&self) -> bool { *self.mu.lock().unwrap() } } pub struct FlushEpochGuard<'a> { tracker: &'a EpochTracker, previously_sealed: bool, } impl Drop for FlushEpochGuard<'_> { fn drop(&mut self) { let rc = self.tracker.rc.fetch_sub(1, Ordering::SeqCst) - 1; if rc & SEAL_MASK == 0 && (rc & SEAL_BIT) == SEAL_BIT { crate::debug_delay(); self.tracker .vacancy_notifier .mark_complete_inner(self.previously_sealed); } } } impl FlushEpochGuard<'_> { pub fn epoch(&self) -> FlushEpoch { self.tracker.epoch } } #[derive(Debug)] pub(crate) struct EpochTracker { epoch: FlushEpoch, rc: AtomicU64, vacancy_notifier: Completion, previous_flush_complete: Completion, } #[derive(Clone, Debug)] pub(crate) struct FlushEpochTracker { active_ebr: ebr::Ebr, 16, 16>, inner: Arc, } #[derive(Debug)] pub(crate) struct FlushEpochInner { counter: AtomicU64, roll_mu: Mutex<()>, current_active: AtomicPtr, } impl Drop for FlushEpochInner { fn drop(&mut self) { let vacancy_mu = self.roll_mu.lock().unwrap(); let old_ptr = self.current_active.swap(std::ptr::null_mut(), Ordering::SeqCst); if !old_ptr.is_null() { //let old: &EpochTracker = &*old_ptr; unsafe { drop(Box::from_raw(old_ptr)) } } drop(vacancy_mu); } } impl Default for FlushEpochTracker { fn default() -> FlushEpochTracker { let last = Completion::new(FlushEpoch(NonZeroU64::new(1).unwrap())); let current_active_ptr = Box::into_raw(Box::new(EpochTracker { epoch: FlushEpoch(NonZeroU64::new(MIN_EPOCH).unwrap()), rc: AtomicU64::new(0), vacancy_notifier: Completion::new(FlushEpoch( NonZeroU64::new(MIN_EPOCH).unwrap(), )), previous_flush_complete: last.clone(), })); last.mark_complete(); let current_active = AtomicPtr::new(current_active_ptr); FlushEpochTracker { inner: Arc::new(FlushEpochInner { counter: AtomicU64::new(2), roll_mu: Mutex::new(()), current_active, }), active_ebr: ebr::Ebr::default(), } } } impl FlushEpochTracker { /// Returns the epoch notifier for the previous epoch. /// Intended to be passed to a flusher that can eventually /// notify the flush-requesting thread. pub fn roll_epoch_forward(&self) -> (Completion, Completion, Completion) { let mut tracker_guard = self.active_ebr.pin(); let vacancy_mu = self.inner.roll_mu.lock().unwrap(); let flush_through = self.inner.counter.fetch_add(1, Ordering::SeqCst); let flush_through_epoch = FlushEpoch(NonZeroU64::new(flush_through).unwrap()); let new_epoch = flush_through_epoch.increment(); let forward_flush_notifier = Completion::new(flush_through_epoch); let new_active = Box::into_raw(Box::new(EpochTracker { epoch: new_epoch, rc: AtomicU64::new(0), vacancy_notifier: Completion::new(new_epoch), previous_flush_complete: forward_flush_notifier.clone(), })); let old_ptr = self.inner.current_active.swap(new_active, Ordering::SeqCst); assert!(!old_ptr.is_null()); let (last_flush_complete_notifier, vacancy_notifier) = unsafe { let old: &EpochTracker = &*old_ptr; let last = old.rc.fetch_add(SEAL_BIT + 1, Ordering::SeqCst); assert_eq!( last & SEAL_BIT, 0, "epoch {} double-sealed", flush_through ); // mark_complete_inner called via drop in a uniform way //println!("dropping flush epoch guard for epoch {flush_through}"); drop(FlushEpochGuard { tracker: old, previously_sealed: true }); (old.previous_flush_complete.clone(), old.vacancy_notifier.clone()) }; tracker_guard.defer_drop(unsafe { Box::from_raw(old_ptr) }); drop(vacancy_mu); (last_flush_complete_notifier, vacancy_notifier, forward_flush_notifier) } pub fn check_in<'a>(&self) -> FlushEpochGuard<'a> { let _tracker_guard = self.active_ebr.pin(); loop { let tracker: &'a EpochTracker = unsafe { &*self.inner.current_active.load(Ordering::SeqCst) }; let rc = tracker.rc.fetch_add(1, Ordering::SeqCst); let previously_sealed = rc & SEAL_BIT == SEAL_BIT; let guard = FlushEpochGuard { tracker, previously_sealed }; if previously_sealed { // the epoch is already closed, so we must drop the rc // and possibly notify, which is handled in the guard's // Drop impl. drop(guard); } else { return guard; } } } pub fn manually_advance_epoch(&self) { self.active_ebr.manually_advance_epoch(); } pub fn current_flush_epoch(&self) -> FlushEpoch { let current = self.inner.counter.load(Ordering::SeqCst); FlushEpoch(NonZeroU64::new(current).unwrap()) } } #[test] fn flush_epoch_basic_functionality() { let epoch_tracker = FlushEpochTracker::default(); for expected in MIN_EPOCH..1_000_000 { let g1 = epoch_tracker.check_in(); let g2 = epoch_tracker.check_in(); assert_eq!(g1.tracker.epoch.0.get(), expected); assert_eq!(g2.tracker.epoch.0.get(), expected); let previous_notifier = epoch_tracker.roll_epoch_forward().1; assert!(!previous_notifier.is_complete()); drop(g1); assert!(!previous_notifier.is_complete()); drop(g2); assert_eq!(previous_notifier.wait_for_complete().0.get(), expected); } } #[cfg(test)] fn concurrent_flush_epoch_burn_in_inner() { const N_THREADS: usize = 10; const N_OPS_PER_THREAD: usize = 3000; let fa = FlushEpochTracker::default(); let barrier = std::sync::Arc::new(std::sync::Barrier::new(21)); let pt = pagetable::PageTable::::default(); let rolls = || { let fa = fa.clone(); let barrier = barrier.clone(); let pt = &pt; move || { barrier.wait(); for _ in 0..N_OPS_PER_THREAD { let (previous, this, next) = fa.roll_epoch_forward(); let last_epoch = previous.wait_for_complete().0.get(); assert_eq!(0, pt.get(last_epoch).load(Ordering::Acquire)); let flush_through_epoch = this.wait_for_complete().0.get(); assert_eq!( 0, pt.get(flush_through_epoch).load(Ordering::Acquire) ); next.mark_complete(); } } }; let check_ins = || { let fa = fa.clone(); let barrier = barrier.clone(); let pt = &pt; move || { barrier.wait(); for _ in 0..N_OPS_PER_THREAD { let guard = fa.check_in(); let epoch = guard.epoch().0.get(); pt.get(epoch).fetch_add(1, Ordering::SeqCst); std::thread::yield_now(); pt.get(epoch).fetch_sub(1, Ordering::SeqCst); drop(guard); } } }; std::thread::scope(|s| { let mut threads = vec![]; for _ in 0..N_THREADS { threads.push(s.spawn(rolls())); threads.push(s.spawn(check_ins())); } barrier.wait(); for thread in threads.into_iter() { thread.join().expect("a test thread crashed unexpectedly"); } }); for i in 0..N_OPS_PER_THREAD * N_THREADS { assert_eq!(0, pt.get(i as u64).load(Ordering::Acquire)); } } #[test] fn concurrent_flush_epoch_burn_in() { for _ in 0..128 { concurrent_flush_epoch_burn_in_inner(); } } ================================================ FILE: src/heap.rs ================================================ use std::fmt; use std::fs; use std::io::{self, Read}; use std::num::NonZeroU64; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::atomic::{AtomicPtr, AtomicU64, Ordering, fence}; use std::time::{Duration, Instant}; use ebr::{Ebr, Guard}; use fault_injection::{annotate, fallible, maybe}; use fnv::FnvHashSet; use fs2::FileExt as _; use parking_lot::{Mutex, RwLock}; use rayon::prelude::*; use crate::object_location_mapper::{AllocatorStats, ObjectLocationMapper}; use crate::{CollectionId, Config, DeferredFree, MetadataStore, ObjectId}; const WARN: &str = "DO_NOT_PUT_YOUR_FILES_HERE"; pub(crate) const N_SLABS: usize = 78; const FILE_TARGET_FILL_RATIO: u64 = 80; const FILE_RESIZE_MARGIN: u64 = 115; const SLAB_SIZES: [usize; N_SLABS] = [ 64, // 0x40 80, // 0x50 96, // 0x60 112, // 0x70 128, // 0x80 160, // 0xa0 192, // 0xc0 224, // 0xe0 256, // 0x100 320, // 0x140 384, // 0x180 448, // 0x1c0 512, // 0x200 640, // 0x280 768, // 0x300 896, // 0x380 1024, // 0x400 1280, // 0x500 1536, // 0x600 1792, // 0x700 2048, // 0x800 2560, // 0xa00 3072, // 0xc00 3584, // 0xe00 4096, // 0x1000 5120, // 0x1400 6144, // 0x1800 7168, // 0x1c00 8192, // 0x2000 10240, // 0x2800 12288, // 0x3000 14336, // 0x3800 16384, // 0x4000 20480, // 0x5000 24576, // 0x6000 28672, // 0x7000 32768, // 0x8000 40960, // 0xa000 49152, // 0xc000 57344, // 0xe000 65536, // 0x10000 98304, // 0x1a000 131072, // 0x20000 163840, // 0x28000 196608, 262144, 393216, 524288, 786432, 1048576, 1572864, 2097152, 3145728, 4194304, 6291456, 8388608, 12582912, 16777216, 25165824, 33554432, 50331648, 67108864, 100663296, 134217728, 201326592, 268435456, 402653184, 536870912, 805306368, 1073741824, 1610612736, 2147483648, 3221225472, 4294967296, 6442450944, 8589934592, 12884901888, 17_179_869_184, // 17gb is max page size as-of now ]; #[derive(Default, Debug, Copy, Clone)] pub struct WriteBatchStats { pub heap_bytes_written: u64, pub heap_files_written_to: u64, /// Latency inclusive of fsync pub heap_write_latency: Duration, /// Latency for fsyncing files pub heap_sync_latency: Duration, pub metadata_bytes_written: u64, pub metadata_write_latency: Duration, pub truncated_files: u64, pub truncated_bytes: u64, pub truncate_latency: Duration, } #[derive(Default, Debug, Clone, Copy)] pub struct HeapStats { pub allocator: AllocatorStats, pub write_batch_max: WriteBatchStats, pub write_batch_sum: WriteBatchStats, pub truncated_file_bytes: u64, } impl WriteBatchStats { pub(crate) fn max(&self, other: &WriteBatchStats) -> WriteBatchStats { WriteBatchStats { heap_bytes_written: self .heap_bytes_written .max(other.heap_bytes_written), heap_files_written_to: self .heap_files_written_to .max(other.heap_files_written_to), heap_write_latency: self .heap_write_latency .max(other.heap_write_latency), heap_sync_latency: self .heap_sync_latency .max(other.heap_sync_latency), metadata_bytes_written: self .metadata_bytes_written .max(other.metadata_bytes_written), metadata_write_latency: self .metadata_write_latency .max(other.metadata_write_latency), truncated_files: self.truncated_files.max(other.truncated_files), truncated_bytes: self.truncated_bytes.max(other.truncated_bytes), truncate_latency: self.truncate_latency.max(other.truncate_latency), } } pub(crate) fn sum(&self, other: &WriteBatchStats) -> WriteBatchStats { use std::ops::Add; WriteBatchStats { heap_bytes_written: self .heap_bytes_written .add(other.heap_bytes_written), heap_files_written_to: self .heap_files_written_to .add(other.heap_files_written_to), heap_write_latency: self .heap_write_latency .add(other.heap_write_latency), heap_sync_latency: self .heap_sync_latency .add(other.heap_sync_latency), metadata_bytes_written: self .metadata_bytes_written .add(other.metadata_bytes_written), metadata_write_latency: self .metadata_write_latency .add(other.metadata_write_latency), truncated_files: self.truncated_files.add(other.truncated_files), truncated_bytes: self.truncated_bytes.add(other.truncated_bytes), truncate_latency: self.truncate_latency.add(other.truncate_latency), } } } const fn overhead_for_size(size: usize) -> usize { if size + 5 <= u8::MAX as usize { // crc32 + 1 byte frame 5 } else if size + 6 <= u16::MAX as usize { // crc32 + 2 byte frame 6 } else if size + 8 <= u32::MAX as usize { // crc32 + 4 byte frame 8 } else { // crc32 + 8 byte frame 12 } } fn slab_for_size(size: usize) -> u8 { let total_size = size + overhead_for_size(size); for (idx, slab_size) in SLAB_SIZES.iter().enumerate() { if *slab_size >= total_size { return u8::try_from(idx).unwrap(); } } u8::MAX } pub use inline_array::InlineArray; #[derive(Debug)] pub struct ObjectRecovery { pub object_id: ObjectId, pub collection_id: CollectionId, pub low_key: InlineArray, } pub struct HeapRecovery { pub heap: Heap, pub recovered_nodes: Vec, pub was_recovered: bool, } enum PersistentSettings { V1 { leaf_fanout: u64 }, } impl PersistentSettings { // NB: should only be called with a directory lock already exclusively acquired fn verify_or_store>( &self, path: P, _directory_lock: &std::fs::File, ) -> io::Result<()> { let settings_path = path.as_ref().join("durability_cookie"); match std::fs::read(&settings_path) { Ok(previous_bytes) => { let previous = PersistentSettings::deserialize(&previous_bytes)?; self.check_compatibility(&previous) } Err(e) if e.kind() == std::io::ErrorKind::NotFound => { std::fs::write(settings_path, self.serialize()) } Err(e) => Err(e), } } fn deserialize(buf: &[u8]) -> io::Result { let mut cursor = buf; let mut buf = [0_u8; 64]; cursor.read_exact(&mut buf)?; let version = u16::from_le_bytes([buf[0], buf[1]]); let crc_actual = (crc32fast::hash(&buf[0..60]) ^ 0xAF).to_le_bytes(); let crc_expected = &buf[60..]; if crc_actual != crc_expected { return Err(io::Error::new( io::ErrorKind::InvalidData, "encountered corrupted settings cookie with mismatched CRC.", )); } match version { 1 => { let leaf_fanout = u64::from_le_bytes(buf[2..10].try_into().unwrap()); Ok(PersistentSettings::V1 { leaf_fanout }) } _ => Err(io::Error::new( io::ErrorKind::InvalidData, "encountered unknown version number when reading settings cookie", )), } } fn check_compatibility( &self, other: &PersistentSettings, ) -> io::Result<()> { use PersistentSettings::*; match (self, other) { (V1 { leaf_fanout: lf1 }, V1 { leaf_fanout: lf2 }) => { if lf1 != lf2 { Err(io::Error::new( io::ErrorKind::Unsupported, format!( "sled was already opened with a LEAF_FANOUT const generic of {}, \ and this may not be changed after initial creation. Please use \ Db::import / Db::export to migrate, if you wish to change the \ system's format.", lf2 ), )) } else { Ok(()) } } } } fn serialize(&self) -> Vec { // format: 64 bytes in total, with the last 4 being a LE crc32 // first 2 are LE version number let mut buf = vec![]; match self { PersistentSettings::V1 { leaf_fanout } => { // LEAF_FANOUT: 8 bytes LE let version: [u8; 2] = 1_u16.to_le_bytes(); buf.extend_from_slice(&version); buf.extend_from_slice(&leaf_fanout.to_le_bytes()); } } // zero-pad the buffer assert!(buf.len() < 60); buf.resize(60, 0); let hash: u32 = crc32fast::hash(&buf) ^ 0xAF; let hash_bytes: [u8; 4] = hash.to_le_bytes(); buf.extend_from_slice(&hash_bytes); // keep the buffer to 64 bytes for easy parsing over time. assert_eq!(buf.len(), 64); buf } } #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct SlabAddress { slab_id: u8, slab_slot: [u8; 7], } impl SlabAddress { pub(crate) fn from_slab_slot(slab: u8, slot: u64) -> SlabAddress { let slot_bytes = slot.to_be_bytes(); assert_eq!(slot_bytes[0], 0); SlabAddress { slab_id: slab, slab_slot: slot_bytes[1..].try_into().unwrap(), } } #[inline] pub const fn slab(&self) -> u8 { self.slab_id } #[inline] pub const fn slot(&self) -> u64 { u64::from_be_bytes([ 0, self.slab_slot[0], self.slab_slot[1], self.slab_slot[2], self.slab_slot[3], self.slab_slot[4], self.slab_slot[5], self.slab_slot[6], ]) } } impl From for SlabAddress { fn from(i: NonZeroU64) -> SlabAddress { let i = i.get(); let bytes = i.to_be_bytes(); SlabAddress { slab_id: bytes[0] - 1, slab_slot: bytes[1..].try_into().unwrap(), } } } impl From for NonZeroU64 { fn from(sa: SlabAddress) -> NonZeroU64 { NonZeroU64::new(u64::from_be_bytes([ sa.slab_id + 1, sa.slab_slot[0], sa.slab_slot[1], sa.slab_slot[2], sa.slab_slot[3], sa.slab_slot[4], sa.slab_slot[5], sa.slab_slot[6], ])) .unwrap() } } #[cfg(unix)] mod sys_io { use std::io; use std::os::unix::fs::FileExt; use super::*; pub(super) fn read_exact_at( file: &fs::File, buf: &mut [u8], offset: u64, ) -> io::Result<()> { match maybe!(file.read_exact_at(buf, offset)) { Ok(r) => Ok(r), Err(e) => { // FIXME BUG 3: failed to read 64 bytes at offset 192 from file with len 192 println!( "failed to read {} bytes at offset {} from file with len {}", buf.len(), offset, file.metadata().unwrap().len(), ); let _ = dbg!(std::backtrace::Backtrace::force_capture()); Err(e) } } } pub(super) fn write_all_at( file: &fs::File, buf: &[u8], offset: u64, ) -> io::Result<()> { maybe!(file.write_all_at(buf, offset)) } } #[cfg(windows)] mod sys_io { use std::os::windows::fs::FileExt; use super::*; pub(super) fn read_exact_at( file: &fs::File, mut buf: &mut [u8], mut offset: u64, ) -> io::Result<()> { while !buf.is_empty() { match maybe!(file.seek_read(buf, offset)) { Ok(0) => break, Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; offset += n as u64; } Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {} Err(e) => return Err(annotate!(e)), } } if !buf.is_empty() { Err(annotate!(io::Error::new( io::ErrorKind::UnexpectedEof, "failed to fill whole buffer" ))) } else { Ok(()) } } pub(super) fn write_all_at( file: &fs::File, mut buf: &[u8], mut offset: u64, ) -> io::Result<()> { while !buf.is_empty() { match maybe!(file.seek_write(buf, offset)) { Ok(0) => { return Err(annotate!(io::Error::new( io::ErrorKind::WriteZero, "failed to write whole buffer", ))); } Ok(n) => { buf = &buf[n..]; offset += n as u64; } Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {} Err(e) => return Err(annotate!(e)), } } Ok(()) } } #[derive(Debug)] struct Slab { file: fs::File, slot_size: usize, max_live_slot_since_last_truncation: AtomicU64, } impl Slab { fn sync(&self) -> io::Result<()> { self.file.sync_all() } fn read( &self, slot: u64, _guard: &mut Guard<'_, DeferredFree, 16, 16>, ) -> io::Result> { log::trace!("reading from slot {} in slab {}", slot, self.slot_size); let mut data = Vec::with_capacity(self.slot_size); unsafe { data.set_len(self.slot_size); } let whence = self.slot_size as u64 * slot; maybe!(sys_io::read_exact_at(&self.file, &mut data, whence))?; let hash_actual: [u8; 4] = (crc32fast::hash(&data[..self.slot_size - 4]) ^ 0xAF).to_le_bytes(); let hash_expected = &data[self.slot_size - 4..]; if hash_expected != hash_actual { return Err(annotate!(io::Error::new( io::ErrorKind::InvalidData, "crc mismatch - data corruption detected" ))); } let len: usize = if self.slot_size <= u8::MAX as usize { // crc32 + 1 byte frame usize::from(data[self.slot_size - 5]) } else if self.slot_size <= u16::MAX as usize { // crc32 + 2 byte frame let mut size_bytes: [u8; 2] = [0; 2]; size_bytes .copy_from_slice(&data[self.slot_size - 6..self.slot_size - 4]); usize::from(u16::from_le_bytes(size_bytes)) } else if self.slot_size <= u32::MAX as usize { // crc32 + 4 byte frame let mut size_bytes: [u8; 4] = [0; 4]; size_bytes .copy_from_slice(&data[self.slot_size - 8..self.slot_size - 4]); usize::try_from(u32::from_le_bytes(size_bytes)).unwrap() } else { // crc32 + 8 byte frame let mut size_bytes: [u8; 8] = [0; 8]; size_bytes.copy_from_slice( &data[self.slot_size - 12..self.slot_size - 4], ); usize::try_from(u64::from_le_bytes(size_bytes)).unwrap() }; data.truncate(len); Ok(data) } fn write(&self, slot: u64, mut data: Vec) -> io::Result<()> { let len = data.len(); assert!(len + overhead_for_size(data.len()) <= self.slot_size); data.resize(self.slot_size, 0); if self.slot_size <= u8::MAX as usize { // crc32 + 1 byte frame data[self.slot_size - 5] = u8::try_from(len).unwrap(); } else if self.slot_size <= u16::MAX as usize { // crc32 + 2 byte frame let size_bytes: [u8; 2] = u16::try_from(len).unwrap().to_le_bytes(); data[self.slot_size - 6..self.slot_size - 4] .copy_from_slice(&size_bytes); } else if self.slot_size <= u32::MAX as usize { // crc32 + 4 byte frame let size_bytes: [u8; 4] = u32::try_from(len).unwrap().to_le_bytes(); data[self.slot_size - 8..self.slot_size - 4] .copy_from_slice(&size_bytes); } else { // crc32 + 8 byte frame let size_bytes: [u8; 8] = u64::try_from(len).unwrap().to_le_bytes(); data[self.slot_size - 12..self.slot_size - 4] .copy_from_slice(&size_bytes); } let hash: [u8; 4] = (crc32fast::hash(&data[..self.slot_size - 4]) ^ 0xAF).to_le_bytes(); data[self.slot_size - 4..].copy_from_slice(&hash); let whence = self.slot_size as u64 * slot; log::trace!("writing to slot {} in slab {}", slot, self.slot_size); sys_io::write_all_at(&self.file, &data, whence) } } fn set_error( global_error: &AtomicPtr<(io::ErrorKind, String)>, error: &io::Error, ) { let kind = error.kind(); let reason = error.to_string(); let boxed = Box::new((kind, reason)); let ptr = Box::into_raw(boxed); if global_error .compare_exchange( std::ptr::null_mut(), ptr, Ordering::SeqCst, Ordering::SeqCst, ) .is_err() { // global fatal error already installed, drop this one unsafe { drop(Box::from_raw(ptr)); } } } #[derive(Debug)] pub enum Update { Store { object_id: ObjectId, collection_id: CollectionId, low_key: InlineArray, data: Vec, }, Free { object_id: ObjectId, collection_id: CollectionId, }, } impl Update { #[allow(unused)] pub(crate) fn object_id(&self) -> ObjectId { match self { Update::Store { object_id, .. } | Update::Free { object_id, .. } => *object_id, } } } #[derive(Debug, PartialOrd, Ord, PartialEq, Eq)] pub enum UpdateMetadata { Store { object_id: ObjectId, collection_id: CollectionId, low_key: InlineArray, location: NonZeroU64, }, Free { object_id: ObjectId, collection_id: CollectionId, }, } impl UpdateMetadata { pub fn object_id(&self) -> ObjectId { match self { UpdateMetadata::Store { object_id, .. } | UpdateMetadata::Free { object_id, .. } => *object_id, } } } #[derive(Debug, Default, Clone, Copy)] struct WriteBatchStatTracker { sum: WriteBatchStats, max: WriteBatchStats, } #[derive(Clone)] pub struct Heap { path: PathBuf, slabs: Arc<[Slab; N_SLABS]>, table: ObjectLocationMapper, metadata_store: Arc>, free_ebr: Ebr, global_error: Arc>, #[allow(unused)] directory_lock: Arc, stats: Arc>, truncated_file_bytes: Arc, } impl fmt::Debug for Heap { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Heap") .field("path", &self.path) .field("stats", &self.stats()) .finish() } } impl Heap { pub fn recover( leaf_fanout: usize, config: &Config, ) -> io::Result { let path = &config.path; log::trace!("recovering Heap at {:?}", path); let slabs_dir = path.join("slabs"); // TODO NOCOMMIT let sync_status = std::process::Command::new("sync") .status() .map(|status| status.success()); if !matches!(sync_status, Ok(true)) { log::warn!( "sync command before recovery failed: {:?}", sync_status ); } // initialize directories if not present let mut was_recovered = true; for p in [path, &slabs_dir] { if let Err(e) = fs::read_dir(p) { if e.kind() == io::ErrorKind::NotFound { fallible!(fs::create_dir_all(p)); was_recovered = false; continue; } } maybe!(fs::File::open(p).and_then(|f| f.sync_all()))?; } let _ = fs::File::create(path.join(WARN)); let mut file_lock_opts = fs::OpenOptions::new(); file_lock_opts.create(false).read(false).write(false); let directory_lock = fallible!(fs::File::open(path)); fallible!(directory_lock.try_lock_exclusive()); maybe!(fs::File::open(&slabs_dir).and_then(|f| f.sync_all()))?; maybe!(directory_lock.sync_all())?; let persistent_settings = PersistentSettings::V1 { leaf_fanout: leaf_fanout as u64 }; persistent_settings.verify_or_store(path, &directory_lock)?; let (metadata_store, recovered_metadata) = MetadataStore::recover(path.join("metadata"))?; let table = ObjectLocationMapper::new( &recovered_metadata, config.target_heap_file_fill_ratio, ); let mut recovered_nodes = Vec::::with_capacity(recovered_metadata.len()); for update_metadata in recovered_metadata { match update_metadata { UpdateMetadata::Store { object_id, collection_id, location: _, low_key, } => { recovered_nodes.push(ObjectRecovery { object_id, collection_id, low_key, }); } UpdateMetadata::Free { .. } => { unreachable!() } } } let mut slabs = vec![]; let mut slab_opts = fs::OpenOptions::new(); slab_opts.create(true).read(true).write(true); for slot_size in &SLAB_SIZES { let slab_path = slabs_dir.join(format!("{}", slot_size)); let file = fallible!(slab_opts.open(slab_path)); slabs.push(Slab { slot_size: *slot_size, file, max_live_slot_since_last_truncation: AtomicU64::new(0), }) } maybe!(fs::File::open(&slabs_dir).and_then(|f| f.sync_all()))?; log::debug!("recovery of Heap at {:?} complete", path); Ok(HeapRecovery { heap: Heap { slabs: Arc::new(slabs.try_into().unwrap()), path: path.into(), table, global_error: metadata_store.get_global_error_arc(), metadata_store: Arc::new(Mutex::new(metadata_store)), directory_lock: Arc::new(directory_lock), free_ebr: Ebr::default(), truncated_file_bytes: Arc::default(), stats: Arc::default(), }, recovered_nodes, was_recovered, }) } pub fn get_global_error_arc( &self, ) -> Arc> { self.global_error.clone() } fn check_error(&self) -> io::Result<()> { let err_ptr: *const (io::ErrorKind, String) = self.global_error.load(Ordering::Acquire); if err_ptr.is_null() { Ok(()) } else { let deref: &(io::ErrorKind, String) = unsafe { &*err_ptr }; Err(io::Error::new(deref.0, deref.1.clone())) } } fn set_error(&self, error: &io::Error) { set_error(&self.global_error, error); } pub fn manually_advance_epoch(&self) { self.free_ebr.manually_advance_epoch(); } pub fn stats(&self) -> HeapStats { let truncated_file_bytes = self.truncated_file_bytes.load(Ordering::Acquire); let stats = self.stats.read(); HeapStats { truncated_file_bytes, allocator: self.table.stats(), write_batch_max: stats.max, write_batch_sum: stats.sum, } } pub fn read(&self, object_id: ObjectId) -> Option>> { if let Err(e) = self.check_error() { return Some(Err(e)); } let mut guard = self.free_ebr.pin(); let slab_address = self.table.get_location_for_object(object_id)?; let slab = &self.slabs[usize::from(slab_address.slab_id)]; match slab.read(slab_address.slot(), &mut guard) { Ok(bytes) => Some(Ok(bytes)), Err(e) => { let annotated = annotate!(e); self.set_error(&annotated); Some(Err(annotated)) } } } pub fn write_batch( &self, batch: Vec, ) -> io::Result { self.check_error()?; let metadata_store = self.metadata_store.try_lock() .expect("write_batch called concurrently! major correctness assumpiton violated"); let mut guard = self.free_ebr.pin(); let slabs = &self.slabs; let table = &self.table; let heap_bytes_written = AtomicU64::new(0); let heap_files_used_0_to_63 = AtomicU64::new(0); let heap_files_used_64_to_127 = AtomicU64::new(0); let map_closure = |update: Update| match update { Update::Store { object_id, collection_id, low_key, data } => { let data_len = data.len(); let slab_id = slab_for_size(data_len); let slab = &slabs[usize::from(slab_id)]; let new_location = table.allocate_slab_slot(slab_id); let new_location_nzu: NonZeroU64 = new_location.into(); let complete_durability_pipeline = maybe!(slab.write(new_location.slot(), data)); if let Err(e) = complete_durability_pipeline { // can immediately free slot as the table.free_slab_slot(new_location); return Err(e); } // record stats heap_bytes_written .fetch_add(data_len as u64, Ordering::Release); if slab_id < 64 { let slab_bit = 0b1 << slab_id; heap_files_used_0_to_63 .fetch_or(slab_bit, Ordering::Release); } else { assert!(slab_id < 128); let slab_bit = 0b1 << (slab_id - 64); heap_files_used_64_to_127 .fetch_or(slab_bit, Ordering::Release); } Ok(UpdateMetadata::Store { object_id, collection_id, low_key, location: new_location_nzu, }) } Update::Free { object_id, collection_id } => { Ok(UpdateMetadata::Free { object_id, collection_id }) } }; let before_heap_write = Instant::now(); let metadata_batch_res: io::Result> = batch.into_par_iter().map(map_closure).collect(); let before_heap_sync = Instant::now(); fence(Ordering::SeqCst); for slab_id in 0..N_SLABS { let dirty = if slab_id < 64 { let slab_bit = 0b1 << slab_id; heap_files_used_0_to_63.load(Ordering::Acquire) & slab_bit == slab_bit } else { let slab_bit = 0b1 << (slab_id - 64); heap_files_used_64_to_127.load(Ordering::Acquire) & slab_bit == slab_bit }; if dirty { self.slabs[slab_id].sync()?; } } let heap_sync_latency = before_heap_sync.elapsed(); let heap_write_latency = before_heap_write.elapsed(); let metadata_batch = match metadata_batch_res { Ok(mut mb) => { // TODO evaluate impact : cost ratio of this sort mb.par_sort_unstable(); mb } Err(e) => { self.set_error(&e); return Err(e); } }; // make metadata durable let before_metadata_write = Instant::now(); let metadata_bytes_written = match metadata_store.write_batch(&metadata_batch) { Ok(metadata_bytes_written) => metadata_bytes_written, Err(e) => { self.set_error(&e); return Err(e); } }; let metadata_write_latency = before_metadata_write.elapsed(); // reclaim previous disk locations for future writes for update_metadata in metadata_batch { let last_address_opt = match update_metadata { UpdateMetadata::Store { object_id, location, .. } => { self.table.insert(object_id, SlabAddress::from(location)) } UpdateMetadata::Free { object_id, .. } => { guard.defer_drop(DeferredFree { allocator: self.table.clone_object_id_allocator_arc(), freed_slot: object_id.0.get(), }); self.table.remove(object_id) } }; if let Some(last_address) = last_address_opt { guard.defer_drop(DeferredFree { allocator: self .table .clone_slab_allocator_arc(last_address.slab_id), freed_slot: last_address.slot(), }); } } // truncate files that are now too fragmented let before_truncate = Instant::now(); let mut truncated_files = 0; let mut truncated_bytes = 0; for (i, max_live_slot) in self.table.get_max_allocated_per_slab() { let slab = &self.slabs[i]; let last_max = slab .max_live_slot_since_last_truncation .fetch_max(max_live_slot, Ordering::SeqCst); let max_since_last_truncation = last_max.max(max_live_slot); let currently_occupied_bytes = (max_live_slot + 1) * slab.slot_size as u64; let max_occupied_bytes = (max_since_last_truncation + 1) * slab.slot_size as u64; let ratio = currently_occupied_bytes * 100 / max_occupied_bytes; if ratio < FILE_TARGET_FILL_RATIO { let target_len = if max_live_slot < 16 { currently_occupied_bytes } else { currently_occupied_bytes * FILE_RESIZE_MARGIN / 100 }; assert!(target_len < max_occupied_bytes); assert!( target_len >= currently_occupied_bytes, "target_len of {} is above actual occupied len of {}", target_len, currently_occupied_bytes ); if cfg!(not(feature = "monotonic-behavior")) { if slab.file.set_len(target_len).is_ok() { slab.max_live_slot_since_last_truncation .store(max_live_slot, Ordering::SeqCst); let file_truncated_bytes = currently_occupied_bytes.saturating_sub(target_len); self.truncated_file_bytes .fetch_add(file_truncated_bytes, Ordering::Release); truncated_files += 1; truncated_bytes += file_truncated_bytes; } else { // TODO surface stats } } } } let truncate_latency = before_truncate.elapsed(); let heap_files_written_to = u64::from( heap_files_used_0_to_63.load(Ordering::Acquire).count_ones() + heap_files_used_64_to_127 .load(Ordering::Acquire) .count_ones(), ); let stats = WriteBatchStats { heap_bytes_written: heap_bytes_written.load(Ordering::Acquire), heap_files_written_to, heap_write_latency, heap_sync_latency, metadata_bytes_written, metadata_write_latency, truncated_files, truncated_bytes, truncate_latency, }; { let mut stats_tracker = self.stats.write(); stats_tracker.max = stats_tracker.max.max(&stats); stats_tracker.sum = stats_tracker.sum.sum(&stats); } Ok(stats) } pub fn heap_object_id_pin(&self) -> ebr::Guard<'_, DeferredFree, 16, 16> { self.free_ebr.pin() } pub fn allocate_object_id(&self) -> ObjectId { self.table.allocate_object_id() } pub(crate) fn objects_to_defrag(&self) -> FnvHashSet { self.table.objects_to_defrag() } } ================================================ FILE: src/id_allocator.rs ================================================ use std::collections::BTreeSet; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use crossbeam_queue::SegQueue; use fnv::FnvHashSet; use parking_lot::Mutex; #[derive(Default, Debug)] struct FreeSetAndTip { free_set: BTreeSet, next_to_allocate: u64, } #[derive(Default, Debug)] pub struct Allocator { free_and_pending: Mutex, /// Flat combining. /// /// A lock free queue of recently freed ids which uses when there is contention on `free_and_pending`. free_queue: SegQueue, allocation_counter: AtomicU64, free_counter: AtomicU64, } impl Allocator { /// Intended primarily for heap slab slot allocators when performing GC. /// /// If the slab is fragmented beyond the desired fill ratio, this returns /// the range of offsets (min inclusive, max exclusive) that may be copied /// into earlier free slots if they are currently occupied in order to /// achieve the desired fragmentation ratio. pub fn fragmentation_cutoff( &self, desired_ratio: f32, ) -> Option<(u64, u64)> { let mut free_and_tip = self.free_and_pending.lock(); let next_to_allocate = free_and_tip.next_to_allocate; if next_to_allocate == 0 { return None; } while let Some(free_id) = self.free_queue.pop() { free_and_tip.free_set.insert(free_id); } let live_objects = next_to_allocate - free_and_tip.free_set.len() as u64; let actual_ratio = live_objects as f32 / next_to_allocate as f32; log::trace!( "fragmented_slots actual ratio: {actual_ratio}, free len: {}", free_and_tip.free_set.len() ); if desired_ratio <= actual_ratio { return None; } // calculate theoretical cut-off point, return everything past that let min = (live_objects as f32 / desired_ratio) as u64; let max = next_to_allocate; assert!(min < max); Some((min, max)) } pub fn from_allocated(allocated: &FnvHashSet) -> Allocator { let mut heap = BTreeSet::::default(); let max = allocated.iter().copied().max(); for i in 0..max.unwrap_or(0) { if !allocated.contains(&i) { heap.insert(i); } } let free_and_pending = Mutex::new(FreeSetAndTip { free_set: heap, next_to_allocate: max.map(|m| m + 1).unwrap_or(0), }); Allocator { free_and_pending, free_queue: SegQueue::default(), allocation_counter: 0.into(), free_counter: 0.into(), } } pub fn max_allocated(&self) -> Option { let next = self.free_and_pending.lock().next_to_allocate; if next == 0 { None } else { Some(next - 1) } } pub fn allocate(&self) -> u64 { self.allocation_counter.fetch_add(1, Ordering::Relaxed); let mut free_and_tip = self.free_and_pending.lock(); while let Some(free_id) = self.free_queue.pop() { free_and_tip.free_set.insert(free_id); } compact(&mut free_and_tip); let pop_attempt = free_and_tip.free_set.pop_first(); if let Some(id) = pop_attempt { id } else { let ret = free_and_tip.next_to_allocate; free_and_tip.next_to_allocate += 1; ret } } pub fn free(&self, id: u64) { if cfg!(not(feature = "monotonic-behavior")) { self.free_counter.fetch_add(1, Ordering::Relaxed); if let Some(mut free) = self.free_and_pending.try_lock() { while let Some(free_id) = self.free_queue.pop() { free.free_set.insert(free_id); } free.free_set.insert(id); compact(&mut free); } else { self.free_queue.push(id); } } } /// Returns the counters for allocated, free pub fn counters(&self) -> (u64, u64) { ( self.allocation_counter.load(Ordering::Acquire), self.free_counter.load(Ordering::Acquire), ) } } fn compact(free: &mut FreeSetAndTip) { let next = &mut free.next_to_allocate; while *next > 1 && free.free_set.contains(&(*next - 1)) { free.free_set.remove(&(*next - 1)); *next -= 1; } } pub struct DeferredFree { pub allocator: Arc, pub freed_slot: u64, } impl Drop for DeferredFree { fn drop(&mut self) { self.allocator.free(self.freed_slot) } } ================================================ FILE: src/leaf.rs ================================================ use crate::*; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub(crate) struct Leaf { pub lo: InlineArray, pub hi: Option, pub prefix_length: usize, data: stack_map::StackMap, pub in_memory_size: usize, pub mutation_count: u64, #[serde(skip)] pub dirty_flush_epoch: Option, #[serde(skip)] pub page_out_on_flush: Option, #[serde(skip)] pub deleted: Option, #[serde(skip)] pub max_unflushed_epoch: Option, } impl Leaf { pub(crate) fn empty() -> Leaf { Leaf { lo: InlineArray::default(), hi: None, prefix_length: 0, data: stack_map::StackMap::default(), // this does not need to be marked as dirty until it actually // receives inserted data dirty_flush_epoch: None, in_memory_size: std::mem::size_of::>(), mutation_count: 0, page_out_on_flush: None, deleted: None, max_unflushed_epoch: None, } } pub(crate) const fn is_empty(&self) -> bool { self.data.is_empty() } pub(crate) fn set_dirty_epoch(&mut self, epoch: FlushEpoch) { assert!(self.deleted.is_none()); if let Some(current_epoch) = self.dirty_flush_epoch { assert!(current_epoch <= epoch); } if self.page_out_on_flush < Some(epoch) { self.page_out_on_flush = None; } self.dirty_flush_epoch = Some(epoch); } fn prefix(&self) -> &[u8] { assert!(self.deleted.is_none()); &self.lo[..self.prefix_length] } pub(crate) fn get(&self, key: &[u8]) -> Option<&InlineArray> { assert!(self.deleted.is_none()); assert!(key.starts_with(self.prefix())); let prefixed_key = &key[self.prefix_length..]; self.data.get(prefixed_key) } pub(crate) fn insert( &mut self, key: InlineArray, value: InlineArray, ) -> Option { assert!(self.deleted.is_none()); assert!(key.starts_with(self.prefix())); let prefixed_key = key[self.prefix_length..].into(); self.data.insert(prefixed_key, value) } pub(crate) fn remove(&mut self, key: &[u8]) -> Option { assert!(self.deleted.is_none()); let prefix = self.prefix(); assert!(key.starts_with(prefix)); let partial_key = &key[self.prefix_length..]; self.data.remove(partial_key) } pub(crate) fn merge_from(&mut self, other: &mut Self) { assert!(self.is_empty()); self.hi = other.hi.clone(); let new_prefix_len = if let Some(hi) = &self.hi { self.lo.iter().zip(hi.iter()).take_while(|(l, r)| l == r).count() } else { 0 }; assert_eq!(self.lo[..new_prefix_len], other.lo[..new_prefix_len]); // self.prefix_length is not read because it's expected to be // initialized here. self.prefix_length = new_prefix_len; if self.prefix() == other.prefix() { self.data = std::mem::take(&mut other.data); return; } assert!( self.prefix_length < other.prefix_length, "self: {:?} other: {:?}", self, other ); let unshifted_key_amount = other.prefix_length - self.prefix_length; let unshifted_prefix = &other.lo [other.prefix_length - unshifted_key_amount..other.prefix_length]; for (k, v) in other.data.iter() { let mut unshifted_key = Vec::with_capacity(unshifted_prefix.len() + k.len()); unshifted_key.extend_from_slice(unshifted_prefix); unshifted_key.extend_from_slice(k); self.data.insert(unshifted_key.into(), v.clone()); } assert_eq!(other.data.len(), self.data.len()); #[cfg(feature = "for-internal-testing-only")] assert_eq!( self.iter().collect::>(), other.iter().collect::>(), "self: {:#?} \n other: {:#?}\n", self, other ); } pub(crate) fn iter( &self, ) -> impl Iterator { let prefix = self.prefix(); self.data.iter().map(|(k, v)| { let mut unshifted_key = Vec::with_capacity(prefix.len() + k.len()); unshifted_key.extend_from_slice(prefix); unshifted_key.extend_from_slice(k); (unshifted_key.into(), v.clone()) }) } pub(crate) fn serialize(&self, zstd_compression_level: i32) -> Vec { let mut ret = vec![]; let mut zstd_enc = zstd::stream::Encoder::new(&mut ret, zstd_compression_level) .unwrap(); bincode::serialize_into(&mut zstd_enc, self).unwrap(); zstd_enc.finish().unwrap(); ret } pub(crate) fn deserialize( buf: &[u8], ) -> std::io::Result>> { let zstd_decoded = zstd::stream::decode_all(buf).unwrap(); let mut leaf: Box> = bincode::deserialize(&zstd_decoded).unwrap(); // use decompressed buffer length as a cheap proxy for in-memory size for now leaf.in_memory_size = zstd_decoded.len(); Ok(leaf) } fn set_in_memory_size(&mut self) { self.in_memory_size = std::mem::size_of::>() + self.hi.as_ref().map(|h| h.len()).unwrap_or(0) + self.lo.len() + self.data.iter().map(|(k, v)| k.len() + v.len()).sum::(); } pub(crate) fn split_if_full( &mut self, new_epoch: FlushEpoch, allocator: &ObjectCache, collection_id: CollectionId, ) -> Option<(InlineArray, Object)> { if self.data.is_full() { let original_len = self.data.len(); let old_prefix_len = self.prefix_length; // split let split_offset = if self.lo.is_empty() { // split left-most shard almost at the beginning for // optimizing downward-growing workloads 1 } else if self.hi.is_none() { // split right-most shard almost at the end for // optimizing upward-growing workloads self.data.len() - 2 } else { self.data.len() / 2 }; let data = self.data.split_off(split_offset); let left_max = &self.data.last().unwrap().0; let right_min = &data.first().unwrap().0; // suffix truncation attempts to shrink the split key // so that shorter keys bubble up into the index let splitpoint_length = right_min .iter() .zip(left_max.iter()) .take_while(|(a, b)| a == b) .count() + 1; let mut split_vec = Vec::with_capacity(self.prefix_length + splitpoint_length); split_vec.extend_from_slice(self.prefix()); split_vec.extend_from_slice(&right_min[..splitpoint_length]); let split_key = InlineArray::from(split_vec); let rhs_id = allocator.allocate_object_id(new_epoch); log::trace!( "split leaf {:?} at split key: {:?} into new {:?} at {:?}", self.lo, split_key, rhs_id, new_epoch, ); let mut rhs = Leaf { dirty_flush_epoch: Some(new_epoch), hi: self.hi.clone(), lo: split_key.clone(), prefix_length: 0, in_memory_size: 0, data, mutation_count: 0, page_out_on_flush: None, deleted: None, max_unflushed_epoch: None, }; rhs.shorten_keys_after_split(old_prefix_len); rhs.set_in_memory_size(); self.hi = Some(split_key.clone()); self.shorten_keys_after_split(old_prefix_len); self.set_in_memory_size(); assert_eq!(self.hi.as_ref().unwrap(), &split_key); assert_eq!(rhs.lo, &split_key); assert_eq!(rhs.data.len() + self.data.len(), original_len); let rhs_node = Object { object_id: rhs_id, collection_id, low_key: split_key.clone(), inner: Arc::new(RwLock::new(CacheBox { leaf: Some(Box::new(rhs)), logged_index: BTreeMap::default(), })), }; return Some((split_key, rhs_node)); } None } pub(crate) fn shorten_keys_after_split(&mut self, old_prefix_len: usize) { let Some(hi) = self.hi.as_ref() else { return }; let new_prefix_len = self.lo.iter().zip(hi.iter()).take_while(|(l, r)| l == r).count(); assert_eq!(self.lo[..new_prefix_len], hi[..new_prefix_len]); // self.prefix_length is not read because it's expected to be // initialized here. self.prefix_length = new_prefix_len; if new_prefix_len == old_prefix_len { return; } assert!( new_prefix_len > old_prefix_len, "expected new prefix length of {} to be greater than the pre-split prefix length of {} for node {:?}", new_prefix_len, old_prefix_len, self ); let key_shift = new_prefix_len - old_prefix_len; for (k, v) in std::mem::take(&mut self.data).iter() { self.data.insert(k[key_shift..].into(), v.clone()); } } } ================================================ FILE: src/lib.rs ================================================ // 1.0 blockers // // bugs // * page-out needs to be deferred until after any flush of the dirty epoch // * need to remove max_unflushed_epoch after flushing it // * can't send reliable page-out request backwards from 7->6 // * re-locking every mutex in a writebatch feels bad // * need to signal stability status forward // * maybe we already are // * can make dirty_flush_epoch atomic and CAS it to 0 after flush // * can change dirty_flush_epoch to unflushed_epoch // * can always set mutation_count to max dirty flush epoch // * this feels nice, we can lazily update a global stable flushed counter // * can get rid of dirty_flush_epoch and page_out_on_flush? // * or at least dirty_flush_epoch // * dirty_flush_epoch really means "hasn't yet been cooperatively serialized @ F.E." // * interesting metrics: // * whether dirty for some epoch // * whether cooperatively serialized for some epoch // * whether fully flushed for some epoch // * clean -> dirty -> {maybe coop} -> flushed // * for page-out, we only care if it's stable or if we need to add it to // a page-out priority queue // * page-out doesn't seem to happen as expected // // reliability // TODO make all writes wrapped in a Tearable wrapper that splits writes // and can possibly crash based on a counter. // TODO test concurrent drop_tree when other threads are still using it // TODO list trees test for recovering empty collections // TODO set explicit max key and value sizes w/ corresponding heap // TODO add failpoints to writepath // // performance // TODO handle prefix encoding // TODO (minor) remove cache access for removed node in merge function // TODO index+log hybrid - tinylsm key -> object location // // features // TODO multi-collection batch // // misc // TODO skim inlining output of RUSTFLAGS="-Cremark=all -Cdebuginfo=1" // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1.0 cutoff ~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // post-1.0 improvements // // reliability // TODO bug hiding: if the crash_iter test panics, the test doesn't fail as expected // TODO event log assertion for testing heap location bidirectional referential integrity, // particularly in the object location mapper. // TODO ensure nothing "from the future" gets copied into earlier epochs during GC // TODO collection_id on page_in checks - it needs to be pinned w/ heap's EBR? // TODO put aborts behind feature flags for hard crashes // TODO re-enable transaction tests in test_tree.rs // // performance // TODO force writers to flush when some number of dirty epochs have built up // TODO serialize flush batch in parallel // TODO concurrent serialization of NotYetSerialized dirty objects // TODO make the Arc`, //! but with several additional capabilities for //! assisting creators of stateful systems. //! //! It is fully thread-safe, and all operations are //! atomic. Multiple `Tree`s with isolated keyspaces //! are supported with the //! [`Db::open_tree`](struct.Db.html#method.open_tree) method. //! //! `sled` is built by experienced database engineers //! who think users should spend less time tuning and //! working against high-friction APIs. Expect //! significant ergonomic and performance improvements //! over time. Most surprises are bugs, so please //! [let us know](mailto:tylerneely@gmail.com?subject=sled%20sucks!!!) //! if something is high friction. //! //! # Examples //! //! ``` //! # let _ = std::fs::remove_dir_all("my_db"); //! let db: sled::Db = sled::open("my_db").unwrap(); //! //! // insert and get //! db.insert(b"yo!", b"v1"); //! assert_eq!(&db.get(b"yo!").unwrap().unwrap(), b"v1"); //! //! // Atomic compare-and-swap. //! db.compare_and_swap( //! b"yo!", // key //! Some(b"v1"), // old value, None for not present //! Some(b"v2"), // new value, None for delete //! ) //! .unwrap(); //! //! // Iterates over key-value pairs, starting at the given key. //! let scan_key: &[u8] = b"a non-present key before yo!"; //! let mut iter = db.range(scan_key..); //! assert_eq!(&iter.next().unwrap().unwrap().0, b"yo!"); //! assert!(iter.next().is_none()); //! //! db.remove(b"yo!"); //! assert!(db.get(b"yo!").unwrap().is_none()); //! //! let other_tree: sled::Tree = db.open_tree(b"cool db facts").unwrap(); //! other_tree.insert( //! b"k1", //! &b"a Db acts like a Tree due to implementing Deref"[..] //! ).unwrap(); //! # let _ = std::fs::remove_dir_all("my_db"); //! ``` #[cfg(feature = "for-internal-testing-only")] mod block_checker; mod config; mod db; mod flush_epoch; mod heap; mod id_allocator; mod leaf; mod metadata_store; mod object_cache; mod object_location_mapper; mod tree; #[cfg(any( feature = "testing-shred-allocator", feature = "testing-count-allocator" ))] pub mod alloc; #[cfg(feature = "for-internal-testing-only")] mod event_verifier; #[inline] fn debug_delay() { #[cfg(debug_assertions)] { let rand = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_nanos(); if rand % 128 > 100 { for _ in 0..rand % 16 { std::thread::yield_now(); } } } } pub use crate::config::Config; pub use crate::db::Db; pub use crate::tree::{Batch, Iter, Tree}; pub use inline_array::InlineArray; const NAME_MAPPING_COLLECTION_ID: CollectionId = CollectionId(0); const DEFAULT_COLLECTION_ID: CollectionId = CollectionId(1); const INDEX_FANOUT: usize = 64; const EBR_LOCAL_GC_BUFFER_SIZE: usize = 128; use std::collections::BTreeMap; use std::num::NonZeroU64; use std::ops::Bound; use std::sync::Arc; use parking_lot::RwLock; use crate::flush_epoch::{ FlushEpoch, FlushEpochGuard, FlushEpochTracker, FlushInvariants, }; use crate::heap::{ HeapStats, ObjectRecovery, SlabAddress, Update, WriteBatchStats, }; use crate::id_allocator::{Allocator, DeferredFree}; use crate::leaf::Leaf; // These are public so that they can be easily crash tested in external // binaries. They are hidden because there are zero guarantees around their // API stability or functionality. #[doc(hidden)] pub use crate::heap::{Heap, HeapRecovery}; #[doc(hidden)] pub use crate::metadata_store::MetadataStore; #[doc(hidden)] pub use crate::object_cache::{CacheStats, Dirty, FlushStats, ObjectCache}; /// Opens a `Db` with a default configuration at the /// specified path. This will create a new storage /// directory at the specified path if it does /// not already exist. You can use the `Db::was_recovered` /// method to determine if your database was recovered /// from a previous instance. pub fn open>(path: P) -> std::io::Result { Config::new().path(path).open() } #[derive(Debug, Copy, Clone)] pub struct Stats { pub cache: CacheStats, } /// Compare and swap result. /// /// It returns `Ok(Ok(()))` if operation finishes successfully and /// - `Ok(Err(CompareAndSwapError(current, proposed)))` if operation failed /// to setup a new value. `CompareAndSwapError` contains current and /// proposed values. /// - `Err(Error::Unsupported)` if the database is opened in read-only mode. /// otherwise. pub type CompareAndSwapResult = std::io::Result< std::result::Result, >; type Index = concurrent_map::ConcurrentMap< InlineArray, Object, INDEX_FANOUT, EBR_LOCAL_GC_BUFFER_SIZE, >; /// Compare and swap error. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct CompareAndSwapError { /// The current value which caused your CAS to fail. pub current: Option, /// Returned value that was proposed unsuccessfully. pub proposed: Option, } /// Compare and swap success. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct CompareAndSwapSuccess { /// The current value which was successfully installed. pub new_value: Option, /// Returned value that was previously stored. pub previous_value: Option, } impl std::fmt::Display for CompareAndSwapError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "Compare and swap conflict") } } impl std::error::Error for CompareAndSwapError {} #[derive( Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialOrd, Ord, PartialEq, Eq, Hash, )] pub struct ObjectId(NonZeroU64); impl ObjectId { fn new(from: u64) -> Option { NonZeroU64::new(from).map(ObjectId) } } impl std::ops::Deref for ObjectId { type Target = u64; fn deref(&self) -> &u64 { let self_ref: &NonZeroU64 = &self.0; // NonZeroU64 is repr(transparent) where it wraps a u64 // so it is guaranteed to match the binary layout. This // makes it safe to cast a reference to one as a reference // to the other like this. let self_ptr: *const NonZeroU64 = self_ref as *const _; let reference: *const u64 = self_ptr as *const u64; unsafe { &*reference } } } impl concurrent_map::Minimum for ObjectId { const MIN: ObjectId = ObjectId(NonZeroU64::MIN); } #[derive( Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialOrd, Ord, PartialEq, Eq, Hash, )] pub struct CollectionId(u64); impl concurrent_map::Minimum for CollectionId { const MIN: CollectionId = CollectionId(u64::MIN); } #[derive(Debug, Clone)] struct CacheBox { leaf: Option>>, #[allow(unused)] logged_index: BTreeMap, } #[allow(unused)] #[derive(Debug, Clone)] struct LogValue { location: SlabAddress, value: Option, } #[derive(Debug, Clone)] pub struct Object { object_id: ObjectId, collection_id: CollectionId, low_key: InlineArray, inner: Arc>>, } impl PartialEq for Object { fn eq(&self, other: &Self) -> bool { self.object_id == other.object_id } } /// Stored on `Db` and `Tree` in an Arc, so that when the /// last "high-level" struct is dropped, the flusher thread /// is cleaned up. struct ShutdownDropper { shutdown_sender: parking_lot::Mutex< std::sync::mpsc::Sender>, >, cache: parking_lot::Mutex>, } impl Drop for ShutdownDropper { fn drop(&mut self) { let (tx, rx) = std::sync::mpsc::channel(); log::debug!("sending shutdown signal to flusher"); if self.shutdown_sender.lock().send(tx).is_ok() { if let Err(e) = rx.recv() { log::error!("failed to shut down flusher thread: {:?}", e); } else { log::debug!("flush thread successfully terminated"); } } else { log::debug!( "failed to shut down flusher, manually flushing ObjectCache" ); let cache = self.cache.lock(); if let Err(e) = cache.flush() { log::error!( "Db flusher encountered error while flushing: {:?}", e ); cache.set_error(&e); } } } } fn map_bound U>(bound: Bound, f: F) -> Bound { match bound { Bound::Unbounded => Bound::Unbounded, Bound::Included(x) => Bound::Included(f(x)), Bound::Excluded(x) => Bound::Excluded(f(x)), } } const fn _assert_public_types_send_sync() { use std::fmt::Debug; const fn _assert_send() {} const fn _assert_send_sync() {} /* _assert_send::(); _assert_send_sync::(); _assert_send_sync::(); _assert_send_sync::(); */ _assert_send::(); _assert_send_sync::(); _assert_send_sync::(); _assert_send_sync::(); _assert_send_sync::(); _assert_send_sync::(); } ================================================ FILE: src/metadata_store.rs ================================================ use std::collections::BTreeSet; use std::fs; use std::io::{self, Read, Write}; use std::num::NonZeroU64; use std::path::{Path, PathBuf}; use std::sync::{ Arc, atomic::{AtomicPtr, AtomicU64, Ordering}, }; use crossbeam_channel::{Receiver, Sender, bounded, unbounded}; use fault_injection::{annotate, fallible, maybe}; use fnv::FnvHashMap; use inline_array::InlineArray; use parking_lot::Mutex; use rayon::prelude::*; use zstd::stream::read::Decoder as ZstdDecoder; use zstd::stream::write::Encoder as ZstdEncoder; use crate::{CollectionId, ObjectId, heap::UpdateMetadata}; const WARN: &str = "DO_NOT_PUT_YOUR_FILES_HERE"; const TMP_SUFFIX: &str = ".tmp"; const LOG_PREFIX: &str = "log"; const SNAPSHOT_PREFIX: &str = "snapshot"; const ZSTD_LEVEL: i32 = 3; // NB: intentionally does not implement Clone, and // the Inner::drop code relies on this invariant for // now so that we don't free the global error until // all high-level structs are dropped. This is not // hard to change over time though, just a current // invariant. pub struct MetadataStore { inner: Inner, is_shut_down: bool, } impl Drop for MetadataStore { fn drop(&mut self) { if self.is_shut_down { return; } self.shutdown_inner(); self.is_shut_down = true; } } struct MetadataRecovery { recovered: Vec, id_for_next_log: u64, snapshot_size: u64, } struct LogAndStats { file: fs::File, bytes_written: u64, log_sequence_number: u64, } enum WorkerMessage { Shutdown(Sender<()>), LogReadyToCompact { log_and_stats: LogAndStats }, } fn get_compactions( rx: &mut Receiver, ) -> Result, Option>> { let mut ret = vec![]; match rx.recv() { Ok(WorkerMessage::Shutdown(tx)) => { return Err(Some(tx)); } Ok(WorkerMessage::LogReadyToCompact { log_and_stats }) => { ret.push(log_and_stats.log_sequence_number); } Err(e) => { log::error!( "metadata store worker thread unable to receive message, unexpected shutdown: {e:?}" ); return Err(None); } } // scoop up any additional logs that have built up while we were busy compacting loop { match rx.try_recv() { Ok(WorkerMessage::Shutdown(tx)) => { tx.send(()).unwrap(); return Err(Some(tx)); } Ok(WorkerMessage::LogReadyToCompact { log_and_stats }) => { ret.push(log_and_stats.log_sequence_number); } Err(_timeout) => return Ok(ret), } } } fn worker( mut rx: Receiver, mut last_snapshot_lsn: u64, inner: Inner, ) { loop { if let Err(error) = check_error(&inner.global_error) { drop(inner); log::error!( "compaction thread terminating after global error set to {:?}", error ); return; } match get_compactions(&mut rx) { Ok(log_ids) => { assert_eq!(log_ids[0], last_snapshot_lsn + 1); let write_res = read_snapshot_and_apply_logs( &inner.storage_directory, log_ids.into_iter().collect(), Some(last_snapshot_lsn), &inner.directory_lock, ); match write_res { Err(e) => { set_error(&inner.global_error, &e); log::error!( "log compactor thread encountered error: {:?} - setting global fatal error and shutting down compactions", e ); return; } Ok(recovery) => { inner .snapshot_size .store(recovery.snapshot_size, Ordering::SeqCst); last_snapshot_lsn = recovery.id_for_next_log.checked_sub(1).unwrap(); } } } Err(Some(tx)) => { drop(inner); if let Err(e) = tx.send(()) { log::error!( "log compactor failed to send shutdown ack to system: {e:?}" ); } return; } Err(None) => { return; } } } } fn set_error( global_error: &AtomicPtr<(io::ErrorKind, String)>, error: &io::Error, ) { let kind = error.kind(); let reason = error.to_string(); let boxed = Box::new((kind, reason)); let ptr = Box::into_raw(boxed); if global_error .compare_exchange( std::ptr::null_mut(), ptr, Ordering::SeqCst, Ordering::SeqCst, ) .is_err() { // global fatal error already installed, drop this one unsafe { drop(Box::from_raw(ptr)); } } } fn check_error( global_error: &AtomicPtr<(io::ErrorKind, String)>, ) -> io::Result<()> { let err_ptr: *const (io::ErrorKind, String) = global_error.load(Ordering::Acquire); if err_ptr.is_null() { Ok(()) } else { let deref: &(io::ErrorKind, String) = unsafe { &*err_ptr }; Err(io::Error::new(deref.0, deref.1.clone())) } } #[derive(Clone)] struct Inner { global_error: Arc>, active_log: Arc>, snapshot_size: Arc, storage_directory: PathBuf, directory_lock: Arc, worker_outbox: Sender, } impl Drop for Inner { fn drop(&mut self) { // NB: this is the only place where the global error should be // reclaimed in the whole sled codebase, as this Inner is only held // by the background writer and the heap (in an Arc) so when this // drop happens, it's because the whole system is going down, not // because any particular Db instance that may have been cloned // by a thread is dropping. let error_ptr = self.global_error.swap(std::ptr::null_mut(), Ordering::Acquire); if !error_ptr.is_null() { unsafe { drop(Box::from_raw(error_ptr)); } } } } impl MetadataStore { pub fn get_global_error_arc( &self, ) -> Arc> { self.inner.global_error.clone() } fn shutdown_inner(&mut self) { let (tx, rx) = bounded(1); if self.inner.worker_outbox.send(WorkerMessage::Shutdown(tx)).is_ok() { let _ = rx.recv(); } self.set_error(&io::Error::other( "system has been shut down".to_string(), )); self.is_shut_down = true; } fn check_error(&self) -> io::Result<()> { check_error(&self.inner.global_error) } fn set_error(&self, error: &io::Error) { set_error(&self.inner.global_error, error); } /// Returns the writer handle `MetadataStore`, a sorted array of metadata, and a sorted array /// of free keys. pub fn recover>( storage_directory: P, ) -> io::Result<( // Metadata writer MetadataStore, // Metadata - node id, value, user data Vec, )> { use fs2::FileExt; // TODO NOCOMMIT let sync_status = std::process::Command::new("sync") .status() .map(|status| status.success()); if !matches!(sync_status, Ok(true)) { log::warn!( "sync command before recovery failed: {:?}", sync_status ); } let path = storage_directory.as_ref(); // initialize directories if not present if let Err(e) = fs::read_dir(path) { if e.kind() == io::ErrorKind::NotFound { fallible!(fs::create_dir_all(path)); } } let _ = fs::File::create(path.join(WARN)); let directory_lock = fallible!(fs::File::open(path)); fallible!(directory_lock.sync_all()); fallible!(directory_lock.try_lock_exclusive()); let recovery = MetadataStore::recover_inner(&storage_directory, &directory_lock)?; let new_log = LogAndStats { log_sequence_number: recovery.id_for_next_log, bytes_written: 0, file: fallible!(fs::File::create(log_path( path, recovery.id_for_next_log ))), }; let (tx, rx) = unbounded(); let inner = Inner { snapshot_size: Arc::new(recovery.snapshot_size.into()), storage_directory: path.into(), directory_lock: Arc::new(directory_lock), global_error: Default::default(), active_log: Arc::new(Mutex::new(new_log)), worker_outbox: tx, }; let worker_inner = inner.clone(); let spawn_res = std::thread::Builder::new() .name("sled_flusher".into()) .spawn(move || { worker( rx, recovery.id_for_next_log.checked_sub(1).unwrap(), worker_inner, ) }); if let Err(e) = spawn_res { return Err(io::Error::other(format!( "unable to spawn metadata compactor thread for sled database: {:?}", e ))); } Ok((MetadataStore { inner, is_shut_down: false }, recovery.recovered)) } /// Returns the recovered mappings, the id for the next log file, the highest allocated object id, and the set of free ids fn recover_inner>( storage_directory: P, directory_lock: &fs::File, ) -> io::Result { let path = storage_directory.as_ref(); log::debug!("opening MetadataStore at {:?}", path); let (log_ids, snapshot_id_opt) = enumerate_logs_and_snapshot(path)?; read_snapshot_and_apply_logs( path, log_ids, snapshot_id_opt, directory_lock, ) } /// Write a batch of metadata. `None` for the second half of the outer tuple represents a /// deletion. Returns the bytes written. pub fn write_batch(&self, batch: &[UpdateMetadata]) -> io::Result { self.check_error()?; let batch_bytes = serialize_batch(batch); let ret = batch_bytes.len() as u64; let mut log = self.inner.active_log.lock(); if let Err(e) = maybe!(log.file.write_all(&batch_bytes)) { self.set_error(&e); return Err(e); } if let Err(e) = maybe!(log.file.sync_all()) .and_then(|_| self.inner.directory_lock.sync_all()) { self.set_error(&e); return Err(e); } log.bytes_written += batch_bytes.len() as u64; if log.bytes_written > self.inner.snapshot_size.load(Ordering::Acquire).max(64 * 1024) { let next_offset = log.log_sequence_number + 1; let next_path = log_path(&self.inner.storage_directory, next_offset); // open new log let mut next_log_file_opts = fs::OpenOptions::new(); next_log_file_opts.create(true).read(true).write(true); let next_log_file = match maybe!(next_log_file_opts.open(next_path)) { Ok(nlf) => nlf, Err(e) => { self.set_error(&e); return Err(e); } }; let next_log_and_stats = LogAndStats { file: next_log_file, log_sequence_number: next_offset, bytes_written: 0, }; // replace log let old_log_and_stats = std::mem::replace(&mut *log, next_log_and_stats); // send to snapshot writer self.inner .worker_outbox .send(WorkerMessage::LogReadyToCompact { log_and_stats: old_log_and_stats, }) .expect("unable to send log to compact to worker"); } Ok(ret) } } fn serialize_batch(batch: &[UpdateMetadata]) -> Vec { // we initialize the vector to contain placeholder bytes for the frame length let batch_bytes = 0_u64.to_le_bytes().to_vec(); // write format: // 6 byte LE frame length (in bytes, not items) // 2 byte crc of the frame length // payload: // zstd encoded 8 byte LE key // zstd encoded 8 byte LE value // repeated for each kv pair // LE encoded crc32 of length + payload raw bytes, XOR 0xAF to make non-zero in empty case let mut batch_encoder = ZstdEncoder::new(batch_bytes, ZSTD_LEVEL).unwrap(); for update_metadata in batch { match update_metadata { UpdateMetadata::Store { object_id, collection_id, low_key, location, } => { batch_encoder .write_all(&object_id.0.get().to_le_bytes()) .unwrap(); batch_encoder .write_all(&collection_id.0.to_le_bytes()) .unwrap(); batch_encoder.write_all(&location.get().to_le_bytes()).unwrap(); let low_key_len: u64 = low_key.len() as u64; batch_encoder.write_all(&low_key_len.to_le_bytes()).unwrap(); batch_encoder.write_all(low_key).unwrap(); } UpdateMetadata::Free { object_id, collection_id } => { batch_encoder .write_all(&object_id.0.get().to_le_bytes()) .unwrap(); batch_encoder .write_all(&collection_id.0.to_le_bytes()) .unwrap(); // heap location batch_encoder.write_all(&0_u64.to_le_bytes()).unwrap(); // metadata len batch_encoder.write_all(&0_u64.to_le_bytes()).unwrap(); } } } let mut batch_bytes = batch_encoder.finish().unwrap(); let batch_len = batch_bytes.len().checked_sub(8).unwrap(); batch_bytes[..8].copy_from_slice(&batch_len.to_le_bytes()); assert_eq!(&[0, 0], &batch_bytes[6..8]); let len_hash: [u8; 2] = (crc32fast::hash(&batch_bytes[..6]) as u16).to_le_bytes(); batch_bytes[6..8].copy_from_slice(&len_hash); let hash: u32 = crc32fast::hash(&batch_bytes) ^ 0xAF; let hash_bytes: [u8; 4] = hash.to_le_bytes(); batch_bytes.extend_from_slice(&hash_bytes); batch_bytes } fn read_frame( file: &mut fs::File, reusable_frame_buffer: &mut Vec, ) -> io::Result> { let mut frame_size_with_crc_buf: [u8; 8] = [0; 8]; // TODO only break if UnexpectedEof, otherwise propagate fallible!(file.read_exact(&mut frame_size_with_crc_buf)); let expected_len_hash_buf = [frame_size_with_crc_buf[6], frame_size_with_crc_buf[7]]; let actual_len_hash_buf: [u8; 2] = (crc32fast::hash(&frame_size_with_crc_buf[..6]) as u16).to_le_bytes(); // clear crc bytes before turning into usize let mut frame_size_buf = frame_size_with_crc_buf; frame_size_buf[6] = 0; frame_size_buf[7] = 0; if actual_len_hash_buf != expected_len_hash_buf { return Err(annotate!(io::Error::new( io::ErrorKind::InvalidData, "corrupt frame length" ))); } let len_u64: u64 = u64::from_le_bytes(frame_size_buf); let len: usize = usize::try_from(len_u64).unwrap(); reusable_frame_buffer.clear(); reusable_frame_buffer.reserve(len + 12); unsafe { reusable_frame_buffer.set_len(len + 12); } reusable_frame_buffer[..8].copy_from_slice(&frame_size_with_crc_buf); fallible!(file.read_exact(&mut reusable_frame_buffer[8..])); let crc_actual = crc32fast::hash(&reusable_frame_buffer[..len + 8]) ^ 0xAF; let crc_recorded = u32::from_le_bytes([ reusable_frame_buffer[len + 8], reusable_frame_buffer[len + 9], reusable_frame_buffer[len + 10], reusable_frame_buffer[len + 11], ]); if crc_actual != crc_recorded { log::warn!("encountered incorrect crc for batch in log"); return Err(annotate!(io::Error::new( io::ErrorKind::InvalidData, "crc mismatch for read of batch frame", ))); } let mut ret = vec![]; let mut decoder = ZstdDecoder::new(&reusable_frame_buffer[8..len + 8]) .expect("failed to create zstd decoder"); let mut object_id_buf: [u8; 8] = [0; 8]; let mut collection_id_buf: [u8; 8] = [0; 8]; let mut location_buf: [u8; 8] = [0; 8]; let mut low_key_len_buf: [u8; 8] = [0; 8]; let mut low_key_buf = vec![]; loop { let first_read_res = decoder .read_exact(&mut object_id_buf) .and_then(|_| decoder.read_exact(&mut collection_id_buf)) .and_then(|_| decoder.read_exact(&mut location_buf)) .and_then(|_| decoder.read_exact(&mut low_key_len_buf)); if let Err(e) = first_read_res { if e.kind() != io::ErrorKind::UnexpectedEof { return Err(e); } else { break; } } let object_id_u64 = u64::from_le_bytes(object_id_buf); let object_id = if let Some(object_id) = ObjectId::new(object_id_u64) { object_id } else { return Err(annotate!(io::Error::new( io::ErrorKind::InvalidData, "corrupt object ID 0 somehow passed crc check" ))); }; let collection_id = CollectionId(u64::from_le_bytes(collection_id_buf)); let location = u64::from_le_bytes(location_buf); let low_key_len_raw = u64::from_le_bytes(low_key_len_buf); let low_key_len = usize::try_from(low_key_len_raw).unwrap(); low_key_buf.reserve(low_key_len); unsafe { low_key_buf.set_len(low_key_len); } decoder .read_exact(&mut low_key_buf) .expect("we expect reads from crc-verified buffers to succeed"); if let Some(location_nzu) = NonZeroU64::new(location) { let low_key = InlineArray::from(&*low_key_buf); ret.push(UpdateMetadata::Store { object_id, collection_id, location: location_nzu, low_key, }); } else { ret.push(UpdateMetadata::Free { object_id, collection_id }); } } Ok(ret) } // returns the deduplicated data in this log, along with an optional offset where a // final torn write occurred. fn read_log( directory_path: &Path, lsn: u64, ) -> io::Result> { log::trace!("reading log {lsn}"); let mut ret = FnvHashMap::default(); let mut file = fallible!(fs::File::open(log_path(directory_path, lsn))); let mut reusable_frame_buffer: Vec = vec![]; while let Ok(frame) = read_frame(&mut file, &mut reusable_frame_buffer) { for update_metadata in frame { ret.insert(update_metadata.object_id(), update_metadata); } } log::trace!("recovered {} items in log {}", ret.len(), lsn); Ok(ret) } /// returns the data from the snapshot as well as the size of the snapshot fn read_snapshot( directory_path: &Path, lsn: u64, ) -> io::Result<(FnvHashMap, u64)> { log::trace!("reading snapshot {lsn}"); let mut reusable_frame_buffer: Vec = vec![]; let mut file = fallible!(fs::File::open(snapshot_path(directory_path, lsn, false))); let size = fallible!(file.metadata()).len(); let raw_frame = read_frame(&mut file, &mut reusable_frame_buffer)?; let frame: FnvHashMap = raw_frame .into_iter() .map(|update_metadata| (update_metadata.object_id(), update_metadata)) .collect(); log::trace!("recovered {} items in snapshot {}", frame.len(), lsn); Ok((frame, size)) } fn log_path(directory_path: &Path, id: u64) -> PathBuf { directory_path.join(format!("{LOG_PREFIX}_{:016x}", id)) } fn snapshot_path(directory_path: &Path, id: u64, temporary: bool) -> PathBuf { if temporary { directory_path .join(format!("{SNAPSHOT_PREFIX}_{:016x}{TMP_SUFFIX}", id)) } else { directory_path.join(format!("{SNAPSHOT_PREFIX}_{:016x}", id)) } } fn enumerate_logs_and_snapshot( directory_path: &Path, ) -> io::Result<(BTreeSet, Option)> { let mut logs = BTreeSet::new(); let mut snapshot: Option = None; for dir_entry_res in fallible!(fs::read_dir(directory_path)) { let dir_entry = fallible!(dir_entry_res); let file_name = if let Ok(f) = dir_entry.file_name().into_string() { f } else { log::warn!( "skipping unexpected file with non-unicode name {:?}", dir_entry.file_name() ); continue; }; if file_name.ends_with(TMP_SUFFIX) { log::warn!("removing incomplete snapshot rewrite {file_name:?}"); fallible!(fs::remove_file(directory_path.join(file_name))); } else if file_name.starts_with(LOG_PREFIX) { let start = LOG_PREFIX.len() + 1; let stop = start + 16; if let Ok(id) = u64::from_str_radix(&file_name[start..stop], 16) { logs.insert(id); } else { todo!() } } else if file_name.starts_with(SNAPSHOT_PREFIX) { let start = SNAPSHOT_PREFIX.len() + 1; let stop = start + 16; if let Ok(id) = u64::from_str_radix(&file_name[start..stop], 16) { if let Some(snap_id) = snapshot { if snap_id < id { log::warn!( "removing stale snapshot {id} that is superceded by snapshot {id}" ); if let Err(e) = fs::remove_file(&file_name) { log::warn!( "failed to remove stale snapshot file {:?}: {:?}", file_name, e ); } snapshot = Some(id); } } else { snapshot = Some(id); } } else { todo!() } } } let snap_id = snapshot.unwrap_or(0); for stale_log_id in logs.range(..=snap_id) { let file_name = log_path(directory_path, *stale_log_id); log::warn!( "removing stale log {file_name:?} that is contained within snapshot {snap_id}" ); fallible!(fs::remove_file(file_name)); } logs.retain(|l| *l > snap_id); Ok((logs, snapshot)) } fn read_snapshot_and_apply_logs( path: &Path, log_ids: BTreeSet, snapshot_id_opt: Option, locked_directory: &fs::File, ) -> io::Result { let (snapshot_tx, snapshot_rx) = bounded(1); if let Some(snapshot_id) = snapshot_id_opt { let path: PathBuf = path.into(); rayon::spawn(move || { let snap_res = read_snapshot(&path, snapshot_id) .map(|(snapshot, _snapshot_len)| snapshot); snapshot_tx.send(snap_res).unwrap(); }); } else { snapshot_tx.send(Ok(Default::default())).unwrap(); } let mut max_log_id = snapshot_id_opt.unwrap_or(0); let log_data_res: io::Result< Vec<(u64, FnvHashMap)>, > = (&log_ids) //.iter().collect::>()) .into_par_iter() .map(move |log_id| { if let Some(snapshot_id) = snapshot_id_opt { assert!(*log_id > snapshot_id); } let log_data = read_log(path, *log_id)?; Ok((*log_id, log_data)) }) .collect(); let mut recovered: FnvHashMap = snapshot_rx.recv().unwrap()?; log::trace!("recovered snapshot contains {recovered:?}"); for (log_id, log_datum) in log_data_res? { max_log_id = max_log_id.max(log_id); for (object_id, update_metadata) in log_datum { if matches!(update_metadata, UpdateMetadata::Store { .. }) { recovered.insert(object_id, update_metadata); } else { let previous = recovered.remove(&object_id); if previous.is_none() { log::trace!( "recovered a Free for {object_id:?} without a preceeding Store" ); } } } } let mut recovered: Vec = recovered.into_values().collect(); recovered.par_sort_unstable(); // write fresh snapshot with recovered data let new_snapshot_data = serialize_batch(&recovered); let snapshot_size = new_snapshot_data.len() as u64; let new_snapshot_tmp_path = snapshot_path(path, max_log_id, true); log::trace!("writing snapshot to {new_snapshot_tmp_path:?}"); let mut snapshot_file_opts = fs::OpenOptions::new(); snapshot_file_opts.create(true).read(false).write(true); let mut snapshot_file = fallible!(snapshot_file_opts.open(&new_snapshot_tmp_path)); fallible!(snapshot_file.write_all(&new_snapshot_data)); drop(new_snapshot_data); fallible!(snapshot_file.sync_all()); let new_snapshot_path = snapshot_path(path, max_log_id, false); log::trace!("renaming written snapshot to {new_snapshot_path:?}"); fallible!(fs::rename(new_snapshot_tmp_path, new_snapshot_path)); fallible!(locked_directory.sync_all()); for log_id in &log_ids { let log_path = log_path(path, *log_id); fallible!(fs::remove_file(log_path)); } if let Some(old_snapshot_id) = snapshot_id_opt { let old_snapshot_path = snapshot_path(path, old_snapshot_id, false); fallible!(fs::remove_file(old_snapshot_path)); } Ok(MetadataRecovery { recovered, id_for_next_log: max_log_id + 1, snapshot_size, }) } ================================================ FILE: src/object_cache.rs ================================================ use std::cell::RefCell; use std::collections::HashMap; use std::io; use std::sync::Arc; use std::sync::atomic::{AtomicPtr, AtomicU64, Ordering}; use std::time::{Duration, Instant}; use cache_advisor::CacheAdvisor; use concurrent_map::{ConcurrentMap, Minimum}; use fault_injection::annotate; use inline_array::InlineArray; use parking_lot::RwLock; use crate::*; #[derive(Debug, Copy, Clone)] pub struct CacheStats { pub cache_hits: u64, pub cache_misses: u64, pub cache_hit_ratio: f32, pub max_read_io_latency_us: u64, pub sum_read_io_latency_us: u64, pub deserialization_latency_max_us: u64, pub deserialization_latency_sum_us: u64, pub heap: HeapStats, pub flush_max: FlushStats, pub flush_sum: FlushStats, pub compacted_heap_slots: u64, pub tree_leaves_merged: u64, } #[derive(Default, Debug, Clone, Copy)] pub struct FlushStats { pub pre_block_on_previous_flush: Duration, pub pre_block_on_current_quiescence: Duration, pub serialization_latency: Duration, pub compute_defrag_latency: Duration, pub storage_latency: Duration, pub post_write_eviction_latency: Duration, pub objects_flushed: u64, pub write_batch: WriteBatchStats, } impl FlushStats { pub fn sum(&self, other: &FlushStats) -> FlushStats { use std::ops::Add; FlushStats { pre_block_on_previous_flush: self .pre_block_on_previous_flush .add(other.pre_block_on_previous_flush), pre_block_on_current_quiescence: self .pre_block_on_current_quiescence .add(other.pre_block_on_current_quiescence), compute_defrag_latency: self .compute_defrag_latency .add(other.compute_defrag_latency), serialization_latency: self .serialization_latency .add(other.serialization_latency), storage_latency: self.storage_latency.add(other.storage_latency), post_write_eviction_latency: self .post_write_eviction_latency .add(other.post_write_eviction_latency), objects_flushed: self.objects_flushed.add(other.objects_flushed), write_batch: self.write_batch.sum(&other.write_batch), } } pub fn max(&self, other: &FlushStats) -> FlushStats { FlushStats { pre_block_on_previous_flush: self .pre_block_on_previous_flush .max(other.pre_block_on_previous_flush), pre_block_on_current_quiescence: self .pre_block_on_current_quiescence .max(other.pre_block_on_current_quiescence), compute_defrag_latency: self .compute_defrag_latency .max(other.compute_defrag_latency), serialization_latency: self .serialization_latency .max(other.serialization_latency), storage_latency: self.storage_latency.max(other.storage_latency), post_write_eviction_latency: self .post_write_eviction_latency .max(other.post_write_eviction_latency), objects_flushed: self.objects_flushed.max(other.objects_flushed), write_batch: self.write_batch.max(&other.write_batch), } } } #[derive(Clone, Debug, PartialEq)] pub enum Dirty { NotYetSerialized { low_key: InlineArray, node: Object, collection_id: CollectionId, }, CooperativelySerialized { object_id: ObjectId, collection_id: CollectionId, low_key: InlineArray, data: Arc>, mutation_count: u64, }, MergedAndDeleted { object_id: ObjectId, collection_id: CollectionId, }, } impl Dirty { pub fn is_final_state(&self) -> bool { match self { Dirty::NotYetSerialized { .. } => false, Dirty::CooperativelySerialized { .. } => true, Dirty::MergedAndDeleted { .. } => true, } } } #[derive(Debug, Default, Clone, Copy)] struct FlushStatTracker { count: u64, sum: FlushStats, max: FlushStats, } #[derive(Debug, Default)] pub(crate) struct ReadStatTracker { pub cache_hits: AtomicU64, pub cache_misses: AtomicU64, pub max_read_io_latency_us: AtomicU64, pub sum_read_io_latency_us: AtomicU64, pub max_deserialization_latency_us: AtomicU64, pub sum_deserialization_latency_us: AtomicU64, } #[derive(Clone)] pub struct ObjectCache { pub config: Config, global_error: Arc>, pub object_id_index: ConcurrentMap< ObjectId, Object, INDEX_FANOUT, EBR_LOCAL_GC_BUFFER_SIZE, >, heap: Heap, cache_advisor: RefCell, flush_epoch: FlushEpochTracker, dirty: ConcurrentMap<(FlushEpoch, ObjectId), Dirty, 4>, compacted_heap_slots: Arc, pub(super) tree_leaves_merged: Arc, #[cfg(feature = "for-internal-testing-only")] pub(super) event_verifier: Arc, invariants: Arc, flush_stats: Arc>, pub(super) read_stats: Arc, } impl std::panic::RefUnwindSafe for ObjectCache { } impl ObjectCache { /// Returns the recovered ObjectCache, the tree indexes, and a bool signifying whether the system /// was recovered or not pub fn recover( config: &Config, ) -> io::Result<( ObjectCache, HashMap>, bool, )> { let HeapRecovery { heap, recovered_nodes, was_recovered } = Heap::recover(LEAF_FANOUT, config)?; let (object_id_index, indices) = initialize(&recovered_nodes, &heap); // validate recovery for ObjectRecovery { object_id, collection_id, low_key } in recovered_nodes { let index = indices.get(&collection_id).unwrap(); let node = index.get(&low_key).unwrap(); assert_eq!(node.object_id, object_id); } if config.cache_capacity_bytes < 256 { log::debug!( "Db configured to have Config.cache_capacity_bytes \ of under 256, so we will use the minimum of 256 bytes instead" ); } if config.entry_cache_percent > 80 { log::debug!( "Db configured to have Config.entry_cache_percent\ of over 80%, so we will clamp it to the maximum of 80% instead" ); } let pc = ObjectCache { config: config.clone(), object_id_index, cache_advisor: RefCell::new(CacheAdvisor::new( config.cache_capacity_bytes.max(256), config.entry_cache_percent.min(80), )), global_error: heap.get_global_error_arc(), heap, dirty: Default::default(), flush_epoch: Default::default(), #[cfg(feature = "for-internal-testing-only")] event_verifier: Arc::default(), compacted_heap_slots: Arc::default(), tree_leaves_merged: Arc::default(), invariants: Arc::default(), flush_stats: Arc::default(), read_stats: Arc::default(), }; Ok((pc, indices, was_recovered)) } pub fn is_clean(&self) -> bool { self.dirty.is_empty() } pub fn read(&self, object_id: ObjectId) -> Option>> { match self.heap.read(object_id) { Some(Ok(buf)) => Some(Ok(buf)), Some(Err(e)) => Some(Err(annotate!(e))), None => None, } } pub fn stats(&self) -> CacheStats { let flush_stats = { *self.flush_stats.read() }; let cache_hits = self.read_stats.cache_hits.load(Ordering::Acquire); let cache_misses = self.read_stats.cache_misses.load(Ordering::Acquire); let cache_hit_ratio = cache_hits as f32 / (cache_hits + cache_misses).max(1) as f32; CacheStats { cache_hits, cache_misses, cache_hit_ratio, compacted_heap_slots: self .compacted_heap_slots .load(Ordering::Acquire), tree_leaves_merged: self.tree_leaves_merged.load(Ordering::Acquire), heap: self.heap.stats(), flush_max: flush_stats.max, flush_sum: flush_stats.sum, deserialization_latency_max_us: self .read_stats .max_deserialization_latency_us .load(Ordering::Acquire), deserialization_latency_sum_us: self .read_stats .sum_deserialization_latency_us .load(Ordering::Acquire), max_read_io_latency_us: self .read_stats .max_read_io_latency_us .load(Ordering::Acquire), sum_read_io_latency_us: self .read_stats .sum_read_io_latency_us .load(Ordering::Acquire), } } pub fn check_error(&self) -> io::Result<()> { let err_ptr: *const (io::ErrorKind, String) = self.global_error.load(Ordering::Acquire); if err_ptr.is_null() { Ok(()) } else { let deref: &(io::ErrorKind, String) = unsafe { &*err_ptr }; Err(io::Error::new(deref.0, deref.1.clone())) } } pub fn set_error(&self, error: &io::Error) { let kind = error.kind(); let reason = error.to_string(); let boxed = Box::new((kind, reason)); let ptr = Box::into_raw(boxed); if self .global_error .compare_exchange( std::ptr::null_mut(), ptr, Ordering::SeqCst, Ordering::SeqCst, ) .is_err() { // global fatal error already installed, drop this one unsafe { drop(Box::from_raw(ptr)); } } } pub fn allocate_default_node( &self, collection_id: CollectionId, ) -> Object { let object_id = self.allocate_object_id(FlushEpoch::MIN); let node = Object { object_id, collection_id, low_key: InlineArray::default(), inner: Arc::new(RwLock::new(CacheBox { leaf: Some(Box::new(Leaf::empty())), logged_index: BTreeMap::default(), })), }; self.object_id_index.insert(object_id, node.clone()); node } pub fn allocate_object_id( &self, #[allow(unused)] flush_epoch: FlushEpoch, ) -> ObjectId { let object_id = self.heap.allocate_object_id(); #[cfg(feature = "for-internal-testing-only")] { self.event_verifier.mark( object_id, flush_epoch, event_verifier::State::CleanPagedIn, concat!(file!(), ':', line!(), ":allocated"), ); } object_id } pub fn current_flush_epoch(&self) -> FlushEpoch { self.flush_epoch.current_flush_epoch() } pub fn check_into_flush_epoch(&self) -> FlushEpochGuard { self.flush_epoch.check_in() } pub fn install_dirty( &self, flush_epoch: FlushEpoch, object_id: ObjectId, dirty: Dirty, ) { // dirty can transition from: // None -> NotYetSerialized // None -> MergedAndDeleted // None -> CooperativelySerialized // // NotYetSerialized -> MergedAndDeleted // NotYetSerialized -> CooperativelySerialized // // if the new Dirty is final, we must assert that // we are transitioning from None or NotYetSerialized. // // if the new Dirty is not final, we must assert // that the old value is also not final. let last_dirty_opt = self.dirty.insert((flush_epoch, object_id), dirty); if let Some(last_dirty) = last_dirty_opt { assert!( !last_dirty.is_final_state(), "tried to install another Dirty marker for a node that is already finalized for this flush epoch. \nflush_epoch: {:?}\nlast: {:?}", flush_epoch, last_dirty, ); } } // NB: must not be called while holding a leaf lock - which also means // that no two LeafGuards can be held concurrently in the same scope due to // this being called in the destructor. pub fn mark_access_and_evict( &self, accessed_object_id: ObjectId, size: usize, #[allow(unused)] flush_epoch: FlushEpoch, ) -> io::Result<()> { let mut ca = self.cache_advisor.borrow_mut(); let to_evict = ca.accessed_reuse_buffer(*accessed_object_id, size); let mut not_found = 0; for (node_to_evict, _rough_size) in to_evict { let object_id = if let Some(object_id) = ObjectId::new(*node_to_evict) { object_id } else { unreachable!("object ID must never have been 0"); }; if accessed_object_id == object_id { // TODO our own object was evicted, so // set page out after current epoch (or just page out if clean?) continue; } let node = if let Some(n) = self.object_id_index.get(&object_id) { if *n.object_id != *node_to_evict { continue; } n } else { not_found += 1; continue; }; let mut write = node.inner.write(); if write.leaf.is_none() { // already paged out continue; } let leaf: &mut Leaf = write.leaf.as_mut().unwrap(); if let Some(dirty_epoch) = leaf.dirty_flush_epoch { // We can't page out this leaf until it has been // flushed, because its changes are not yet durable. leaf.page_out_on_flush = leaf.page_out_on_flush.max(Some(dirty_epoch)); } else if let Some(max_unflushed_epoch) = leaf.max_unflushed_epoch { leaf.page_out_on_flush = leaf.page_out_on_flush.max(Some(max_unflushed_epoch)); } else { #[cfg(feature = "for-internal-testing-only")] { self.event_verifier.mark( node.object_id, flush_epoch, event_verifier::State::PagedOut, concat!(file!(), ':', line!(), ":page-out"), ); } write.leaf = None; } } if not_found > 0 { log::trace!( "during cache eviction, did not find {} nodes that we were trying to evict", not_found ); } Ok(()) } pub fn heap_object_id_pin(&self) -> ebr::Guard<'_, DeferredFree, 16, 16> { self.heap.heap_object_id_pin() } pub fn flush(&self) -> io::Result { let mut write_batch = vec![]; log::trace!("advancing epoch"); let ( previous_flush_complete_notifier, this_vacant_notifier, forward_flush_notifier, ) = self.flush_epoch.roll_epoch_forward(); let before_previous_block = Instant::now(); log::trace!( "waiting for previous flush of {:?} to complete", previous_flush_complete_notifier.epoch() ); let previous_epoch = previous_flush_complete_notifier.wait_for_complete(); let pre_block_on_previous_flush = before_previous_block.elapsed(); let before_current_quiescence = Instant::now(); log::trace!( "waiting for our epoch {:?} to become vacant", this_vacant_notifier.epoch() ); assert_eq!(previous_epoch.increment(), this_vacant_notifier.epoch()); let flush_through_epoch: FlushEpoch = this_vacant_notifier.wait_for_complete(); let pre_block_on_current_quiescence = before_current_quiescence.elapsed(); self.invariants.mark_flushing_epoch(flush_through_epoch); let mut objects_to_defrag = self.heap.objects_to_defrag(); let flush_boundary = (flush_through_epoch.increment(), ObjectId::MIN); let mut evict_after_flush = vec![]; let before_serialization = Instant::now(); for ((dirty_epoch, dirty_object_id), dirty_value_initial_read) in self.dirty.range(..flush_boundary) { objects_to_defrag.remove(&dirty_object_id); let dirty_value = self .dirty .remove(&(dirty_epoch, dirty_object_id)) .expect("violation of flush responsibility"); if let Dirty::NotYetSerialized { .. } = &dirty_value { assert_eq!(dirty_value_initial_read, dirty_value); } // drop is necessary to increase chance of Arc strong count reaching 1 // while taking ownership of the value drop(dirty_value_initial_read); assert_eq!(dirty_epoch, flush_through_epoch); match dirty_value { Dirty::MergedAndDeleted { object_id, collection_id } => { assert_eq!(object_id, dirty_object_id); log::trace!( "MergedAndDeleted for {:?}, adding None to write_batch", object_id ); write_batch.push(Update::Free { object_id, collection_id }); #[cfg(feature = "for-internal-testing-only")] { self.event_verifier.mark( object_id, dirty_epoch, event_verifier::State::AddedToWriteBatch, concat!( file!(), ':', line!(), ":flush-merged-and-deleted" ), ); } } Dirty::CooperativelySerialized { object_id: _, collection_id, low_key, mutation_count: _, mut data, } => { Arc::make_mut(&mut data); let data = Arc::into_inner(data).unwrap(); write_batch.push(Update::Store { object_id: dirty_object_id, collection_id, low_key, data, }); #[cfg(feature = "for-internal-testing-only")] { self.event_verifier.mark( dirty_object_id, dirty_epoch, event_verifier::State::AddedToWriteBatch, concat!( file!(), ':', line!(), ":flush-cooperative" ), ); } } Dirty::NotYetSerialized { low_key, collection_id, node } => { assert_eq!(low_key, node.low_key); assert_eq!( dirty_object_id, node.object_id, "mismatched node ID for NotYetSerialized with low key {:?}", low_key ); let mut lock = node.inner.write(); let leaf_ref: &mut Leaf = if let Some( lock_ref, ) = lock.leaf.as_mut() { lock_ref } else { #[cfg(feature = "for-internal-testing-only")] self.event_verifier .print_debug_history_for_object(dirty_object_id); panic!( "failed to get lock for node that was NotYetSerialized, low key {:?} id {:?}", low_key, node.object_id ); }; assert_eq!(leaf_ref.lo, low_key); let data = if leaf_ref.dirty_flush_epoch == Some(flush_through_epoch) { if let Some(deleted_at) = leaf_ref.deleted { #[cfg(feature = "for-internal-testing-only")] if deleted_at <= flush_through_epoch { println!( "{dirty_object_id:?} deleted at {deleted_at:?} \ but we are flushing at {flush_through_epoch:?}" ); self.event_verifier .print_debug_history_for_object( dirty_object_id, ); } assert!(deleted_at > flush_through_epoch); } leaf_ref.max_unflushed_epoch = leaf_ref.dirty_flush_epoch.take(); #[cfg(feature = "for-internal-testing-only")] { self.event_verifier.mark( dirty_object_id, dirty_epoch, event_verifier::State::AddedToWriteBatch, concat!( file!(), ':', line!(), ":flush-serialize" ), ); } leaf_ref.serialize(self.config.zstd_compression_level) } else { // Here we expect that there was a benign data race and that another thread // mutated the leaf after encountering it being dirty for our epoch, after // storing a CooperativelySerialized in the dirty map. let dirty_value_2_opt = self.dirty.remove(&(dirty_epoch, dirty_object_id)); if let Some(Dirty::CooperativelySerialized { low_key: low_key_2, mutation_count: _, mut data, collection_id: ci2, object_id: ni2, }) = dirty_value_2_opt { assert_eq!(node.object_id, ni2); assert_eq!(node.object_id, dirty_object_id); assert_eq!(low_key, low_key_2); assert_eq!(node.low_key, low_key); assert_eq!(collection_id, ci2); Arc::make_mut(&mut data); #[cfg(feature = "for-internal-testing-only")] { self.event_verifier.mark( dirty_object_id, dirty_epoch, event_verifier::State::AddedToWriteBatch, concat!( file!(), ':', line!(), ":flush-laggy-cooperative" ), ); } Arc::into_inner(data).unwrap() } else { log::error!( "violation of flush responsibility for second read \ of expected cooperative serialization. leaf in question's \ dirty_flush_epoch is {:?}, our expected key was {:?}. node.deleted: {:?}", leaf_ref.dirty_flush_epoch, (dirty_epoch, dirty_object_id), leaf_ref.deleted, ); #[cfg(feature = "for-internal-testing-only")] self.event_verifier.print_debug_history_for_object( dirty_object_id, ); unreachable!( "a leaf was expected to be cooperatively serialized but it was not available. \ violation of flush responsibility for second read \ of expected cooperative serialization. leaf in question's \ dirty_flush_epoch is {:?}, our expected key was {:?}. node.deleted: {:?}", leaf_ref.dirty_flush_epoch, (dirty_epoch, dirty_object_id), leaf_ref.deleted, ); } }; write_batch.push(Update::Store { object_id: dirty_object_id, collection_id, low_key, data, }); if leaf_ref.page_out_on_flush == Some(flush_through_epoch) { // page_out_on_flush is set to false // on page-in due to serde(skip) evict_after_flush.push(node.clone()); } } } } if !objects_to_defrag.is_empty() { log::debug!( "objects to defrag (after flush loop): {}", objects_to_defrag.len() ); self.compacted_heap_slots .fetch_add(objects_to_defrag.len() as u64, Ordering::Relaxed); } let before_compute_defrag = Instant::now(); if cfg!(not(feature = "monotonic-behavior")) { let mut object_not_found = 0; for fragmented_object_id in objects_to_defrag { let object_opt = self.object_id_index.get(&fragmented_object_id); let object = if let Some(object) = object_opt { object } else { object_not_found += 1; continue; }; if let Some(ref inner) = object.inner.read().leaf { if let Some(dirty) = inner.dirty_flush_epoch { assert!(dirty > flush_through_epoch); // This object will be rewritten anyway when its dirty epoch gets flushed continue; } } let data = match self.read(fragmented_object_id) { Some(Ok(data)) => data, Some(Err(e)) => { let annotated = annotate!(e); log::error!( "failed to read object during GC: {annotated:?}" ); continue; } None => { log::error!( "failed to read object during GC: object not found" ); continue; } }; write_batch.push(Update::Store { object_id: fragmented_object_id, collection_id: object.collection_id, low_key: object.low_key, data, }); } if object_not_found > 0 { log::debug!( "{} objects not found while defragmenting", object_not_found ); } } let compute_defrag_latency = before_compute_defrag.elapsed(); let serialization_latency = before_serialization.elapsed(); let before_storage = Instant::now(); let objects_flushed = write_batch.len() as u64; #[cfg(feature = "for-internal-testing-only")] let write_batch_object_ids: Vec = write_batch.iter().map(Update::object_id).collect(); let write_batch_stats = if objects_flushed > 0 { let write_batch_stats = self.heap.write_batch(write_batch)?; log::trace!( "marking {flush_through_epoch:?} as flushed - \ {objects_flushed} objects written, {write_batch_stats:?}", ); write_batch_stats } else { WriteBatchStats::default() }; let storage_latency = before_storage.elapsed(); #[cfg(feature = "for-internal-testing-only")] { for update_object_id in write_batch_object_ids { self.event_verifier.mark( update_object_id, flush_through_epoch, event_verifier::State::Flushed, concat!(file!(), ':', line!(), ":flush-finished"), ); } } log::trace!( "marking the forward flush notifier that {:?} is flushed", flush_through_epoch ); self.invariants.mark_flushed_epoch(flush_through_epoch); forward_flush_notifier.mark_complete(); let before_eviction = Instant::now(); for node_to_evict in evict_after_flush { // NB: since we dropped this leaf and lock after we marked its // node in evict_after_flush, it's possible that it may have // been written to afterwards. let mut lock = node_to_evict.inner.write(); let leaf = lock.leaf.as_mut().unwrap(); if let Some(dirty_epoch) = leaf.dirty_flush_epoch { if dirty_epoch != flush_through_epoch { continue; } } else { continue; } #[cfg(feature = "for-internal-testing-only")] { self.event_verifier.mark( node_to_evict.object_id, flush_through_epoch, event_verifier::State::PagedOut, concat!(file!(), ':', line!(), ":page-out-after-flush"), ); } lock.leaf = None; } let post_write_eviction_latency = before_eviction.elapsed(); // kick forward the low level epoch-based reclamation systems // because this operation can cause a lot of garbage to build // up, and this speeds up its reclamation. self.flush_epoch.manually_advance_epoch(); self.heap.manually_advance_epoch(); let ret = FlushStats { pre_block_on_current_quiescence, pre_block_on_previous_flush, serialization_latency, storage_latency, post_write_eviction_latency, objects_flushed, write_batch: write_batch_stats, compute_defrag_latency, }; let mut flush_stats = self.flush_stats.write(); flush_stats.count += 1; flush_stats.max = flush_stats.max.max(&ret); flush_stats.sum = flush_stats.sum.sum(&ret); assert_eq!(self.dirty.range(..flush_boundary).count(), 0); Ok(ret) } } fn initialize( recovered_nodes: &[ObjectRecovery], heap: &Heap, ) -> ( ConcurrentMap< ObjectId, Object, INDEX_FANOUT, EBR_LOCAL_GC_BUFFER_SIZE, >, HashMap>, ) { let mut trees: HashMap> = HashMap::new(); let object_id_index: ConcurrentMap< ObjectId, Object, INDEX_FANOUT, EBR_LOCAL_GC_BUFFER_SIZE, > = ConcurrentMap::default(); for ObjectRecovery { object_id, collection_id, low_key } in recovered_nodes { let node = Object { object_id: *object_id, collection_id: *collection_id, low_key: low_key.clone(), inner: Arc::new(RwLock::new(CacheBox { leaf: None, logged_index: BTreeMap::default(), })), }; assert!(object_id_index.insert(*object_id, node.clone()).is_none()); let tree = trees.entry(*collection_id).or_default(); assert!( tree.insert(low_key.clone(), node).is_none(), "inserted multiple objects with low key {:?}", low_key ); } // initialize default collections if not recovered for collection_id in [NAME_MAPPING_COLLECTION_ID, DEFAULT_COLLECTION_ID] { let tree = trees.entry(collection_id).or_default(); if tree.is_empty() { let object_id = heap.allocate_object_id(); let initial_low_key = InlineArray::MIN; let empty_node = Object { object_id, collection_id, low_key: initial_low_key.clone(), inner: Arc::new(RwLock::new(CacheBox { leaf: Some(Box::new(Leaf::empty())), logged_index: BTreeMap::default(), })), }; assert!( object_id_index.insert(object_id, empty_node.clone()).is_none() ); assert!(tree.insert(initial_low_key, empty_node).is_none()); } else { assert!( tree.contains_key(&InlineArray::MIN), "tree {:?} had no minimum node", collection_id ); } } for (cid, tree) in &trees { assert!( tree.contains_key(&InlineArray::MIN), "tree {:?} had no minimum node", cid ); } (object_id_index, trees) } ================================================ FILE: src/object_location_mapper.rs ================================================ use std::num::NonZeroU64; use std::sync::Arc; use std::sync::atomic::{AtomicU64, Ordering}; use fnv::FnvHashSet; use pagetable::PageTable; use crate::{ Allocator, ObjectId, heap::{N_SLABS, SlabAddress, UpdateMetadata}, }; #[derive(Debug, Default, Copy, Clone)] pub struct AllocatorStats { pub objects_allocated: u64, pub objects_freed: u64, pub heap_slots_allocated: u64, pub heap_slots_freed: u64, } #[derive(Default)] struct SlabTenancy { slot_to_object_id: PageTable, slot_allocator: Arc, } impl SlabTenancy { // returns (ObjectId, slot index) pairs fn objects_to_defrag( &self, target_fill_ratio: f32, ) -> Vec<(ObjectId, u64)> { let (frag_min, frag_max) = if let Some(frag) = self.slot_allocator.fragmentation_cutoff(target_fill_ratio) { frag } else { return vec![]; }; let mut ret = vec![]; for fragmented_slot in frag_min..frag_max { let object_id_u64 = self .slot_to_object_id .get(fragmented_slot) .load(Ordering::Acquire); if let Some(object_id) = ObjectId::new(object_id_u64) { ret.push((object_id, fragmented_slot)); } } ret } } #[derive(Clone)] pub(crate) struct ObjectLocationMapper { object_id_to_location: PageTable, slab_tenancies: Arc<[SlabTenancy; N_SLABS]>, object_id_allocator: Arc, target_fill_ratio: f32, } impl ObjectLocationMapper { pub(crate) fn new( recovered_metadata: &[UpdateMetadata], target_fill_ratio: f32, ) -> ObjectLocationMapper { let mut ret = ObjectLocationMapper { object_id_to_location: PageTable::default(), slab_tenancies: Arc::new(core::array::from_fn(|_| { SlabTenancy::default() })), object_id_allocator: Arc::default(), target_fill_ratio, }; let mut object_ids: FnvHashSet = Default::default(); let mut slots_per_slab: [FnvHashSet; N_SLABS] = core::array::from_fn(|_| Default::default()); for update_metadata in recovered_metadata { match update_metadata { UpdateMetadata::Store { object_id, collection_id: _, location, low_key: _, } => { object_ids.insert(**object_id); let slab_address = SlabAddress::from(*location); slots_per_slab[slab_address.slab() as usize] .insert(slab_address.slot()); ret.insert(*object_id, slab_address); } UpdateMetadata::Free { .. } => { unreachable!() } } } ret.object_id_allocator = Arc::new(Allocator::from_allocated(&object_ids)); let slabs = Arc::get_mut(&mut ret.slab_tenancies).unwrap(); for i in 0..N_SLABS { let slab = &mut slabs[i]; slab.slot_allocator = Arc::new(Allocator::from_allocated(&slots_per_slab[i])); } ret } pub(crate) fn get_max_allocated_per_slab(&self) -> Vec<(usize, u64)> { let mut ret = vec![]; for (i, slab) in self.slab_tenancies.iter().enumerate() { if let Some(max_allocated) = slab.slot_allocator.max_allocated() { ret.push((i, max_allocated)); } } ret } pub(crate) fn stats(&self) -> AllocatorStats { let (objects_allocated, objects_freed) = self.object_id_allocator.counters(); let mut heap_slots_allocated = 0; let mut heap_slots_freed = 0; for slab_id in 0..N_SLABS { let (allocated, freed) = self.slab_tenancies[slab_id].slot_allocator.counters(); heap_slots_allocated += allocated; heap_slots_freed += freed; } AllocatorStats { objects_allocated, objects_freed, heap_slots_allocated, heap_slots_freed, } } pub(crate) fn clone_object_id_allocator_arc(&self) -> Arc { self.object_id_allocator.clone() } pub(crate) fn allocate_object_id(&self) -> ObjectId { // object IDs wrap a NonZeroU64, so if we get 0, just re-allocate and leak the id let mut object_id = self.object_id_allocator.allocate(); if object_id == 0 { object_id = self.object_id_allocator.allocate(); assert_ne!(object_id, 0); } ObjectId::new(object_id).unwrap() } pub(crate) fn clone_slab_allocator_arc( &self, slab_id: u8, ) -> Arc { self.slab_tenancies[usize::from(slab_id)].slot_allocator.clone() } pub(crate) fn allocate_slab_slot(&self, slab_id: u8) -> SlabAddress { let slot = self.slab_tenancies[usize::from(slab_id)].slot_allocator.allocate(); SlabAddress::from_slab_slot(slab_id, slot) } pub(crate) fn free_slab_slot(&self, slab_address: SlabAddress) { self.slab_tenancies[usize::from(slab_address.slab())] .slot_allocator .free(slab_address.slot()) } pub(crate) fn get_location_for_object( &self, object_id: ObjectId, ) -> Option { let location_u64 = self.object_id_to_location.get(*object_id).load(Ordering::Acquire); let nzu = NonZeroU64::new(location_u64)?; Some(SlabAddress::from(nzu)) } /// Returns the previous address for this object, if it is vacating one. /// /// # Panics /// /// Asserts that the new location is actually unoccupied. This is a major /// correctness violation if that isn't true. pub(crate) fn insert( &self, object_id: ObjectId, new_location: SlabAddress, ) -> Option { // insert into object_id_to_location let location_nzu: NonZeroU64 = new_location.into(); let location_u64 = location_nzu.get(); let last_u64 = self .object_id_to_location .get(*object_id) .swap(location_u64, Ordering::Release); let last_address_opt = if let Some(nzu) = NonZeroU64::new(last_u64) { let last_address = SlabAddress::from(nzu); Some(last_address) } else { None }; // insert into slab_tenancies let slab = new_location.slab(); let slot = new_location.slot(); let _last_oid_at_location = self.slab_tenancies[usize::from(slab)] .slot_to_object_id .get(slot) .swap(*object_id, Ordering::Release); // TODO add debug event verifier here assert_eq!(0, last_oid_at_location); last_address_opt } /// Unmaps an object and returns its location. /// /// # Panics /// /// Asserts that the object was actually stored in a location. pub(crate) fn remove(&self, object_id: ObjectId) -> Option { let last_u64 = self .object_id_to_location .get(*object_id) .swap(0, Ordering::Release); if let Some(nzu) = NonZeroU64::new(last_u64) { let last_address = SlabAddress::from(nzu); let slab = last_address.slab(); let slot = last_address.slot(); let last_oid_at_location = self.slab_tenancies[usize::from(slab)] .slot_to_object_id .get(slot) .swap(0, Ordering::Release); assert_eq!(*object_id, last_oid_at_location); Some(last_address) } else { None } } pub(crate) fn objects_to_defrag(&self) -> FnvHashSet { let mut ret = FnvHashSet::default(); for slab_id in 0..N_SLABS { let slab = &self.slab_tenancies[slab_id]; for (object_id, slot) in slab.objects_to_defrag(self.target_fill_ratio) { let sa = SlabAddress::from_slab_slot( u8::try_from(slab_id).unwrap(), slot, ); let rt_sa = if let Some(rt_raw_sa) = NonZeroU64::new( self.object_id_to_location .get(*object_id) .load(Ordering::Acquire), ) { SlabAddress::from(rt_raw_sa) } else { // object has been removed but its slot has not yet been freed, // hopefully due to a deferred write // TODO test that with a testing event log continue; }; if sa == rt_sa { let newly_inserted = ret.insert(object_id); assert!( newly_inserted, "{object_id:?} present multiple times across slab objects_to_defrag" ); } } } ret } } ================================================ FILE: src/tree.rs ================================================ use std::collections::{BTreeMap, VecDeque}; use std::fmt; use std::hint; use std::io; use std::mem::ManuallyDrop; use std::ops; use std::ops::Bound; use std::ops::RangeBounds; use std::sync::Arc; use std::sync::atomic::Ordering; use std::time::Instant; use concurrent_map::Minimum; use fault_injection::annotate; use inline_array::InlineArray; use parking_lot::{ RawRwLock, lock_api::{ArcRwLockReadGuard, ArcRwLockWriteGuard}, }; use crate::*; #[cfg(feature = "for-internal-testing-only")] use crate::block_checker::track_blocks; #[derive(Clone)] pub struct Tree { collection_id: CollectionId, cache: ObjectCache, pub(crate) index: Index, _shutdown_dropper: Arc>, } impl Drop for Tree { fn drop(&mut self) { if self.cache.config.flush_every_ms.is_none() { if let Err(e) = self.flush() { log::error!("failed to flush Db on Drop: {e:?}"); } } else { // otherwise, it is expected that the flusher thread will // flush while shutting down the final Db/Tree instance } } } impl fmt::Debug for Tree { fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result { let alternate = w.alternate(); let mut debug_struct = w.debug_struct(&format!("Db<{}>", LEAF_FANOUT)); if alternate { debug_struct .field("global_error", &self.check_error()) .field( "data", &format!("{:?}", self.iter().collect::>()), ) .finish() } else { debug_struct.field("global_error", &self.check_error()).finish() } } } #[must_use] struct LeafReadGuard<'a, const LEAF_FANOUT: usize = 1024> { leaf_read: ManuallyDrop>>, low_key: InlineArray, inner: &'a Tree, object_id: ObjectId, external_cache_access_and_eviction: bool, } impl Drop for LeafReadGuard<'_, LEAF_FANOUT> { fn drop(&mut self) { let size = self.leaf_read.leaf.as_ref().unwrap().in_memory_size; // we must drop our mutex before calling mark_access_and_evict unsafe { ManuallyDrop::drop(&mut self.leaf_read); } if self.external_cache_access_and_eviction { return; } let current_epoch = self.inner.cache.current_flush_epoch(); if let Err(e) = self.inner.cache.mark_access_and_evict( self.object_id, size, current_epoch, ) { self.inner.set_error(&e); log::error!( "io error while paging out dirty data: {:?} \ for guard of leaf with low key {:?}", e, self.low_key ); } } } struct LeafWriteGuard<'a, const LEAF_FANOUT: usize = 1024> { leaf_write: ManuallyDrop>>, flush_epoch_guard: FlushEpochGuard<'a>, low_key: InlineArray, inner: &'a Tree, node: Object, external_cache_access_and_eviction: bool, } impl LeafWriteGuard<'_, LEAF_FANOUT> { fn epoch(&self) -> FlushEpoch { self.flush_epoch_guard.epoch() } // Handling cache access involves acquiring a mutex to anything // that is being paged-out so that it can be dropped. We call // this for things that we want to perform cache fn handle_cache_access_and_eviction_externally( mut self, ) -> (ObjectId, usize) { self.external_cache_access_and_eviction = true; ( self.node.object_id, self.leaf_write.leaf.as_ref().unwrap().in_memory_size, ) } } impl Drop for LeafWriteGuard<'_, LEAF_FANOUT> { fn drop(&mut self) { let size = self.leaf_write.leaf.as_ref().unwrap().in_memory_size; // we must drop our mutex before calling mark_access_and_evict unsafe { ManuallyDrop::drop(&mut self.leaf_write); } if self.external_cache_access_and_eviction { return; } if let Err(e) = self.inner.cache.mark_access_and_evict( self.node.object_id, size, self.epoch(), ) { self.inner.set_error(&e); log::error!("io error while paging out dirty data: {:?}", e); } } } impl Tree { pub(crate) fn new( collection_id: CollectionId, cache: ObjectCache, index: Index, _shutdown_dropper: Arc>, ) -> Tree { Tree { collection_id, cache, index, _shutdown_dropper } } // This is only pub for an extra assertion during testing. #[doc(hidden)] pub fn check_error(&self) -> io::Result<()> { self.cache.check_error() } fn set_error(&self, error: &io::Error) { self.cache.set_error(error) } pub fn storage_stats(&self) -> Stats { Stats { cache: self.cache.stats() } } /// Synchronously flushes all dirty IO buffers and calls /// fsync. If this succeeds, it is guaranteed that all /// previous writes will be recovered if the system /// crashes. Returns the number of bytes flushed during /// this call. /// /// Flushing can take quite a lot of time, and you should /// measure the performance impact of using it on /// realistic sustained workloads running on realistic /// hardware. /// /// This is called automatically on drop of the last open Db /// instance. pub fn flush(&self) -> io::Result { self.cache.flush() } pub(crate) fn page_in( &self, key: &[u8], flush_epoch: FlushEpoch, ) -> io::Result<( InlineArray, ArcRwLockWriteGuard>, Object, )> { let before_read_io = Instant::now(); #[cfg(feature = "for-internal-testing-only")] let _b0 = track_blocks(); let mut loops: u64 = 0; let mut last_continue = "none"; let mut warned = false; loop { loops += 1; if loops > 10_000_000 && !warned { log::warn!( "page_in spinning for a long time due to continue point {}", last_continue ); warned = true; #[cfg(feature = "for-internal-testing-only")] assert!( loops <= 10_000_000, "stuck in loop at continue point: {}, search key: {:?}", last_continue, key, ); } let _heap_pin = self.cache.heap_object_id_pin(); let (low_key, node) = self.index.get_lte(key).unwrap(); if node.collection_id != self.collection_id { log::trace!("retry due to mismatched collection id in page_in"); hint::spin_loop(); last_continue = concat!(file!(), ':', line!()); continue; } #[cfg(feature = "for-internal-testing-only")] let _b1 = track_blocks(); let mut write = node.inner.write_arc(); if write.leaf.is_none() { self.cache .read_stats .cache_misses .fetch_add(1, Ordering::Relaxed); let leaf_bytes = if let Some(read_res) = self.cache.read(node.object_id) { match read_res { Ok(buf) => buf, Err(e) => return Err(annotate!(e)), } } else { hint::spin_loop(); last_continue = concat!(file!(), ':', line!()); continue; }; let read_io_latency_us = u64::try_from(before_read_io.elapsed().as_micros()) .unwrap(); self.cache .read_stats .max_read_io_latency_us .fetch_max(read_io_latency_us, Ordering::Relaxed); self.cache .read_stats .sum_read_io_latency_us .fetch_add(read_io_latency_us, Ordering::Relaxed); let before_deserialization = Instant::now(); let leaf: Box> = Leaf::deserialize(&leaf_bytes).unwrap(); if leaf.lo != low_key { // TODO determine why this rare situation occurs and better // understand whether it is really benign. log::trace!("mismatch between object key and leaf low"); hint::spin_loop(); last_continue = concat!(file!(), ':', line!()); continue; } let deserialization_latency_us = u64::try_from(before_deserialization.elapsed().as_micros()) .unwrap(); self.cache .read_stats .max_deserialization_latency_us .fetch_max(deserialization_latency_us, Ordering::Relaxed); self.cache .read_stats .sum_deserialization_latency_us .fetch_add(deserialization_latency_us, Ordering::Relaxed); #[cfg(feature = "for-internal-testing-only")] { self.cache.event_verifier.mark( node.object_id, FlushEpoch::MIN, event_verifier::State::CleanPagedIn, concat!(file!(), ':', line!(), ":page-in"), ); } write.leaf = Some(leaf); } else { self.cache .read_stats .cache_hits .fetch_add(1, Ordering::Relaxed); } let leaf = write.leaf.as_mut().unwrap(); if leaf.deleted.is_some() { log::trace!("retry due to deleted node in page_in"); drop(write); hint::spin_loop(); last_continue = concat!(file!(), ':', line!()); continue; } if &*leaf.lo > key { let size = leaf.in_memory_size; drop(write); log::trace!("key undershoot in page_in"); self.cache.mark_access_and_evict( node.object_id, size, flush_epoch, )?; hint::spin_loop(); last_continue = concat!(file!(), ':', line!()); continue; } if let Some(ref hi) = leaf.hi { if &**hi <= key { let size = leaf.in_memory_size; log::trace!( "key overshoot in page_in - search key {:?}, node hi {:?}", key, hi ); drop(write); self.cache.mark_access_and_evict( node.object_id, size, flush_epoch, )?; hint::spin_loop(); last_continue = concat!(file!(), ':', line!()); continue; } } return Ok((low_key, write, node)); } } // NB: must never be called without having already added the empty leaf // operations to a normal flush epoch. This function acquires the lock // for the left sibling so that the empty leaf's hi key can be given // to the left sibling, but for this to happen atomically, the act of // moving left must "happen" in the same flush epoch. By "pushing" the // merge left potentially into a future flush epoch, any deletions that the // leaf had applied that may have been a part of a previous batch would also // be pushed into the future flush epoch, which would break the crash // atomicity of the batch if the updates were not flushed in the same epoch // as the rest of the batch. So, this is why we potentially separate the // flush of the left merge from the flush of the operations that caused // the leaf to empty in the first place. fn merge_leaf_into_right_sibling<'a>( &'a self, mut predecessor: LeafWriteGuard<'a, LEAF_FANOUT>, ) -> io::Result<()> { #[cfg(feature = "for-internal-testing-only")] let _b1 = track_blocks(); let mut successor = self.successor_leaf_mut(&predecessor)?; // This should be true because we acquire the successor // write mutex after acquiring the predecessor's. assert!(successor.epoch() >= predecessor.epoch()); let merge_epoch = predecessor.epoch().max(successor.epoch()); let predecessor_epoch = predecessor.epoch(); let predecessor_leaf = predecessor.leaf_write.leaf.as_mut().unwrap(); let successor_leaf = successor.leaf_write.leaf.as_mut().unwrap(); assert!(predecessor_leaf.deleted.is_none()); assert!(predecessor_leaf.is_empty()); assert!(successor_leaf.deleted.is_none()); assert_eq!( predecessor_leaf.hi.as_deref(), Some(successor_leaf.lo.as_ref()), ); log::trace!( "merging empty predecessor node id {} with low key {:?} and high key {:?} \ and successor node id {} with low key {:?} and high key {:?} into the \ predecessor", predecessor.node.object_id.0, predecessor_leaf.lo, predecessor_leaf.hi, successor.node.object_id.0, successor_leaf.lo, successor_leaf.hi ); if merge_epoch != predecessor_epoch { // need to cooperatively serialize predecessor so that whatever // writes caused it to be empty in the first place are atomically // persisted with the rest of any batch that may have caused that. self.cooperatively_serialize_leaf( predecessor.node.object_id, &mut *predecessor_leaf, ); } predecessor_leaf.set_dirty_epoch(merge_epoch); predecessor_leaf.merge_from(successor_leaf.as_mut()); successor_leaf.deleted = Some(merge_epoch); successor .inner .cache .tree_leaves_merged .fetch_add(1, Ordering::Relaxed); assert_eq!(successor.low_key, successor_leaf.lo); assert_eq!(predecessor.low_key, predecessor_leaf.lo); self.index.remove(&successor.low_key).unwrap(); self.cache.object_id_index.remove(&successor.node.object_id).unwrap(); // NB: these updates must "happen" atomically in the same flush epoch self.cache.install_dirty( merge_epoch, successor.node.object_id, Dirty::MergedAndDeleted { object_id: successor.node.object_id, collection_id: self.collection_id, }, ); #[cfg(feature = "for-internal-testing-only")] { self.cache.event_verifier.mark( successor.node.object_id, merge_epoch, event_verifier::State::Unallocated, concat!(file!(), ':', line!(), ":merged"), ); } self.cache.install_dirty( merge_epoch, predecessor.node.object_id, Dirty::NotYetSerialized { low_key: predecessor_leaf.lo.clone(), node: predecessor.node.clone(), collection_id: self.collection_id, }, ); #[cfg(feature = "for-internal-testing-only")] { self.cache.event_verifier.mark( predecessor.node.object_id, merge_epoch, event_verifier::State::Dirty, concat!(file!(), ':', line!(), ":merged-into"), ); } let (p_object_id, p_sz) = predecessor.handle_cache_access_and_eviction_externally(); let (s_object_id, s_sz) = successor.handle_cache_access_and_eviction_externally(); self.cache.mark_access_and_evict(p_object_id, p_sz, merge_epoch)?; self.cache.mark_access_and_evict(s_object_id, s_sz, merge_epoch)?; Ok(()) } fn successor_leaf_mut<'a>( &'a self, predecessor: &LeafWriteGuard<'a, LEAF_FANOUT>, ) -> io::Result> { let predecessor_leaf = predecessor.leaf_write.leaf.as_ref().unwrap(); assert!(predecessor_leaf.hi.is_some()); #[cfg(feature = "for-internal-testing-only")] let _b0 = track_blocks(); loop { let search_key = predecessor_leaf.hi.as_ref().unwrap(); #[cfg(feature = "for-internal-testing-only")] let _b1 = track_blocks(); let successor_node = self.leaf_for_key_mut(search_key)?; let successor_leaf = successor_node.leaf_write.leaf.as_ref().unwrap(); assert!(predecessor_leaf.lo < successor_leaf.lo); if predecessor_leaf.hi.as_ref().unwrap() > &successor_leaf.lo { let still_in_index = self.index.get(&successor_leaf.lo); panic!( "somehow, predecessor high key of {:?} \ is greater than successor low key of {:?}. current index presence: {:?} \n \ predecessor: {:?} \n successor: {:?}", predecessor_leaf.hi, successor_leaf.lo, still_in_index, predecessor_leaf, successor_leaf, ); } if predecessor_leaf.hi.as_ref().unwrap() != &successor_leaf.lo { continue; } return Ok(successor_node); } } fn cooperatively_serialize_leaf( &self, object_id: ObjectId, leaf: &mut Leaf, ) { // cooperatively serialize and put into dirty let old_dirty_epoch = leaf.dirty_flush_epoch.take().unwrap(); assert!(Some(old_dirty_epoch) > leaf.max_unflushed_epoch); leaf.max_unflushed_epoch = Some(old_dirty_epoch); leaf.page_out_on_flush.take(); log::trace!( "cooperatively serializing leaf id {:?} with low key {:?}", object_id, leaf.lo ); #[cfg(feature = "for-internal-testing-only")] { self.cache.event_verifier.mark( object_id, old_dirty_epoch, event_verifier::State::CooperativelySerialized, concat!(file!(), ':', line!(), ":cooperative-serialize"), ); } // be extra-explicit about serialized bytes let leaf_ref: &Leaf = &*leaf; let serialized = leaf_ref.serialize(self.cache.config.zstd_compression_level); log::trace!( "D adding node {} to dirty {:?}", object_id.0, old_dirty_epoch ); self.cache.install_dirty( old_dirty_epoch, object_id, Dirty::CooperativelySerialized { object_id, collection_id: self.collection_id, low_key: leaf.lo.clone(), mutation_count: leaf.mutation_count, data: Arc::new(serialized), }, ); } fn leaf_for_key<'a>( &'a self, key: &[u8], ) -> io::Result> { #[cfg(feature = "for-internal-testing-only")] let _b0 = track_blocks(); loop { let (low_key, node) = self.index.get_lte(key).unwrap(); #[cfg(feature = "for-internal-testing-only")] let _b1 = track_blocks(); let mut read = node.inner.read_arc(); if read.leaf.is_none() { drop(read); let (read_low_key, write, _node) = self.page_in(key, self.cache.current_flush_epoch())?; assert!(&*read_low_key <= key); read = ArcRwLockWriteGuard::downgrade(write); } else { self.cache .read_stats .cache_hits .fetch_add(1, Ordering::Relaxed); } let leaf_guard = LeafReadGuard { leaf_read: ManuallyDrop::new(read), inner: self, low_key, object_id: node.object_id, external_cache_access_and_eviction: false, }; let leaf = leaf_guard.leaf_read.leaf.as_ref().unwrap(); if leaf.deleted.is_some() { log::trace!("retry due to deleted node in leaf_for_key"); drop(leaf_guard); hint::spin_loop(); continue; } if &*leaf.lo > key { log::trace!("key undershoot in leaf_for_key"); drop(leaf_guard); hint::spin_loop(); continue; } if let Some(ref hi) = leaf.hi { if &**hi <= key { log::trace!("key overshoot on leaf_for_key"); // cache maintenance occurs in Drop for LeafReadGuard drop(leaf_guard); hint::spin_loop(); continue; } } if leaf.lo != node.low_key { // TODO determine why this rare situation occurs and better // understand whether it is really benign. log::trace!("mismatch between object key and leaf low"); // cache maintenance occurs in Drop for LeafReadGuard drop(leaf_guard); hint::spin_loop(); continue; } assert_eq!(node.low_key, leaf.lo); return Ok(leaf_guard); } } fn leaf_for_key_mut<'a>( &'a self, key: &[u8], ) -> io::Result> { let reader_epoch = self.cache.current_flush_epoch(); let (low_key, mut write, node) = self.page_in(key, reader_epoch)?; // by checking into an epoch after acquiring the node mutex, we // avoid inversions where progress may be observed to go backwards. let flush_epoch_guard = self.cache.check_into_flush_epoch(); let leaf = write.leaf.as_mut().unwrap(); // NB: these invariants should be enforced in page_in assert!(leaf.deleted.is_none()); assert!(&*leaf.lo <= key); if let Some(ref hi) = leaf.hi { assert!( &**hi > key, "while retrieving the leaf for key {:?} \ we pulled a leaf with hi key of {:?}", key, hi ); } if let Some(max_unflushed_epoch) = leaf.max_unflushed_epoch { // We already serialized something for this epoch, so if we did so again, // we need to think a bit. assert_ne!(max_unflushed_epoch, flush_epoch_guard.epoch()); } if let Some(old_dirty_epoch) = leaf.dirty_flush_epoch { if old_dirty_epoch != flush_epoch_guard.epoch() { assert!(old_dirty_epoch < flush_epoch_guard.epoch()); log::trace!( "cooperatively flushing {:?} with dirty {:?} after checking into {:?}", node.object_id, old_dirty_epoch, flush_epoch_guard.epoch() ); self.cooperatively_serialize_leaf(node.object_id, &mut *leaf); } } Ok(LeafWriteGuard { flush_epoch_guard, leaf_write: ManuallyDrop::new(write), inner: self, low_key, node, external_cache_access_and_eviction: false, }) } /// Retrieve a value from the `Tree` if it exists. /// /// # Examples /// /// ``` /// # fn main() -> Result<(), Box> { /// # let config = sled::Config::tmp().unwrap(); /// # let db: sled::Db<1024> = config.open()?; /// db.insert(&[0], vec![0])?; /// assert_eq!(db.get(&[0]).unwrap(), Some(sled::InlineArray::from(vec![0]))); /// assert!(db.get(&[1]).unwrap().is_none()); /// # Ok(()) } /// ``` pub fn get>( &self, key: K, ) -> io::Result> { self.check_error()?; let key_ref = key.as_ref(); let leaf_guard = self.leaf_for_key(key_ref)?; let leaf = leaf_guard.leaf_read.leaf.as_ref().unwrap(); if let Some(ref hi) = leaf.hi { assert!(&**hi > key_ref); } Ok(leaf.get(key_ref).cloned()) } /// Insert a key to a new value, returning the last value if it /// was set. /// /// # Examples /// /// ``` /// # fn main() -> Result<(), Box> { /// # let config = sled::Config::tmp().unwrap(); /// # let db: sled::Db<1024> = config.open()?; /// assert_eq!(db.insert(&[1, 2, 3], vec![0]).unwrap(), None); /// assert_eq!(db.insert(&[1, 2, 3], vec![1]).unwrap(), Some(sled::InlineArray::from(&[0]))); /// # Ok(()) } /// ``` #[doc(alias = "set")] #[doc(alias = "put")] pub fn insert( &self, key: K, value: V, ) -> io::Result> where K: AsRef<[u8]>, V: Into, { self.check_error()?; let key_ref = key.as_ref(); let value_ivec = value.into(); let mut leaf_guard = self.leaf_for_key_mut(key_ref)?; let new_epoch = leaf_guard.epoch(); let leaf = leaf_guard.leaf_write.leaf.as_mut().unwrap(); let ret = leaf.insert(key_ref.into(), value_ivec.clone()); let old_size = ret.as_ref().map(|v| key_ref.len() + v.len()).unwrap_or(0); let new_size = key_ref.len() + value_ivec.len(); if new_size > old_size { leaf.in_memory_size += new_size - old_size; } else { leaf.in_memory_size = leaf.in_memory_size.saturating_sub(old_size - new_size); } let split = leaf.split_if_full(new_epoch, &self.cache, self.collection_id); if split.is_some() || Some(value_ivec) != ret { leaf.mutation_count += 1; leaf.set_dirty_epoch(new_epoch); log::trace!( "F adding node {} to dirty {:?}", leaf_guard.node.object_id.0, new_epoch ); self.cache.install_dirty( new_epoch, leaf_guard.node.object_id, Dirty::NotYetSerialized { collection_id: self.collection_id, node: leaf_guard.node.clone(), low_key: leaf_guard.low_key.clone(), }, ); #[cfg(feature = "for-internal-testing-only")] { self.cache.event_verifier.mark( leaf_guard.node.object_id, new_epoch, event_verifier::State::Dirty, concat!(file!(), ':', line!(), ":insert"), ); } } if let Some((split_key, rhs_node)) = split { assert_eq!(leaf.hi.as_ref().unwrap(), &split_key); log::trace!( "G adding new from split {:?} to dirty {:?}", rhs_node.object_id, new_epoch ); assert_ne!(rhs_node.object_id, leaf_guard.node.object_id); assert!(!split_key.is_empty()); let rhs_object_id = rhs_node.object_id; self.cache.install_dirty( new_epoch, rhs_object_id, Dirty::NotYetSerialized { collection_id: self.collection_id, node: rhs_node.clone(), low_key: split_key.clone(), }, ); #[cfg(feature = "for-internal-testing-only")] { self.cache.event_verifier.mark( rhs_object_id, new_epoch, event_verifier::State::Dirty, concat!(file!(), ':', line!(), ":insert-split"), ); } // NB only make the new node reachable via the index after // we marked it as dirty, as from this point on, any other // thread may cooperatively deserialize it and maybe conflict // with that previous NotYetSerialized marker. self.cache .object_id_index .insert(rhs_node.object_id, rhs_node.clone()); let prev = self.index.insert(split_key, rhs_node); assert!(prev.is_none()); } // this is for clarity, that leaf_guard is held while // inserting into dirty with its guarded epoch drop(leaf_guard); Ok(ret) } /// Delete a value, returning the old value if it existed. /// /// # Examples /// /// ``` /// # fn main() -> Result<(), Box> { /// # let config = sled::Config::tmp().unwrap(); /// # let db: sled::Db<1024> = config.open()?; /// db.insert(&[1], vec![1]); /// assert_eq!(db.remove(&[1]).unwrap(), Some(sled::InlineArray::from(vec![1]))); /// assert!(db.remove(&[1]).unwrap().is_none()); /// # Ok(()) } /// ``` #[doc(alias = "delete")] #[doc(alias = "del")] pub fn remove>( &self, key: K, ) -> io::Result> { self.check_error()?; let key_ref = key.as_ref(); let mut leaf_guard = self.leaf_for_key_mut(key_ref)?; let new_epoch = leaf_guard.epoch(); let leaf = leaf_guard.leaf_write.leaf.as_mut().unwrap(); assert!(leaf.deleted.is_none()); let ret = leaf.remove(key_ref); if ret.is_some() { leaf.mutation_count += 1; leaf.set_dirty_epoch(new_epoch); log::trace!( "H adding node {} to dirty {:?}", leaf_guard.node.object_id.0, new_epoch ); self.cache.install_dirty( new_epoch, leaf_guard.node.object_id, Dirty::NotYetSerialized { collection_id: self.collection_id, low_key: leaf_guard.low_key.clone(), node: leaf_guard.node.clone(), }, ); #[cfg(feature = "for-internal-testing-only")] { self.cache.event_verifier.mark( leaf_guard.node.object_id, new_epoch, event_verifier::State::Dirty, concat!(file!(), ':', line!(), ":remove"), ); } if cfg!(not(feature = "monotonic-behavior")) && leaf.is_empty() && leaf.hi.is_some() { self.merge_leaf_into_right_sibling(leaf_guard)?; } } Ok(ret) } /// Compare and swap. Capable of unique creation, conditional modification, /// or deletion. If old is `None`, this will only set the value if it /// doesn't exist yet. If new is `None`, will delete the value if old is /// correct. If both old and new are `Some`, will modify the value if /// old is correct. /// /// It returns `Ok(Ok(CompareAndSwapSuccess { new_value, previous_value }))` if operation finishes successfully. /// /// If it fails it returns: /// - `Ok(Err(CompareAndSwapError{ current, proposed }))` if no IO /// error was encountered but the operation /// failed to specify the correct current value. `CompareAndSwapError` contains /// current and proposed values. /// - `Err(io::Error)` if there was a high-level IO problem that prevented /// the operation from logically progressing. This is usually fatal and /// will prevent future requests from functioning, and requires the /// administrator to fix the system issue before restarting. /// /// # Examples /// /// ``` /// # fn main() -> Result<(), Box> { /// # let config = sled::Config::tmp().unwrap(); /// # let db: sled::Db<1024> = config.open()?; /// // unique creation /// assert!( /// db.compare_and_swap(&[1], None as Option<&[u8]>, Some(&[10])).unwrap().is_ok(), /// ); /// /// // conditional modification /// assert!( /// db.compare_and_swap(&[1], Some(&[10]), Some(&[20])).unwrap().is_ok(), /// ); /// /// // failed conditional modification -- the current value is returned in /// // the error variant /// let operation = db.compare_and_swap(&[1], Some(&[30]), Some(&[40])); /// assert!(operation.is_ok()); // the operation succeeded /// let modification = operation.unwrap(); /// assert!(modification.is_err()); /// let actual_value = modification.unwrap_err(); /// assert_eq!(actual_value.current.map(|ivec| ivec.to_vec()), Some(vec![20])); /// /// // conditional deletion /// assert!( /// db.compare_and_swap(&[1], Some(&[20]), None as Option<&[u8]>).unwrap().is_ok(), /// ); /// assert!(db.get(&[1]).unwrap().is_none()); /// # Ok(()) } /// ``` #[doc(alias = "cas")] #[doc(alias = "tas")] #[doc(alias = "test_and_swap")] #[doc(alias = "compare_and_set")] pub fn compare_and_swap( &self, key: K, old: Option, new: Option, ) -> CompareAndSwapResult where K: AsRef<[u8]>, OV: AsRef<[u8]>, NV: Into, { self.check_error()?; let key_ref = key.as_ref(); let mut leaf_guard = self.leaf_for_key_mut(key_ref)?; let new_epoch = leaf_guard.epoch(); let proposed: Option = new.map(Into::into); let leaf = leaf_guard.leaf_write.leaf.as_mut().unwrap(); let current = leaf.get(key_ref).cloned(); let previous_matches = match (old, ¤t) { (None, None) => true, (Some(conditional), Some(current)) if conditional.as_ref() == current.as_ref() => { true } _ => false, }; let ret = if previous_matches { if let Some(ref new_value) = proposed { leaf.insert(key_ref.into(), new_value.clone()) } else { leaf.remove(key_ref) }; Ok(CompareAndSwapSuccess { new_value: proposed, previous_value: current, }) } else { Err(CompareAndSwapError { current, proposed }) }; let split = leaf.split_if_full(new_epoch, &self.cache, self.collection_id); let split_happened = split.is_some(); if split_happened || ret.is_ok() { leaf.mutation_count += 1; leaf.set_dirty_epoch(new_epoch); log::trace!( "A adding node {} to dirty {:?}", leaf_guard.node.object_id.0, new_epoch ); self.cache.install_dirty( new_epoch, leaf_guard.node.object_id, Dirty::NotYetSerialized { collection_id: self.collection_id, node: leaf_guard.node.clone(), low_key: leaf_guard.low_key.clone(), }, ); #[cfg(feature = "for-internal-testing-only")] { self.cache.event_verifier.mark( leaf_guard.node.object_id, new_epoch, event_verifier::State::Dirty, concat!(file!(), ':', line!(), ":cas"), ); } } if let Some((split_key, rhs_node)) = split { log::trace!( "B adding new from split {:?} to dirty {:?}", rhs_node.object_id, new_epoch ); self.cache.install_dirty( new_epoch, rhs_node.object_id, Dirty::NotYetSerialized { collection_id: self.collection_id, node: rhs_node.clone(), low_key: split_key.clone(), }, ); #[cfg(feature = "for-internal-testing-only")] { self.cache.event_verifier.mark( rhs_node.object_id, new_epoch, event_verifier::State::Dirty, concat!(file!(), ':', line!(), "cas-split"), ); } // NB only make the new node reachable via the index after // we marked it as dirty, as from this point on, any other // thread may cooperatively deserialize it and maybe conflict // with that previous NotYetSerialized marker. self.cache .object_id_index .insert(rhs_node.object_id, rhs_node.clone()); let prev = self.index.insert(split_key, rhs_node); assert!(prev.is_none()); } if cfg!(not(feature = "monotonic-behavior")) && leaf.is_empty() && leaf.hi.is_some() { assert!(!split_happened); self.merge_leaf_into_right_sibling(leaf_guard)?; } Ok(ret) } /// Fetch the value, apply a function to it and return the result. /// /// # Note /// /// This may call the function multiple times if the value has been /// changed from other threads in the meantime. /// /// # Examples /// /// ``` /// # fn main() -> Result<(), Box> { /// use sled::{Config, InlineArray}; /// /// let config = Config::tmp().unwrap(); /// let db: sled::Db<1024> = config.open()?; /// /// fn u64_to_ivec(number: u64) -> InlineArray { /// InlineArray::from(number.to_be_bytes().to_vec()) /// } /// /// let zero = u64_to_ivec(0); /// let one = u64_to_ivec(1); /// let two = u64_to_ivec(2); /// let three = u64_to_ivec(3); /// /// fn increment(old: Option<&[u8]>) -> Option> { /// let number = match old { /// Some(bytes) => { /// let array: [u8; 8] = bytes.try_into().unwrap(); /// let number = u64::from_be_bytes(array); /// number + 1 /// } /// None => 0, /// }; /// /// Some(number.to_be_bytes().to_vec()) /// } /// /// assert_eq!(db.update_and_fetch("counter", increment).unwrap(), Some(zero)); /// assert_eq!(db.update_and_fetch("counter", increment).unwrap(), Some(one)); /// assert_eq!(db.update_and_fetch("counter", increment).unwrap(), Some(two)); /// assert_eq!(db.update_and_fetch("counter", increment).unwrap(), Some(three)); /// # Ok(()) } /// ``` pub fn update_and_fetch( &self, key: K, mut f: F, ) -> io::Result> where K: AsRef<[u8]>, F: FnMut(Option<&[u8]>) -> Option, V: Into, { let key_ref = key.as_ref(); let mut current = self.get(key_ref)?; loop { let tmp = current.as_ref().map(AsRef::as_ref); let next = f(tmp).map(Into::into); match self.compare_and_swap::<_, _, InlineArray>( key_ref, tmp, next.clone(), )? { Ok(_) => return Ok(next), Err(CompareAndSwapError { current: cur, .. }) => { current = cur; } } } } /// Fetch the value, apply a function to it and return the previous value. /// /// # Note /// /// This may call the function multiple times if the value has been /// changed from other threads in the meantime. /// /// # Examples /// /// ``` /// # fn main() -> Result<(), Box> { /// use sled::{Config, InlineArray}; /// /// let config = Config::tmp().unwrap(); /// let db: sled::Db<1024> = config.open()?; /// /// fn u64_to_ivec(number: u64) -> InlineArray { /// InlineArray::from(number.to_be_bytes().to_vec()) /// } /// /// let zero = u64_to_ivec(0); /// let one = u64_to_ivec(1); /// let two = u64_to_ivec(2); /// /// fn increment(old: Option<&[u8]>) -> Option> { /// let number = match old { /// Some(bytes) => { /// let array: [u8; 8] = bytes.try_into().unwrap(); /// let number = u64::from_be_bytes(array); /// number + 1 /// } /// None => 0, /// }; /// /// Some(number.to_be_bytes().to_vec()) /// } /// /// assert_eq!(db.fetch_and_update("counter", increment).unwrap(), None); /// assert_eq!(db.fetch_and_update("counter", increment).unwrap(), Some(zero)); /// assert_eq!(db.fetch_and_update("counter", increment).unwrap(), Some(one)); /// assert_eq!(db.fetch_and_update("counter", increment).unwrap(), Some(two)); /// # Ok(()) } /// ``` pub fn fetch_and_update( &self, key: K, mut f: F, ) -> io::Result> where K: AsRef<[u8]>, F: FnMut(Option<&[u8]>) -> Option, V: Into, { let key_ref = key.as_ref(); let mut current = self.get(key_ref)?; loop { let tmp = current.as_ref().map(AsRef::as_ref); let next = f(tmp); match self.compare_and_swap(key_ref, tmp, next)? { Ok(_) => return Ok(current), Err(CompareAndSwapError { current: cur, .. }) => { current = cur; } } } } pub fn iter(&self) -> Iter { Iter { prefetched: VecDeque::new(), prefetched_back: VecDeque::new(), next_fetch: Some(InlineArray::MIN), next_back_last_lo: None, next_calls: 0, next_back_calls: 0, inner: self.clone(), bounds: (Bound::Unbounded, Bound::Unbounded), } } pub fn range(&self, range: R) -> Iter where K: AsRef<[u8]>, R: RangeBounds, { let start: Bound = map_bound(range.start_bound(), |b| InlineArray::from(b.as_ref())); let end: Bound = map_bound(range.end_bound(), |b| InlineArray::from(b.as_ref())); let next_fetch = Some(match &start { Bound::Included(b) | Bound::Excluded(b) => b.clone(), Bound::Unbounded => InlineArray::MIN, }); Iter { prefetched: VecDeque::new(), prefetched_back: VecDeque::new(), next_fetch, next_back_last_lo: None, next_calls: 0, next_back_calls: 0, inner: self.clone(), bounds: (start, end), } } /// Create a new batched update that is applied /// atomically. Readers will atomically see all updates /// at an atomic instant, and if the database crashes, /// either 0% or 100% of the full batch will be recovered, /// but never a partial batch. If a `flush` operation succeeds /// after this, it is guaranteed that 100% of the batch will be /// visible, unless later concurrent updates changed the values /// before the flush. /// /// # Examples /// /// ``` /// # fn main() -> Result<(), Box> { /// # let _ = std::fs::remove_dir_all("batch_doctest"); /// # let db: sled::Db<1024> = sled::open("batch_doctest")?; /// db.insert("key_0", "val_0")?; /// /// let mut batch = sled::Batch::default(); /// batch.insert("key_a", "val_a"); /// batch.insert("key_b", "val_b"); /// batch.insert("key_c", "val_c"); /// batch.remove("key_0"); /// /// db.apply_batch(batch)?; /// // key_0 no longer exists, and key_a, key_b, and key_c /// // now do exist. /// # let _ = std::fs::remove_dir_all("batch_doctest"); /// # Ok(()) } /// ``` pub fn apply_batch(&self, batch: Batch) -> io::Result<()> { // NB: we rely on lexicographic lock acquisition // by iterating over the batch's BTreeMap to avoid // deadlocks during 2PL let mut acquired_locks: BTreeMap< InlineArray, ( ArcRwLockWriteGuard>, Object, ), > = BTreeMap::new(); // Phase 1: lock acquisition let mut last: Option<( InlineArray, ArcRwLockWriteGuard>, Object, )> = None; for key in batch.writes.keys() { if let Some((_lo, w, _id)) = &last { let leaf = w.leaf.as_ref().unwrap(); assert!(&leaf.lo <= key); if let Some(hi) = &leaf.hi { if hi <= key { let (lo, w, n) = last.take().unwrap(); acquired_locks.insert(lo, (w, n)); } } } if last.is_none() { // TODO evaluate whether this is correct, as page_in performs // cache maintenance internally if it over/undershoots due to // concurrent modifications. last = Some(self.page_in(key, self.cache.current_flush_epoch())?); } } if let Some((lo, w, id)) = last.take() { acquired_locks.insert(lo, (w, id)); } // NB: add the flush epoch at the end of the lock acquisition // process when all locks have been acquired, to avoid situations // where a leaf is already dirty with an epoch "from the future". let flush_epoch_guard = self.cache.check_into_flush_epoch(); let new_epoch = flush_epoch_guard.epoch(); // Flush any leaves that are dirty from a previous flush epoch // before performing operations. for (write, node) in acquired_locks.values_mut() { let leaf = write.leaf.as_mut().unwrap(); if let Some(old_flush_epoch) = leaf.dirty_flush_epoch { if old_flush_epoch == new_epoch { // no need to cooperatively flush continue; } assert!(old_flush_epoch < new_epoch); log::trace!( "cooperatively flushing {:?} with dirty {:?} after checking into {:?}", node.object_id, old_flush_epoch, new_epoch ); self.cooperatively_serialize_leaf(node.object_id, &mut *leaf); } } let mut splits: Vec<(InlineArray, Object)> = vec![]; let mut merges: BTreeMap> = BTreeMap::new(); // Insert and split when full for (key, value_opt) in batch.writes { let range = ..=&key; let (lo, (w, object)) = acquired_locks .range_mut::(range) .next_back() .unwrap(); let leaf = w.leaf.as_mut().unwrap(); assert_eq!(lo, &leaf.lo); assert!(leaf.lo <= key); if let Some(hi) = &leaf.hi { assert!(hi > &key); } if let Some(value) = value_opt { leaf.insert(key, value); merges.remove(lo); merges.remove(&leaf.lo); if let Some((split_key, rhs_node)) = leaf.split_if_full( new_epoch, &self.cache, self.collection_id, ) { #[cfg(feature = "for-internal-testing-only")] let _b1 = track_blocks(); let write = rhs_node.inner.write_arc(); assert!(write.leaf.is_some()); splits.push((split_key.clone(), rhs_node.clone())); acquired_locks.insert(split_key, (write, rhs_node)); } } else { leaf.remove(&key); if leaf.is_empty() { assert_eq!(leaf.lo, lo); merges.insert(leaf.lo.clone(), object.clone()); } } } // Make splits globally visible for (split_key, rhs_node) in splits { self.cache .object_id_index .insert(rhs_node.object_id, rhs_node.clone()); self.index.insert(split_key, rhs_node); } // Add all written leaves to dirty and prepare to mark cache accesses let mut cache_accesses = Vec::with_capacity(acquired_locks.len()); for (low_key, (write, node)) in &mut acquired_locks { let leaf = write.leaf.as_mut().unwrap(); leaf.set_dirty_epoch(new_epoch); leaf.mutation_count += 1; cache_accesses.push((node.object_id, leaf.in_memory_size)); self.cache.install_dirty( new_epoch, node.object_id, Dirty::NotYetSerialized { collection_id: self.collection_id, node: node.clone(), low_key: low_key.clone(), }, ); #[cfg(feature = "for-internal-testing-only")] { self.cache.event_verifier.mark( node.object_id, new_epoch, event_verifier::State::Dirty, concat!(file!(), ':', line!(), ":apply-batch"), ); } } // Drop locks drop(acquired_locks); // Perform cache maintenance for (object_id, size) in cache_accesses { self.cache.mark_access_and_evict(object_id, size, new_epoch)?; } Ok(()) } /// Returns `true` if the `Tree` contains a value for /// the specified key. /// /// # Examples /// /// ``` /// # fn main() -> Result<(), Box> { /// # let config = sled::Config::tmp().unwrap(); /// # let db: sled::Db<1024> = config.open()?; /// db.insert(&[0], vec![0])?; /// assert!(db.contains_key(&[0])?); /// assert!(!db.contains_key(&[1])?); /// # Ok(()) } /// ``` pub fn contains_key>(&self, key: K) -> io::Result { self.get(key).map(|v| v.is_some()) } /// Retrieve the key and value before the provided key, /// if one exists. /// /// # Note /// The order follows the Ord implementation for `Vec`: /// /// `[] < [0] < [255] < [255, 0] < [255, 255] ...` /// /// To retain the ordering of numerical types use big endian reprensentation /// /// # Examples /// /// ``` /// # fn main() -> Result<(), Box> { /// use sled::InlineArray; /// # let config = sled::Config::tmp().unwrap(); /// # let db: sled::Db<1024> = config.open()?; /// for i in 0..10 { /// db.insert(&[i], vec![i]) /// .expect("should write successfully"); /// } /// /// assert!(db.get_lt(&[]).unwrap().is_none()); /// assert!(db.get_lt(&[0]).unwrap().is_none()); /// assert_eq!( /// db.get_lt(&[1]).unwrap(), /// Some((InlineArray::from(&[0]), InlineArray::from(&[0]))) /// ); /// assert_eq!( /// db.get_lt(&[9]).unwrap(), /// Some((InlineArray::from(&[8]), InlineArray::from(&[8]))) /// ); /// assert_eq!( /// db.get_lt(&[10]).unwrap(), /// Some((InlineArray::from(&[9]), InlineArray::from(&[9]))) /// ); /// assert_eq!( /// db.get_lt(&[255]).unwrap(), /// Some((InlineArray::from(&[9]), InlineArray::from(&[9]))) /// ); /// # Ok(()) } /// ``` pub fn get_lt( &self, key: K, ) -> io::Result> where K: AsRef<[u8]>, { self.range(..key).next_back().transpose() } /// Retrieve the next key and value from the `Tree` after the /// provided key. /// /// # Note /// The order follows the Ord implementation for `Vec`: /// /// `[] < [0] < [255] < [255, 0] < [255, 255] ...` /// /// To retain the ordering of numerical types use big endian reprensentation /// /// # Examples /// /// ``` /// # fn main() -> Result<(), Box> { /// use sled::InlineArray; /// # let config = sled::Config::tmp().unwrap(); /// # let db: sled::Db<1024> = config.open()?; /// for i in 0..10 { /// db.insert(&[i], vec![i])?; /// } /// /// assert_eq!( /// db.get_gt(&[]).unwrap(), /// Some((InlineArray::from(&[0]), InlineArray::from(&[0]))) /// ); /// assert_eq!( /// db.get_gt(&[0]).unwrap(), /// Some((InlineArray::from(&[1]), InlineArray::from(&[1]))) /// ); /// assert_eq!( /// db.get_gt(&[1]).unwrap(), /// Some((InlineArray::from(&[2]), InlineArray::from(&[2]))) /// ); /// assert_eq!( /// db.get_gt(&[8]).unwrap(), /// Some((InlineArray::from(&[9]), InlineArray::from(&[9]))) /// ); /// assert!(db.get_gt(&[9]).unwrap().is_none()); /// /// db.insert(500u16.to_be_bytes(), vec![10]); /// assert_eq!( /// db.get_gt(&499u16.to_be_bytes()).unwrap(), /// Some((InlineArray::from(&500u16.to_be_bytes()), InlineArray::from(&[10]))) /// ); /// # Ok(()) } /// ``` pub fn get_gt( &self, key: K, ) -> io::Result> where K: AsRef<[u8]>, { self.range((ops::Bound::Excluded(key), ops::Bound::Unbounded)) .next() .transpose() } /// Create an iterator over tuples of keys and values /// where all keys start with the given prefix. /// /// # Examples /// /// ``` /// # fn main() -> Result<(), Box> { /// # let config = sled::Config::tmp().unwrap(); /// # let db: sled::Db<1024> = config.open()?; /// use sled::InlineArray; /// db.insert(&[0, 0, 0], vec![0, 0, 0])?; /// db.insert(&[0, 0, 1], vec![0, 0, 1])?; /// db.insert(&[0, 0, 2], vec![0, 0, 2])?; /// db.insert(&[0, 0, 3], vec![0, 0, 3])?; /// db.insert(&[0, 1, 0], vec![0, 1, 0])?; /// db.insert(&[0, 1, 1], vec![0, 1, 1])?; /// /// let prefix: &[u8] = &[0, 0]; /// let mut r = db.scan_prefix(prefix); /// assert_eq!( /// r.next().unwrap().unwrap(), /// (InlineArray::from(&[0, 0, 0]), InlineArray::from(&[0, 0, 0])) /// ); /// assert_eq!( /// r.next().unwrap().unwrap(), /// (InlineArray::from(&[0, 0, 1]), InlineArray::from(&[0, 0, 1])) /// ); /// assert_eq!( /// r.next().unwrap().unwrap(), /// (InlineArray::from(&[0, 0, 2]), InlineArray::from(&[0, 0, 2])) /// ); /// assert_eq!( /// r.next().unwrap().unwrap(), /// (InlineArray::from(&[0, 0, 3]), InlineArray::from(&[0, 0, 3])) /// ); /// assert!(r.next().is_none()); /// # Ok(()) } /// ``` pub fn scan_prefix

(&self, prefix: P) -> Iter where P: AsRef<[u8]>, { let prefix_ref = prefix.as_ref(); let mut upper = prefix_ref.to_vec(); while let Some(last) = upper.pop() { if last < u8::MAX { upper.push(last + 1); return self.range(prefix_ref..&upper); } } self.range(prefix..) } /// Returns the first key and value in the `Tree`, or /// `None` if the `Tree` is empty. pub fn first(&self) -> io::Result> { self.iter().next().transpose() } /// Returns the last key and value in the `Tree`, or /// `None` if the `Tree` is empty. pub fn last(&self) -> io::Result> { self.iter().next_back().transpose() } /// Atomically removes the maximum item in the `Tree` instance. /// /// # Examples /// /// ``` /// # fn main() -> Result<(), Box> { /// # let config = sled::Config::tmp().unwrap(); /// # let db: sled::Db<1024> = config.open()?; /// db.insert(&[0], vec![0])?; /// db.insert(&[1], vec![10])?; /// db.insert(&[2], vec![20])?; /// db.insert(&[3], vec![30])?; /// db.insert(&[4], vec![40])?; /// db.insert(&[5], vec![50])?; /// /// assert_eq!(&db.pop_last()?.unwrap().0, &[5]); /// assert_eq!(&db.pop_last()?.unwrap().0, &[4]); /// assert_eq!(&db.pop_last()?.unwrap().0, &[3]); /// assert_eq!(&db.pop_last()?.unwrap().0, &[2]); /// assert_eq!(&db.pop_last()?.unwrap().0, &[1]); /// assert_eq!(&db.pop_last()?.unwrap().0, &[0]); /// assert_eq!(db.pop_last()?, None); /// # Ok(()) } /// ``` pub fn pop_last(&self) -> io::Result> { loop { if let Some(first_res) = self.iter().next_back() { let first = first_res?; if self .compare_and_swap::<_, _, &[u8]>( &first.0, Some(&first.1), None, )? .is_ok() { log::trace!("pop_last removed item {:?}", first); return Ok(Some(first)); } // try again } else { log::trace!("pop_last removed nothing from empty tree"); return Ok(None); } } } /// Pops the last kv pair in the provided range, or returns `Ok(None)` if nothing /// exists within that range. /// /// # Panics /// /// This will panic if the provided range's end_bound() == Bound::Excluded(K::MIN). /// /// # Examples /// /// ``` /// # fn main() -> Result<(), Box> { /// # let config = sled::Config::tmp().unwrap(); /// # let db: sled::Db<1024> = config.open()?; /// /// let data = vec![ /// (b"key 1", b"value 1"), /// (b"key 2", b"value 2"), /// (b"key 3", b"value 3") /// ]; /// /// for (k, v) in data { /// db.insert(k, v).unwrap(); /// } /// /// let r1 = db.pop_last_in_range(b"key 1".as_ref()..=b"key 3").unwrap(); /// assert_eq!(Some((b"key 3".into(), b"value 3".into())), r1); /// /// let r2 = db.pop_last_in_range(b"key 1".as_ref()..b"key 3").unwrap(); /// assert_eq!(Some((b"key 2".into(), b"value 2".into())), r2); /// /// let r3 = db.pop_last_in_range(b"key 4".as_ref()..).unwrap(); /// assert!(r3.is_none()); /// /// let r4 = db.pop_last_in_range(b"key 2".as_ref()..=b"key 3").unwrap(); /// assert!(r4.is_none()); /// /// let r5 = db.pop_last_in_range(b"key 0".as_ref()..=b"key 3").unwrap(); /// assert_eq!(Some((b"key 1".into(), b"value 1".into())), r5); /// /// let r6 = db.pop_last_in_range(b"key 0".as_ref()..=b"key 3").unwrap(); /// assert!(r6.is_none()); /// # Ok (()) } /// ``` pub fn pop_last_in_range( &self, range: R, ) -> io::Result> where K: AsRef<[u8]>, R: Clone + RangeBounds, { loop { let mut r = self.range(range.clone()); let (k, v) = if let Some(kv_res) = r.next_back() { kv_res? } else { return Ok(None); }; if self .compare_and_swap(&k, Some(&v), None as Option)? .is_ok() { return Ok(Some((k, v))); } } } /// Atomically removes the minimum item in the `Tree` instance. /// /// # Examples /// /// ``` /// # fn main() -> Result<(), Box> { /// # let config = sled::Config::tmp().unwrap(); /// # let db: sled::Db<1024> = config.open()?; /// db.insert(&[0], vec![0])?; /// db.insert(&[1], vec![10])?; /// db.insert(&[2], vec![20])?; /// db.insert(&[3], vec![30])?; /// db.insert(&[4], vec![40])?; /// db.insert(&[5], vec![50])?; /// /// assert_eq!(&db.pop_first()?.unwrap().0, &[0]); /// assert_eq!(&db.pop_first()?.unwrap().0, &[1]); /// assert_eq!(&db.pop_first()?.unwrap().0, &[2]); /// assert_eq!(&db.pop_first()?.unwrap().0, &[3]); /// assert_eq!(&db.pop_first()?.unwrap().0, &[4]); /// assert_eq!(&db.pop_first()?.unwrap().0, &[5]); /// assert_eq!(db.pop_first()?, None); /// # Ok(()) } /// ``` pub fn pop_first(&self) -> io::Result> { loop { if let Some(first_res) = self.iter().next() { let first = first_res?; if self .compare_and_swap::<_, _, &[u8]>( &first.0, Some(&first.1), None, )? .is_ok() { log::trace!("pop_first removed item {:?}", first); return Ok(Some(first)); } // try again } else { log::trace!("pop_first removed nothing from empty tree"); return Ok(None); } } } /// Pops the first kv pair in the provided range, or returns `Ok(None)` if nothing /// exists within that range. /// /// # Panics /// /// This will panic if the provided range's end_bound() == Bound::Excluded(K::MIN). /// /// # Examples /// /// ``` /// # fn main() -> Result<(), Box> { /// # let config = sled::Config::tmp().unwrap(); /// # let db: sled::Db<1024> = config.open()?; /// /// let data = vec![ /// (b"key 1", b"value 1"), /// (b"key 2", b"value 2"), /// (b"key 3", b"value 3") /// ]; /// /// for (k, v) in data { /// db.insert(k, v).unwrap(); /// } /// /// let r1 = db.pop_first_in_range("key 1".as_ref()..="key 3").unwrap(); /// assert_eq!(Some((b"key 1".into(), b"value 1".into())), r1); /// /// let r2 = db.pop_first_in_range("key 1".as_ref().."key 3").unwrap(); /// assert_eq!(Some((b"key 2".into(), b"value 2".into())), r2); /// /// let r3_res: std::io::Result> = db.range(b"key 4".as_ref()..).collect(); /// let r3: Vec<_> = r3_res.unwrap(); /// assert!(r3.is_empty()); /// /// let r4 = db.pop_first_in_range("key 2".as_ref()..="key 3").unwrap(); /// assert_eq!(Some((b"key 3".into(), b"value 3".into())), r4); /// # Ok (()) } /// ``` pub fn pop_first_in_range( &self, range: R, ) -> io::Result> where K: AsRef<[u8]>, R: Clone + RangeBounds, { loop { let mut r = self.range(range.clone()); let (k, v) = if let Some(kv_res) = r.next() { kv_res? } else { return Ok(None); }; if self .compare_and_swap(&k, Some(&v), None as Option)? .is_ok() { return Ok(Some((k, v))); } } } /// Returns the number of elements in this tree. /// /// Beware: performs a full O(n) scan under the hood. /// /// # Examples /// /// ``` /// # fn main() -> Result<(), Box> { /// # let config = sled::Config::tmp().unwrap(); /// # let db: sled::Db<1024> = config.open()?; /// db.insert(b"a", vec![0]); /// db.insert(b"b", vec![1]); /// assert_eq!(db.len().unwrap(), 2); /// # Ok(()) } /// ``` pub fn len(&self) -> io::Result { let mut count = 0; for item_res in self.iter() { let _item = item_res?; count += 1; } Ok(count) } /// Returns `true` if the `Tree` contains no elements. /// /// This is O(1), as we only need to see if an iterator /// returns anything for the first call to `next()`. pub fn is_empty(&self) -> io::Result { if let Some(res) = self.iter().next() { res?; Ok(false) } else { Ok(true) } } /// Clears the `Tree`, removing all values. /// /// Note that this is not atomic. /// /// Beware: performs a full O(n) scan under the hood. pub fn clear(&self) -> io::Result<()> { for k in self.iter().keys() { let key = k?; let _old = self.remove(key)?; } Ok(()) } /// Returns the CRC32 of all keys and values /// in this Tree. /// /// This is O(N) and locks the underlying tree /// for the duration of the entire scan. pub fn checksum(&self) -> io::Result { let mut hasher = crc32fast::Hasher::new(); for kv_res in self.iter() { let (k, v) = kv_res?; hasher.update(&k); hasher.update(&v); } Ok(hasher.finalize()) } } #[allow(unused)] pub struct Iter { inner: Tree, bounds: (Bound, Bound), next_calls: usize, next_back_calls: usize, next_fetch: Option, next_back_last_lo: Option, prefetched: VecDeque<(InlineArray, InlineArray)>, prefetched_back: VecDeque<(InlineArray, InlineArray)>, } impl Iterator for Iter { type Item = io::Result<(InlineArray, InlineArray)>; fn next(&mut self) -> Option { self.next_calls += 1; while self.prefetched.is_empty() { let search_key = if let Some(last) = &self.next_fetch { last.clone() } else { return None; }; let node = match self.inner.leaf_for_key(&search_key) { Ok(n) => n, Err(e) => return Some(Err(e)), }; let leaf = node.leaf_read.leaf.as_ref().unwrap(); if let Some(leaf_hi) = &leaf.hi { if leaf_hi <= &search_key { // concurrent merge, retry log::trace!("undershot in interator, retrying search"); continue; } } if leaf.lo > search_key { // concurrent successor split, retry log::trace!("overshot in interator, retrying search"); continue; } for (k, v) in leaf.iter() { if self.bounds.contains(&k) && search_key <= k { self.prefetched.push_back((k.clone(), v.clone())); } } self.next_fetch = leaf.hi.clone(); } self.prefetched.pop_front().map(Ok) } } impl DoubleEndedIterator for Iter { fn next_back(&mut self) -> Option { self.next_back_calls += 1; while self.prefetched_back.is_empty() { let search_key: InlineArray = if let Some(last) = &self.next_back_last_lo { if !self.bounds.contains(last) || last == &InlineArray::MIN { return None; } self.inner .index .range::(..last) .next_back() .unwrap() .0 } else { match &self.bounds.1 { Bound::Included(k) => k.clone(), Bound::Excluded(k) if k == &InlineArray::MIN => { InlineArray::MIN } Bound::Excluded(k) => self.inner.index.get_lt(k).unwrap().0, Bound::Unbounded => self.inner.index.last().unwrap().0, } }; let node = match self.inner.leaf_for_key(&search_key) { Ok(n) => n, Err(e) => return Some(Err(e)), }; let leaf = node.leaf_read.leaf.as_ref().unwrap(); if leaf.lo > search_key { // concurrent successor split, retry log::trace!("overshot in reverse interator, retrying search"); continue; } // determine if we undershot our target due to concurrent modifications let undershot = match (&leaf.hi, &self.next_back_last_lo, &self.bounds.1) { (Some(leaf_hi), Some(last_lo), _) => leaf_hi < last_lo, (Some(_leaf_hi), None, Bound::Unbounded) => true, (Some(leaf_hi), None, Bound::Included(bound_key)) => { leaf_hi <= bound_key } (Some(leaf_hi), None, Bound::Excluded(bound_key)) => { leaf_hi < bound_key } (None, _, _) => false, }; if undershot { log::trace!( "undershoot detected in reverse iterator with \ (leaf_hi, next_back_last_lo, self.bounds.1) being {:?}", (&leaf.hi, &self.next_back_last_lo, &self.bounds.1) ); continue; } for (k, v) in leaf.iter() { if self.bounds.contains(&k) { let beneath_last_lo = if let Some(last_lo) = &self.next_back_last_lo { &k < last_lo } else { true }; if beneath_last_lo { self.prefetched_back.push_back((k.clone(), v.clone())); } } } self.next_back_last_lo = Some(leaf.lo.clone()); } self.prefetched_back.pop_back().map(Ok) } } impl Iter { pub fn keys( self, ) -> impl DoubleEndedIterator> { self.into_iter().map(|kv_res| kv_res.map(|(k, _v)| k)) } pub fn values( self, ) -> impl DoubleEndedIterator> { self.into_iter().map(|kv_res| kv_res.map(|(_k, v)| v)) } } impl IntoIterator for &Tree { type Item = io::Result<(InlineArray, InlineArray)>; type IntoIter = Iter; fn into_iter(self) -> Self::IntoIter { self.iter() } } /// A batch of updates that will /// be applied atomically to the /// Tree. /// /// # Examples /// /// ``` /// # fn main() -> Result<(), Box> { /// use sled::{Batch, open}; /// /// # let _ = std::fs::remove_dir_all("batch_db_2"); /// let db: sled::Db<1024> = open("batch_db_2")?; /// db.insert("key_0", "val_0")?; /// /// let mut batch = Batch::default(); /// batch.insert("key_a", "val_a"); /// batch.insert("key_b", "val_b"); /// batch.insert("key_c", "val_c"); /// batch.remove("key_0"); /// /// db.apply_batch(batch)?; /// // key_0 no longer exists, and key_a, key_b, and key_c /// // now do exist. /// # let _ = std::fs::remove_dir_all("batch_db_2"); /// # Ok(()) } /// ``` #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct Batch { pub(crate) writes: std::collections::BTreeMap>, } impl Batch { /// Set a key to a new value pub fn insert(&mut self, key: K, value: V) where K: Into, V: Into, { self.writes.insert(key.into(), Some(value.into())); } /// Remove a key pub fn remove(&mut self, key: K) where K: Into, { self.writes.insert(key.into(), None); } /// Get a value if it is present in the `Batch`. /// `Some(None)` means it's present as a deletion. pub fn get>(&self, k: K) -> Option> { let inner = self.writes.get(k.as_ref())?; Some(inner.as_ref()) } } ================================================ FILE: tests/00_regression.rs ================================================ mod common; mod tree; use std::alloc::{Layout, System}; use tree::{Key, Op::*, prop_tree_matches_btreemap}; #[global_allocator] static ALLOCATOR: ShredAllocator = ShredAllocator; #[derive(Default, Debug, Clone, Copy)] struct ShredAllocator; unsafe impl std::alloc::GlobalAlloc for ShredAllocator { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { unsafe { assert!(layout.size() < 1_000_000_000); let ret = System.alloc(layout); assert_ne!(ret, std::ptr::null_mut()); std::ptr::write_bytes(ret, 0xa1, layout.size()); ret } } unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { unsafe { std::ptr::write_bytes(ptr, 0xde, layout.size()); System.dealloc(ptr, layout) } } } #[allow(dead_code)] const INTENSITY: usize = 10; #[test] #[cfg_attr(miri, ignore)] fn tree_bug_00() { // postmortem: prop_tree_matches_btreemap(vec![Restart], false, 0, 256); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_01() { // postmortem: // this was a bug in the snapshot recovery, where // it led to max_id dropping by 1 after a restart. // postmortem 2: // we were stalling here because we had a new log with stable of // SEG_HEADER_LEN, but when we iterated over it to create a new // snapshot (snapshot every 1 set in Config), we iterated up until // that offset. make_stable requires our stable offset to be >= // the provided one, to deal with 0. prop_tree_matches_btreemap( vec![ Set(Key(vec![32]), 9), Set(Key(vec![195]), 13), Restart, Set(Key(vec![164]), 147), ], true, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_02() { // postmortem: // this was a bug in the way that the `Materializer` // was fed data, possibly out of order, if recover // in the pagecache had to run over log entries // that were later run through the same `Materializer` // then the second time (triggered by a snapshot) // would not pick up on the importance of seeing // the new root set. // portmortem 2: when refactoring iterators, failed // to account for node.hi being empty on the infinity // shard prop_tree_matches_btreemap( vec![ Restart, Set(Key(vec![215]), 121), Restart, Set(Key(vec![216]), 203), Scan(Key(vec![210]), 4), ], true, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_03() { // postmortem: the tree was not persisting and recovering root hoists // postmortem 2: when refactoring the log storage, we failed to restart // log writing in the proper location. prop_tree_matches_btreemap( vec![ Set(Key(vec![113]), 204), Set(Key(vec![119]), 205), Set(Key(vec![166]), 88), Set(Key(vec![23]), 44), Restart, Set(Key(vec![226]), 192), Set(Key(vec![189]), 186), Restart, Scan(Key(vec![198]), 11), ], true, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_04() { // postmortem: pagecache was failing to replace the LogId list // when it encountered a new Update::Compact. // postmortem 2: after refactoring log storage, we were not properly // setting the log tip, and the beginning got clobbered after writing // after a restart. prop_tree_matches_btreemap( vec![ Set(Key(vec![158]), 31), Set(Key(vec![111]), 134), Set(Key(vec![230]), 187), Set(Key(vec![169]), 58), Set(Key(vec![131]), 10), Set(Key(vec![108]), 246), Set(Key(vec![127]), 155), Restart, Set(Key(vec![59]), 119), ], true, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_05() { // postmortem: during recovery, the segment accountant was failing to // properly set the file's tip. prop_tree_matches_btreemap( vec![ Set(Key(vec![231]), 107), Set(Key(vec![251]), 42), Set(Key(vec![80]), 81), Set(Key(vec![178]), 130), Set(Key(vec![150]), 232), Restart, Set(Key(vec![98]), 78), Set(Key(vec![0]), 45), ], true, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_06() { // postmortem: after reusing segments, we were failing to checksum reads // performed while iterating over rewritten segment buffers, and using // former garbage data. fix: use the crc that's there for catching torn // writes with high probability, AND zero out buffers. prop_tree_matches_btreemap( vec![ Set(Key(vec![162]), 8), Set(Key(vec![59]), 192), Set(Key(vec![238]), 83), Set(Key(vec![151]), 231), Restart, Set(Key(vec![30]), 206), Set(Key(vec![150]), 146), Set(Key(vec![18]), 34), ], true, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_07() { // postmortem: the segment accountant was not fully recovered, and thought // that it could reuse a particular segment that wasn't actually empty // yet. prop_tree_matches_btreemap( vec![ Set(Key(vec![135]), 22), Set(Key(vec![41]), 36), Set(Key(vec![101]), 31), Set(Key(vec![111]), 35), Restart, Set(Key(vec![47]), 36), Set(Key(vec![79]), 114), Set(Key(vec![64]), 9), Scan(Key(vec![196]), 25), ], true, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_08() { // postmortem: failed to properly recover the state in the segment // accountant that tracked the previously issued segment. prop_tree_matches_btreemap( vec![ Set(Key(vec![145]), 151), Set(Key(vec![155]), 148), Set(Key(vec![131]), 170), Set(Key(vec![163]), 60), Set(Key(vec![225]), 126), Restart, Set(Key(vec![64]), 237), Set(Key(vec![102]), 205), Restart, ], true, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_09() { // postmortem 1: was failing to load existing snapshots on initialization. // would encounter uninitialized segments at the log tip and overwrite // the first segment (indexed by LSN of 0) in the segment accountant // ordering, skipping over important updates. // // postmortem 2: page size tracking was inconsistent in SA. completely // removed exact size tracking, and went back to simpler pure-page // tenancy model. prop_tree_matches_btreemap( vec![ Set(Key(vec![189]), 36), Set(Key(vec![254]), 194), Set(Key(vec![132]), 50), Set(Key(vec![91]), 221), Set(Key(vec![126]), 6), Set(Key(vec![199]), 183), Set(Key(vec![71]), 125), Scan(Key(vec![67]), 16), Set(Key(vec![190]), 16), Restart, ], true, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_10() { // postmortem: after reusing a segment, but not completely writing a // segment, we were hitting an old LSN and violating an assert, rather // than just ending. prop_tree_matches_btreemap( vec![ Set(Key(vec![152]), 163), Set(Key(vec![105]), 191), Set(Key(vec![207]), 217), Set(Key(vec![128]), 19), Set(Key(vec![106]), 22), Scan(Key(vec![20]), 24), Set(Key(vec![14]), 150), Set(Key(vec![80]), 43), Set(Key(vec![174]), 134), Set(Key(vec![20]), 150), Set(Key(vec![13]), 171), Restart, Scan(Key(vec![240]), 25), Scan(Key(vec![77]), 37), Set(Key(vec![153]), 232), Del(Key(vec![2])), Set(Key(vec![227]), 169), Get(Key(vec![232])), Cas(Key(vec![247]), 151, 70), Set(Key(vec![78]), 52), Get(Key(vec![16])), Del(Key(vec![78])), Cas(Key(vec![201]), 93, 196), Set(Key(vec![172]), 84), ], true, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_11() { // postmortem: a stall was happening because LSNs and LogIds were being // conflated in calls to make_stable. A higher LogId than any LSN was // being created, then passed in. prop_tree_matches_btreemap( vec![ Set(Key(vec![38]), 148), Set(Key(vec![176]), 175), Set(Key(vec![82]), 88), Set(Key(vec![164]), 85), Set(Key(vec![139]), 74), Set(Key(vec![73]), 23), Cas(Key(vec![34]), 67, 151), Set(Key(vec![115]), 133), Set(Key(vec![249]), 138), Restart, Set(Key(vec![243]), 6), ], true, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_12() { // postmortem: was not checking that a log entry's LSN matches its position // as part of detecting tears / partial rewrites. prop_tree_matches_btreemap( vec![ Set(Key(vec![118]), 156), Set(Key(vec![8]), 63), Set(Key(vec![165]), 110), Set(Key(vec![219]), 108), Set(Key(vec![91]), 61), Set(Key(vec![18]), 98), Scan(Key(vec![73]), 6), Set(Key(vec![240]), 108), Cas(Key(vec![71]), 28, 189), Del(Key(vec![199])), Restart, Set(Key(vec![30]), 140), Scan(Key(vec![118]), 13), Get(Key(vec![180])), Cas(Key(vec![115]), 151, 116), Restart, Set(Key(vec![31]), 95), Cas(Key(vec![79]), 153, 225), Set(Key(vec![34]), 161), Get(Key(vec![213])), Set(Key(vec![237]), 215), Del(Key(vec![52])), Set(Key(vec![56]), 78), Scan(Key(vec![141]), 2), Cas(Key(vec![228]), 114, 170), Get(Key(vec![231])), Get(Key(vec![223])), Del(Key(vec![167])), Restart, Scan(Key(vec![240]), 31), Del(Key(vec![54])), Del(Key(vec![2])), Set(Key(vec![117]), 165), Set(Key(vec![223]), 50), Scan(Key(vec![69]), 4), Get(Key(vec![156])), Set(Key(vec![214]), 72), ], true, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_13() { // postmortem: failed root hoists were being improperly recovered before the // following free was done on their page, but we treated the written node as // if it were a successful completed root hoist. prop_tree_matches_btreemap( vec![ Set(Key(vec![42]), 10), Set(Key(vec![137]), 220), Set(Key(vec![183]), 129), Set(Key(vec![91]), 145), Set(Key(vec![126]), 26), Set(Key(vec![255]), 67), Set(Key(vec![69]), 18), Restart, Set(Key(vec![24]), 92), Set(Key(vec![193]), 17), Set(Key(vec![3]), 143), Cas(Key(vec![50]), 13, 84), Restart, Set(Key(vec![191]), 116), Restart, Del(Key(vec![165])), ], true, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_14() { // postmortem: after adding prefix compression, we were not // handling re-inserts and deletions properly prop_tree_matches_btreemap( vec![ Set(Key(vec![107]), 234), Set(Key(vec![7]), 245), Set(Key(vec![40]), 77), Set(Key(vec![171]), 244), Set(Key(vec![173]), 16), Set(Key(vec![171]), 176), Scan(Key(vec![93]), 33), ], true, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_15() { // postmortem: was not sorting keys properly when binary searching for them prop_tree_matches_btreemap( vec![ Set(Key(vec![102]), 165), Set(Key(vec![91]), 191), Set(Key(vec![141]), 228), Set(Key(vec![188]), 124), Del(Key(vec![141])), Scan(Key(vec![101]), 26), ], true, 0, 256, ); } /* #[test] #[cfg_attr(miri, ignore)] fn tree_bug_16() { // postmortem: the test merge function was not properly adding numbers. prop_tree_matches_btreemap( vec![Merge(Key(vec![247]), 162), Scan(Key(vec![209]), 31)], false, 0, 256 ); } */ #[test] #[cfg_attr(miri, ignore)] fn tree_bug_17() { // postmortem: we were creating a copy of a node leaf during iteration // before accidentally putting it into a PinnedValue, despite the // fact that it was not actually part of the node's actual memory! prop_tree_matches_btreemap( vec![ Set(Key(vec![194, 215, 103, 0, 138, 11, 248, 131]), 70), Scan(Key(vec![]), 30), ], false, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_18() { // postmortem: when implementing get_gt and get_lt, there were some // issues with getting order comparisons correct. prop_tree_matches_btreemap( vec![ Set(Key(vec![]), 19), Set(Key(vec![78]), 98), Set(Key(vec![255]), 224), Set(Key(vec![]), 131), Get(Key(vec![255])), GetGt(Key(vec![89])), ], false, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_19() { // postmortem: we were not seeking properly to the next node // when we hit a half-split child and were using get_lt prop_tree_matches_btreemap( vec![ Set(Key(vec![]), 138), Set(Key(vec![68]), 113), Set(Key(vec![155]), 73), Set(Key(vec![50]), 220), Set(Key(vec![]), 247), GetLt(Key(vec![100])), ], false, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_20() { // postmortem: we were not seeking forward during get_gt // if path_for_key reached a leaf that didn't include // a key for our prop_tree_matches_btreemap( vec![ Set(Key(vec![]), 10), Set(Key(vec![56]), 42), Set(Key(vec![138]), 27), Set(Key(vec![155]), 73), Set(Key(vec![]), 251), GetGt(Key(vec![94])), ], false, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_21() { // postmortem: more split woes while implementing get_lt // postmortem 2: failed to properly account for node hi key // being empty in the view predecessor function // postmortem 3: when rewriting Iter, failed to account for // direction of iteration prop_tree_matches_btreemap( vec![ Set(Key(vec![176]), 163), Set(Key(vec![]), 229), Set(Key(vec![169]), 121), Set(Key(vec![]), 58), GetLt(Key(vec![176])), ], false, 0, 256, ); } /* #[test] #[cfg_attr(miri, ignore)] fn tree_bug_22() { // postmortem: inclusivity wasn't being properly flipped off after // the first result during iteration // postmortem 2: failed to properly check bounds while iterating prop_tree_matches_btreemap( vec![ Merge(Key(vec![]), 155), Merge(Key(vec![56]), 251), Scan(Key(vec![]), 2), ], false, 0, 256, ); } */ #[test] #[cfg_attr(miri, ignore)] fn tree_bug_23() { // postmortem: when rewriting CRC handling code, mis-sized the blob crc prop_tree_matches_btreemap( vec![Set(Key(vec![6; 5120]), 92), Restart, Scan(Key(vec![]), 35)], false, 0, 256, ); } /* #[test] #[cfg_attr(miri, ignore)] fn tree_bug_24() { // postmortem: get_gt diverged with the Iter impl prop_tree_matches_btreemap( vec![ Merge(Key(vec![]), 193), Del(Key(vec![])), Del(Key(vec![])), Set(Key(vec![]), 55), Set(Key(vec![]), 212), Merge(Key(vec![]), 236), Del(Key(vec![])), Set(Key(vec![]), 192), Del(Key(vec![])), Set(Key(vec![94]), 115), Merge(Key(vec![62]), 34), GetGt(Key(vec![])), ], false, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_25() { // postmortem: was not accounting for merges when traversing // the frag chain and a Del was encountered prop_tree_matches_btreemap( vec![Del(Key(vec![])), Merge(Key(vec![]), 84), Get(Key(vec![]))], false, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_26() { // postmortem: prop_tree_matches_btreemap( vec![ Merge(Key(vec![]), 194), Merge(Key(vec![62]), 114), Merge(Key(vec![80]), 202), Merge(Key(vec![]), 169), Set(Key(vec![]), 197), Del(Key(vec![])), Del(Key(vec![])), Set(Key(vec![]), 215), Set(Key(vec![]), 164), Merge(Key(vec![]), 150), GetGt(Key(vec![])), GetLt(Key(vec![80])), ], false, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_27() { // postmortem: was not accounting for the fact that deletions reduce the // chances of being able to split successfully. prop_tree_matches_btreemap( vec![ Del(Key(vec![])), Merge( Key(vec![ 74, 117, 68, 37, 89, 16, 84, 130, 133, 78, 74, 59, 44, 109, 34, 5, 36, 74, 131, 100, 79, 86, 87, 107, 87, 27, 1, 85, 53, 112, 89, 75, 67, 78, 58, 121, 0, 105, 8, 117, 79, 40, 94, 123, 83, 72, 78, 23, 23, 35, 50, 77, 59, 75, 54, 92, 89, 12, 27, 48, 64, 21, 42, 97, 45, 28, 122, 13, 4, 32, 51, 25, 26, 18, 65, 12, 54, 104, 106, 80, 75, 91, 111, 9, 5, 130, 43, 40, 3, 72, 0, 58, 92, 64, 112, 97, 75, 130, 11, 135, 19, 107, 40, 17, 25, 49, 48, 119, 82, 54, 35, 113, 91, 68, 12, 118, 123, 62, 108, 88, 67, 43, 33, 119, 132, 124, 1, 62, 133, 110, 25, 62, 129, 117, 117, 107, 123, 94, 127, 80, 0, 116, 101, 9, 9, 54, 134, 70, 66, 79, 50, 124, 115, 85, 42, 120, 24, 15, 81, 100, 72, 71, 40, 58, 22, 6, 34, 54, 69, 110, 18, 74, 111, 80, 52, 90, 44, 4, 29, 84, 95, 21, 25, 10, 10, 60, 18, 78, 23, 21, 114, 92, 96, 17, 127, 53, 86, 2, 60, 104, 8, 132, 44, 115, 6, 25, 80, 46, 12, 20, 44, 67, 136, 127, 50, 55, 70, 41, 90, 16, 10, 44, 32, 24, 106, 13, 104, ]), 219, ), Merge(Key(vec![]), 71), Del(Key(vec![])), Set(Key(vec![0]), 146), Merge(Key(vec![13]), 155), Merge(Key(vec![]), 14), Del(Key(vec![])), Set(Key(vec![]), 150), Set( Key(vec![ 13, 8, 3, 6, 9, 14, 3, 13, 7, 12, 13, 7, 13, 13, 1, 13, 5, 4, 3, 2, 6, 16, 17, 10, 0, 16, 12, 0, 16, 1, 0, 15, 15, 4, 1, 6, 9, 9, 11, 16, 7, 6, 10, 1, 11, 10, 4, 9, 9, 14, 4, 12, 16, 10, 15, 2, 1, 8, 4, ]), 247, ), Del(Key(vec![154])), Del(Key(vec![])), Del(Key(vec![ 0, 24, 24, 31, 40, 23, 10, 30, 16, 41, 30, 23, 14, 25, 21, 19, 18, 7, 17, 41, 11, 5, 14, 42, 11, 22, 4, 8, 4, 38, 33, 31, 3, 30, 40, 22, 40, 39, 5, 40, 1, 41, 11, 26, 25, 33, 12, 38, 4, 35, 30, 42, 19, 26, 23, 22, 39, 18, 29, 4, 1, 24, 14, 38, 0, 36, 27, 11, 27, 34, 16, 15, 38, 0, 20, 37, 22, 31, 12, 26, 16, 4, 22, 25, 4, 34, 4, 33, 37, 28, 18, 4, 41, 15, 8, 16, 27, 3, 20, 26, 40, 31, 15, 15, 17, 15, 5, 13, 22, 37, 7, 13, 35, 14, 6, 28, 21, 26, 13, 35, 1, 10, 8, 34, 23, 27, 29, 8, 14, 42, 36, 31, 34, 12, 31, 24, 5, 8, 11, 36, 29, 24, 38, 8, 12, 18, 22, 36, 21, 28, 11, 24, 0, 41, 37, 39, 42, 25, 13, 41, 27, 8, 24, 22, 30, 17, 2, 4, 20, 33, 5, 24, 33, 6, 29, 5, 0, 17, 9, 20, 26, 15, 23, 22, 16, 23, 16, 1, 20, 0, 28, 16, 34, 30, 19, 5, 36, 40, 28, 6, 39, ])), Merge(Key(vec![]), 50), ], false, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_28() { // postmortem: prop_tree_matches_btreemap( vec![ Del(Key(vec![])), Set(Key(vec![]), 65), Del(Key(vec![])), Del(Key(vec![])), Merge(Key(vec![]), 50), Merge(Key(vec![]), 2), Del(Key(vec![197])), Merge(Key(vec![5]), 146), Set(Key(vec![222]), 224), Merge(Key(vec![149]), 60), Scan(Key(vec![178]), 18), ], false, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_29() { // postmortem: tree merge and split thresholds caused an infinite // loop while performing updates prop_tree_matches_btreemap( vec![ Set(Key(vec![]), 142), Merge( Key(vec![ 45, 47, 6, 67, 16, 12, 62, 35, 69, 80, 49, 61, 29, 82, 9, 47, 25, 78, 47, 64, 29, 74, 45, 0, 37, 44, 21, 82, 55, 44, 31, 60, 86, 18, 45, 67, 55, 21, 35, 46, 25, 51, 5, 32, 33, 36, 1, 81, 28, 28, 79, 76, 80, 89, 80, 62, 8, 85, 50, 15, 4, 11, 76, 72, 73, 47, 30, 50, 85, 67, 84, 13, 82, 84, 78, 70, 42, 83, 8, 7, 50, 77, 85, 37, 47, 82, 86, 46, 30, 27, 5, 39, 70, 26, 59, 16, 6, 34, 56, 40, 40, 67, 16, 61, 63, 56, 64, 31, 15, 81, 84, 19, 61, 66, 3, 7, 40, 56, 13, 40, 64, 50, 88, 47, 88, 50, 63, 65, 79, 62, 1, 44, 59, 27, 12, 60, 3, 36, 89, 45, 18, 4, 68, 48, 61, 30, 48, 26, 84, 49, 3, 74, 51, 53, 30, 57, 50, 35, 74, 59, 30, 73, 19, 30, 82, 78, 3, 5, 62, 17, 48, 29, 67, 52, 45, 61, 74, 52, 29, 61, 63, 11, 89, 76, 34, 8, 50, 75, 42, 12, 5, 55, 0, 59, 44, 68, 26, 76, 37, 50, 53, 73, 53, 76, 57, 40, 30, 52, 0, 41, 21, 8, 79, 79, 38, 37, 50, 56, 43, 9, 85, 21, 60, 64, 13, 54, 60, 83, 1, 2, 37, 75, 42, 0, 83, 81, 80, 87, 12, 15, 75, 55, 41, 59, 9, 80, 66, 27, 65, 26, 48, 29, 37, 38, 9, 76, 31, 39, 35, 22, 73, 59, 28, 33, 35, 63, 78, 17, 22, 82, 12, 60, 49, 26, 54, 19, 60, 29, 39, 37, 10, 50, 12, 19, 29, 1, 74, 12, 5, 38, 49, 41, 19, 88, 3, 27, 77, 81, 72, 42, 71, 86, 82, 11, 79, 40, 35, 26, 35, 64, 4, 33, 87, 31, 84, 81, 74, 31, 49, 0, 29, 73, 14, 55, 78, 21, 23, 20, 83, 48, 89, 88, 62, 64, 73, 7, 20, 70, 81, 64, 3, 79, 38, 75, 13, 40, 29, 82, 40, 14, 66, 56, 54, 52, 37, 14, 67, 8, 37, 1, 5, 73, 14, 35, 63, 48, 46, 22, 84, 71, 2, 60, 63, 88, 14, 15, 69, 88, 2, 43, 57, 43, 52, 18, 78, 75, 75, 74, 13, 35, 50, 35, 17, 13, 64, 82, 55, 32, 14, 57, 35, 77, 65, 22, 40, 27, 39, 80, 23, 20, 41, 50, 48, 22, 84, 37, 59, 45, 64, 10, 3, 69, 56, 24, 4, 25, 76, 65, 47, 52, 64, 88, 3, 23, 37, 16, 56, 69, 71, 27, 87, 65, 74, 23, 82, 41, 60, 78, 75, 22, 51, 15, 57, 80, 46, 73, 7, 1, 36, 64, 0, 56, 83, 74, 62, 73, 81, 68, 71, 63, 31, 5, 23, 11, 15, 39, 2, 10, 23, 18, 74, 3, 43, 25, 68, 54, 11, 21, 14, 58, 10, 73, 0, 66, 28, 73, 25, 40, 55, 56, 33, 81, 67, 43, 35, 65, 38, 21, 48, 81, 4, 77, 68, 51, 38, 36, 49, 43, 33, 51, 28, 43, 60, 71, 78, 48, 49, 76, 21, 0, 72, 0, 32, 78, 12, 87, 5, 80, 62, 40, 85, 26, 70, 58, 56, 78, 7, 53, 30, 16, 22, 12, 23, 37, 83, 45, 33, 41, 83, 78, 87, 44, 0, 65, 51, 3, 8, 72, 38, 14, 24, 64, 77, 45, 5, 1, 7, 27, 82, 7, 6, 70, 25, 67, 22, 8, 30, 76, 41, 11, 14, 1, 65, 85, 60, 80, 0, 30, 31, 79, 43, 89, 33, 84, 22, 7, 67, 45, 39, 74, 75, 12, 61, 19, 71, 66, 83, 57, 38, 45, 21, 18, 37, 54, 36, 14, 54, 63, 81, 12, 7, 10, 39, 16, 40, 10, 7, 81, 45, 12, 22, 20, 29, 85, 40, 41, 72, 79, 58, 50, 41, 59, 64, 41, 32, 56, 35, 8, 60, 17, 14, 89, 17, 7, 48, 6, 35, 9, 34, 54, 6, 44, 87, 76, 50, 1, 67, 70, 15, 8, 4, 45, 67, 86, 32, 69, 3, 88, 85, 72, 66, 21, 89, 11, 77, 1, 50, 75, 56, 41, 74, 6, 4, 51, 65, 39, 50, 45, 56, 3, 19, 80, 86, 55, 48, 81, 17, 3, 89, 7, 9, 63, 58, 80, 39, 34, 85, 55, 71, 41, 55, 8, 63, 38, 51, 47, 49, 83, 2, 73, 22, 39, 18, 45, 77, 56, 80, 54, 13, 23, 81, 54, 15, 48, 57, 83, 71, 41, 32, 64, 1, 9, 46, 27, 16, 21, 7, 28, 55, 17, 71, 68, 17, 74, 46, 38, 84, 3, 12, 71, 63, 16, 23, 48, 12, 29, 28, 5, 21, 61, 14, 77, 66, 62, 57, 18, 30, 63, 14, 41, 37, 30, 73, 16, 12, 74, 8, 82, 67, 53, 10, 5, 37, 36, 39, 52, 37, 72, 76, 21, 35, 40, 42, 55, 47, 50, 41, 19, 40, 86, 26, 54, 23, 74, 46, 66, 59, 80, 26, 81, 61, 80, 88, 55, 40, 30, 45, 7, 46, 21, 3, 20, 46, 63, 18, 9, 34, 67, 9, 19, 52, 53, 29, 69, 78, 65, 39, 71, 40, 38, 57, 80, 27, 34, 30, 27, 55, 8, 65, 31, 37, 33, 25, 39, 46, 9, 83, 6, 27, 28, 61, 9, 21, 58, 21, 10, 69, 24, 5, 31, 32, 44, 26, 84, 73, 73, 9, 64, 26, 21, 85, 12, 39, 81, 38, 49, 24, 35, 3, 88, 15, 15, 76, 64, 70, 9, 30, 51, 26, 16, 70, 60, 15, 7, 54, 36, 32, 9, 10, 18, 66, 19, 25, 77, 46, 51, 51, 14, 41, 56, 65, 41, 87, 26, 10, 2, 73, 2, 71, 26, 56, 10, 68, 15, 53, 10, 43, 15, 22, 45, 2, 15, 16, 69, 80, 83, 18, 22, 70, 77, 52, 48, 24, 17, 40, 56, 22, 17, 3, 36, 46, 37, 41, 22, 0, 41, 45, 14, 15, 73, 18, 42, 34, 5, 87, 6, 2, 7, 58, 3, 86, 87, 7, 79, 88, 33, 30, 48, 3, 66, 27, 34, 58, 48, 71, 40, 1, 46, 84, 32, 63, 79, 0, 21, 71, 1, 59, 39, 77, 51, 14, 20, 58, 83, 19, 0, 2, 2, 57, 73, 79, 42, 59, 33, 50, 15, 11, 48, 25, 14, 39, 36, 88, 71, 28, 45, 15, 59, 39, 60, 78, 18, 18, 45, 50, 29, 66, 86, 5, 76, 85, 55, 17, 28, 8, 39, 75, 33, 9, 73, 71, 59, 56, 57, 86, 6, 75, 26, 43, 68, 34, 82, 88, 76, 17, 86, 63, 2, 38, 63, 13, 44, 8, 25, 0, 63, 54, 73, 52, 3, 72, ]), 9, ), Set(Key(vec![]), 35), Set( Key(vec![ 165, 64, 99, 55, 152, 102, 148, 35, 59, 10, 198, 191, 71, 129, 170, 155, 7, 106, 171, 93, 126, ]), 212, ), Del(Key(vec![])), Merge(Key(vec![]), 177), Merge( Key(vec![ 20, 55, 154, 104, 10, 68, 64, 3, 31, 78, 232, 227, 169, 161, 13, 50, 16, 239, 87, 0, 9, 85, 248, 32, 156, 106, 11, 18, 57, 13, 177, 36, 69, 176, 101, 92, 119, 38, 218, 26, 4, 154, 185, 135, 75, 167, 101, 107, 206, 76, 153, 213, 70, 52, 205, 95, 55, 116, 242, 68, 77, 90, 249, 142, 93, 135, 118, 127, 116, 121, 235, 183, 215, 2, 118, 193, 146, 185, 4, 129, 167, 164, 178, 105, 149, 47, 73, 121, 95, 23, 216, 153, 23, 108, 141, 190, 250, 121, 98, 229, 33, 106, 89, 117, 122, 145, 47, 242, 81, 88, 141, 38, 177, 170, 167, 56, 24, 196, 61, 97, 83, 91, 202, 181, 75, 112, 3, 169, 61, 17, 100, 81, 111, 178, 122, 176, 95, 185, 169, 146, 239, 40, 168, 32, 170, 34, 172, 89, 59, 188, 170, 186, 61, 7, 177, 230, 130, 155, 208, 171, 82, 153, 20, 72, 74, 111, 147, 178, 164, 157, 71, 114, 216, 40, 85, 91, 20, 145, 149, 95, 36, 114, 24, 129, 144, 229, 14, 133, 77, 92, 139, 167, 48, 18, 178, 4, 15, 171, 171, 88, 74, 104, 157, 2, 121, 13, 141, 6, 107, 118, 228, 147, 152, 28, 206, 128, 102, 150, 1, 129, 84, 171, 119, 110, 198, 72, 100, 166, 153, 98, 66, 128, 79, 41, 126, ]), 103, ), Del(Key(vec![])), Merge( Key(vec![ 117, 48, 90, 153, 149, 191, 229, 73, 3, 6, 73, 52, 73, 186, 42, 53, 94, 17, 61, 11, 153, 118, 219, 188, 184, 89, 13, 124, 138, 40, 238, 9, 46, 45, 38, 115, 153, 106, 166, 56, 134, 206, 140, 57, 95, 244, 27, 135, 43, 13, 143, 137, 56, 122, 243, 205, 52, 116, 130, 35, 80, 167, 58, 93, ]), 8, ), Set(Key(vec![145]), 43), GetLt(Key(vec![229])), ], false, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_30() { // postmortem: prop_tree_matches_btreemap( vec![ Merge(Key(vec![]), 241), Set(Key(vec![20]), 146), Merge( Key(vec![ 60, 38, 29, 57, 35, 71, 15, 46, 7, 27, 76, 84, 27, 25, 90, 30, 37, 63, 11, 24, 27, 28, 94, 93, 82, 68, 69, 61, 46, 86, 11, 86, 63, 34, 90, 71, 92, 87, 38, 48, 40, 78, 9, 37, 26, 36, 60, 4, 2, 38, 32, 73, 86, 43, 52, 79, 11, 43, 59, 21, 60, 40, 80, 94, 69, 44, 4, 73, 59, 16, 16, 22, 88, 41, 13, 21, 91, 33, 49, 91, 20, 79, 23, 61, 53, 63, 58, 62, 49, 10, 71, 72, 27, 55, 53, 39, 91, 82, 86, 38, 41, 1, 54, 3, 77, 15, 93, 31, 49, 29, 82, 7, 17, 58, 42, 12, 49, 67, 62, 46, 20, 27, 61, 32, 58, 9, 17, 19, 28, 44, 41, 34, 94, 11, 50, 73, 1, 50, 48, 8, 88, 33, 40, 51, 15, 35, 2, 36, 37, 30, 37, 83, 71, 91, 32, 0, 69, 28, 64, 30, 72, 63, 39, 7, 89, 0, 21, 51, 92, 80, 13, 57, 7, 53, 94, 26, 2, 63, 18, 23, 89, 34, 83, 55, 32, 75, 81, 27, 11, 5, 63, 0, 75, 12, 39, 9, 13, 20, 25, 57, 94, 75, 59, 46, 84, 80, 61, 24, 31, 7, 68, 93, 12, 94, 6, 94, 27, 33, 81, 19, 3, 78, 3, 14, 22, 36, 49, 61, 51, 79, 43, 35, 58, 54, 65, 72, 36, 87, 3, 3, 25, 75, 82, 58, 75, 76, 29, 89, 1, 16, 64, 63, 85, 0, 47, ]), 11, ), Merge(Key(vec![25]), 245), Merge(Key(vec![119]), 152), Scan(Key(vec![]), 31), ], false, 0, 256, ); } */ #[test] #[cfg_attr(miri, ignore)] fn tree_bug_31() { // postmortem: prop_tree_matches_btreemap( vec![ Set(Key(vec![1]), 212), Set(Key(vec![12]), 174), Set(Key(vec![]), 182), Set( Key(vec![ 12, 55, 46, 38, 40, 34, 44, 32, 19, 15, 28, 49, 35, 40, 55, 35, 61, 9, 62, 18, 3, 58, ]), 86, ), Scan(Key(vec![]), -18), ], false, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_32() { // postmortem: the MAX_IVEC that predecessor used in reverse // iteration was setting the first byte to 0 even though we // no longer perform per-key prefix encoding. prop_tree_matches_btreemap( vec![Set(Key(vec![57]), 141), Scan(Key(vec![]), -40)], false, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_33() { // postmortem: the split point was being incorrectly // calculated when using the simplified prefix technique. prop_tree_matches_btreemap( vec![ Set(Key(vec![]), 91), Set(Key(vec![1]), 216), Set(Key(vec![85, 25]), 78), Set(Key(vec![85]), 43), GetLt(Key(vec![])), ], false, 0, 256, ); } /* #[test] #[cfg_attr(miri, ignore)] fn tree_bug_34() { // postmortem: a safety check was too aggressive when // finding predecessors using the new simplified prefix // encoding technique. prop_tree_matches_btreemap( vec![ Set(Key(vec![9, 212]), 100), Set(Key(vec![9]), 63), Set(Key(vec![5]), 100), Merge(Key(vec![]), 16), Set(Key(vec![9, 70]), 188), Scan(Key(vec![]), -40), ], false, 0, 256, ); } */ #[test] #[cfg_attr(miri, ignore)] fn tree_bug_35() { // postmortem: prefix lengths were being incorrectly // handled on splits. prop_tree_matches_btreemap( vec![ Set(Key(vec![207]), 29), Set(Key(vec![192]), 218), Set(Key(vec![121]), 167), Set(Key(vec![189]), 40), Set(Key(vec![85]), 197), Set(Key(vec![185]), 58), Set(Key(vec![84]), 97), Set(Key(vec![23]), 34), Set(Key(vec![47]), 162), Set(Key(vec![39]), 92), Set(Key(vec![46]), 173), Set(Key(vec![33]), 202), Set(Key(vec![8]), 113), Set(Key(vec![17]), 228), Set(Key(vec![8, 49]), 217), Set(Key(vec![6]), 192), Set(Key(vec![5]), 47), Set(Key(vec![]), 5), Set(Key(vec![0]), 103), Set(Key(vec![1]), 230), Set(Key(vec![0, 229]), 117), Set(Key(vec![]), 112), ], false, 0, 256, ); } /* #[test] #[cfg_attr(miri, ignore)] fn tree_bug_36() { // postmortem: suffix truncation caused // regions to be permanently inaccessible // when applied to split points on index // nodes. prop_tree_matches_btreemap( vec![ Set(Key(vec![152]), 65), Set(Key(vec![]), 227), Set(Key(vec![101]), 23), Merge(Key(vec![254]), 97), Set(Key(vec![254, 5]), 207), Scan(Key(vec![]), -30), ], false, 0, 256, ); } */ #[test] #[cfg_attr(miri, ignore)] fn tree_bug_37() { // postmortem: suffix truncation was so // aggressive that it would cut into // the prefix in the lo key sometimes. prop_tree_matches_btreemap( vec![ Set(Key(vec![]), 82), Set(Key(vec![2, 0]), 40), Set(Key(vec![2, 0, 0]), 49), Set(Key(vec![1]), 187), Scan(Key(vec![]), 33), ], false, 0, 256, ); } /* #[test] #[cfg_attr(miri, ignore)] fn tree_bug_38() { // postmortem: Free pages were not being initialized in the // pagecache properly. for _ in 0..10 { prop_tree_matches_btreemap( vec![ Set(Key(vec![193]), 73), Merge(Key(vec![117]), 216), Set(Key(vec![221]), 176), GetLt(Key(vec![123])), Restart, ], false, 0, 256, ); } } */ /* #[test] #[cfg_attr(miri, ignore)] fn tree_bug_39() { // postmortem: for _ in 0..100 { prop_tree_matches_btreemap( vec![ Set( Key(vec![ 67, 48, 34, 254, 61, 189, 196, 127, 26, 185, 244, 63, 60, 63, 246, 194, 243, 177, 218, 210, 153, 126, 124, 47, 160, 242, 157, 2, 51, 34, 88, 41, 44, 65, 58, 211, 245, 74, 192, 101, 222, 68, 196, 250, 127, 231, 102, 177, 246, 105, 190, 144, 113, 148, 71, 72, 149, 246, 38, 95, 106, 42, 83, 65, 84, 73, 148, 34, 95, 88, 57, 232, 219, 227, 74, 14, 5, 124, 106, 57, 244, 50, 81, 93, 145, 111, 40, 190, 127, 227, 17, 242, 165, 194, 171, 60, 6, 255, 176, 143, 131, 164, 217, 18, 123, 19, 246, 183, 29, 0, 6, 39, 175, 57, 134, 166, 231, 47, 254, 158, 163, 178, 78, 240, 108, 157, 72, 135, 34, 236, 103, 192, 109, 31, 2, 72, 128, 242, 4, 113, 109, 224, 120, 61, 169, 226, 131, 210, 33, 181, 91, 91, 197, 223, 127, 26, 94, 158, 55, 57, 3, 184, 15, 30, 2, 222, 39, 29, 12, 42, 14, 166, 176, 28, 13, 246, 11, 186, 8, 247, 113, 253, 102, 227, 68, 111, 227, 238, 54, 150, 11, 57, 155, 4, 75, 179, 17, 172, 42, 22, 199, 44, 242, 211, 0, 39, 243, 221, 114, 86, 145, 22, 226, 108, 32, 248, 42, 49, 191, 112, 1, 69, 101, 112, 251, 243, 252, 83, 140, 132, 165, ]), 250, ), Del(Key(vec![ 11, 77, 168, 37, 181, 169, 239, 146, 240, 211, 7, 115, 197, 119, 46, 80, 240, 92, 221, 108, 208, 247, 221, 129, 108, 13, 36, 21, 93, 11, 243, 103, 188, 39, 126, 77, 29, 32, 206, 175, 199, 245, 71, 96, 221, 7, 68, 64, 45, 78, 68, 193, 73, 13, 60, 13, 28, 167, 147, 7, 90, 11, 206, 44, 84, 243, 3, 77, 122, 87, 7, 125, 184, 6, 178, 59, ])), Merge(Key(vec![176]), 123), Restart, Merge( Key(vec![ 93, 43, 181, 76, 63, 247, 227, 15, 17, 239, 9, 252, 181, 53, 65, 74, 22, 18, 71, 64, 115, 58, 110, 30, 13, 177, 31, 47, 124, 14, 0, 157, 200, 194, 92, 215, 21, 36, 239, 204, 18, 88, 216, 149, 18, 208, 187, 188, 32, 76, 35, 12, 142, 157, 38, 186, 245, 63, 2, 230, 13, 79, 160, 86, 32, 170, 239, 151, 25, 180, 170, 201, 22, 211, 238, 208, 24, 139, 5, 44, 38, 48, 243, 38, 249, 36, 43, 200, 52, 244, 166, 0, 29, 114, 10, 18, 253, 253, 130, 223, 37, 8, 109, 228, 0, 122, 192, 16, 68, 231, 37, 230, 249, 180, 214, 101, 17, ]), 176, ), Set( Key(vec![ 153, 217, 142, 179, 255, 74, 1, 20, 254, 1, 38, 28, 66, 244, 81, 101, 210, 58, 18, 107, 12, 116, 74, 188, 95, 56, 248, 9, 204, 128, 24, 239, 143, 83, 83, 213, 17, 32, 135, 73, 217, 8, 241, 44, 57, 131, 107, 139, 122, 32, 194, 225, 136, 148, 227, 196, 196, 121, 97, 81, 74, ]), 42, ), Set(Key(vec![]), 160), GetLt(Key(vec![ 244, 145, 243, 120, 149, 64, 125, 161, 98, 205, 205, 107, 191, 119, 83, 42, 92, 119, 25, 198, 47, 123, 26, 224, 190, 98, 144, 238, 74, 36, 76, 186, 226, 153, 69, 217, 109, 214, 201, 104, 148, 107, 132, 219, 37, 109, 98, 172, 70, 160, 177, 115, 194, 80, 76, 60, 148, 176, 191, 84, 109, 35, 51, 107, 157, 11, 233, 126, 71, 183, 215, 116, 72, 235, 218, 171, 233, 181, 53, 253, 104, 231, 138, 166, 40, ])), Set( Key(vec![ 37, 160, 29, 162, 43, 212, 2, 100, 236, 24, 2, 82, 58, 38, 81, 137, 89, 55, 164, 83, ]), 64, ), Get(Key(vec![ 15, 53, 101, 33, 156, 199, 212, 82, 2, 64, 136, 70, 235, 72, 170, 188, 180, 200, 109, 231, 6, 13, 30, 70, 4, 132, 133, 101, 82, 187, 78, 241, 157, 49, 156, 3, 17, 167, 216, 209, 7, 174, 112, 186, 170, 189, 85, 99, 119, 52, 39, 38, 151, 108, 203, 42, 63, 255, 216, 234, 34, 2, 80, 168, 122, 70, 20, 11, 220, 106, 49, 110, 165, 170, 149, 163, ])), GetLt(Key(vec![])), Merge(Key(vec![136]), 135), Cas(Key(vec![177]), 159, 209), Cas(Key(vec![101]), 143, 240), Set(Key(vec![226, 62, 34, 63, 172, 96, 162]), 43), Merge( Key(vec![ 48, 182, 144, 255, 137, 100, 2, 139, 69, 111, 159, 133, 234, 147, 118, 231, 155, 74, 73, 98, 58, 36, 35, 21, 50, 42, 71, 25, 200, 5, 4, 198, 158, 41, 88, 75, 153, 254, 248, 213, 0, 89, 43, 160, 58, 206, 88, 107, 57, 208, 119, 34, 80, 166, 112, 13, 241, 46, 172, 115, 179, 42, 59, 200, 225, 125, 65, 18, 173, 77, 27, 129, 228, 68, 53, 175, 61, 230, 27, 136, 131, 171, 64, 79, 125, 149, 52, 80, ]), 105, ), Merge( Key(vec![ 126, 109, 165, 43, 2, 82, 97, 81, 59, 78, 243, 142, 37, 105, 109, 178, 25, 73, 50, 103, 107, 129, 213, 193, 158, 16, 63, 108, 160, 204, 78, 83, 2, 43, 66, 2, 18, 11, 147, 47, 106, 106, 141, 82, 65, 101, 99, 171, 178, 68, 106, 7, 190, 159, 105, 132, 155, 240, 155, 95, 66, 254, 239, 202, 168, 26, 207, 213, 116, 215, 141, 77, 7, 245, 174, 144, 39, 28, ]), 122, ), Del(Key(vec![ 13, 152, 171, 90, 130, 131, 232, 51, 173, 103, 255, 225, 156, 192, 146, 141, 94, 84, 39, 171, 152, 114, 133, 20, 125, 68, 57, 27, 33, 175, 37, 164, 40, ])), Scan(Key(vec![]), -34), Set(Key(vec![]), 85), Merge(Key(vec![112]), 104), Restart, Restart, Del(Key(vec![237])), Set( Key(vec![ 53, 79, 71, 234, 187, 78, 206, 117, 48, 84, 162, 101, 132, 137, 43, 144, 234, 23, 116, 13, 28, 184, 174, 241, 181, 201, 131, 156, 7, 103, 135, 17, 168, 249, 7, 120, 74, 8, 192, 134, 109, 54, 175, 130, 145, 206, 185, 49, 144, 133, 226, 244, 42, 126, 176, 232, 96, 56, 70, 56, 159, 127, 35, 39, 185, 114, 182, 41, 50, 93, 61, ]), 144, ), Merge( Key(vec![ 10, 58, 6, 62, 17, 15, 26, 29, 79, 34, 77, 12, 93, 65, 87, 71, 19, 57, 25, 40, 53, 73, 57, 2, 81, 49, 67, 62, 78, 14, 34, 70, 86, 49, 86, 84, 16, 33, 24, 7, 87, 49, 58, 50, 13, 14, 35, 46, 7, 39, 76, 51, 21, 76, 9, 53, 45, 21, 71, 48, 16, 73, 68, 1, 63, 34, 12, 42, 11, 85, 79, 19, 11, 77, 90, 0, 62, 56, 37, 33, 10, 69, 20, 64, 15, 51, 64, 90, 69, 15, 7, 41, 53, 71, 52, 21, 45, 45, 49, 3, 59, 15, 90, 7, 12, 62, 30, 81, ]), 131, ), Get(Key(vec![ 79, 28, 48, 41, 5, 70, 54, 56, 36, 32, 59, 15, 26, 42, 61, 23, 53, 6, 71, 44, 61, 65, 4, 17, 23, 15, 65, 64, 46, 66, 27, 63, 51, 44, 35, 1, 8, 70, 7, 1, 13, 10, 40, 6, 36, 64, 68, 52, 8, 0, 46, 53, 48, 32, 9, 52, 69, 41, 8, 57, 27, 31, 79, 27, 12, 70, 72, 33, 6, 22, 47, 37, 11, 38, 32, 7, 31, 37, 45, 23, 74, 22, 46, 1, 3, 74, 72, 56, 52, 65, 78, 28, 5, 68, 30, 36, 5, 43, 7, 2, 48, 75, 16, 53, 31, 40, 9, 3, 49, 71, 70, 20, 24, 6, 23, 76, 49, 21, 12, 60, 54, 43, 7, 79, 74, 62, 53, 20, 46, 11, 74, 29, 31, 43, 20, 27, 22, 22, 15, 59, 12, 21, 61, 11, 8, 28, 5, 78, 70, 22, 11, 36, 62, 56, 44, 49, 25, 39, 37, 24, 72, 65, 67, 22, 48, 16, 50, 5, 10, 13, 36, 65, 29, 3, 26, 74, 15, 73, 78, 36, 14, 36, 30, 42, 19, 73, 65, 75, 2, 25, 1, 32, 38, 43, 58, 19, 37, 37, 48, 23, 72, 77, 34, 24, 1, 4, 42, 11, 68, 54, 23, 34, 0, 48, 20, 20, 23, 61, 65, 72, 64, 24, 63, 3, 21, 48, 63, 57, 40, 36, 46, 48, 8, 20, 62, 7, 69, 35, 79, 38, 45, 74, 7, 16, 48, 59, 56, 31, 13, 13, ])), Del(Key(vec![176, 58, 119])), Get(Key(vec![241])), Get(Key(vec![160])), Cas(Key(vec![]), 166, 235), Set( Key(vec![ 64, 83, 151, 149, 100, 93, 5, 18, 91, 58, 84, 156, 127, 108, 99, 168, 54, 51, 169, 185, 174, 101, 178, 148, 28, 91, 25, 138, 14, 133, 170, 97, 138, 180, 157, 131, 174, 22, 91, 108, 59, 165, 52, 28, 17, 175, 44, 95, 112, 38, 141, 46, 124, 49, 116, 55, 39, 109, 73, 181, 104, 86, 81, 150, 95, 149, 69, 110, 110, 102, 22, 62, 180, 60, 87, 127, 127, 136, 12, 139, 109, 165, 34, 181, 158, 156, 102, 38, 6, 149, 183, 69, 129, 98, 161, 175, 82, 51, 47, 93, 136, 16, 118, 65, 152, 139, 8, 30, 10, 100, 47, 13, 47, 179, 87, 19, 109, 78, 116, 20, 111, 89, 28, 0, 86, 39, 139, 7, 111, 40, 145, 155, 107, 45, 36, 90, 143, 154, 135, 36, 13, 98, 61, 150, 65, 128, 16, 52, 100, 128, 11, 5, 49, 143, 56, 78, 48, 62, 86, 50, 86, 41, 153, 53, 139, 89, 164, 33, 136, 83, 182, 53, 132, 144, 177, 105, 104, 55, 9, 174, 30, 65, 76, 33, 163, 172, 80, 169, 175, 54, 165, 173, 109, 24, 70, 25, 158, 135, 76, 130, 76, 9, 56, 20, 13, 133, 33, 168, 160, 153, 43, 80, 58, 56, 171, 28, 97, 122, 162, 32, 164, 11, 112, 177, 63, 47, 25, 0, 66, 87, 169, 118, 173, 27, 154, 79, 72, 107, 140, 126, 150, 60, 174, 184, 111, 155, 22, 32, 185, 149, 95, 60, 146, 165, 103, 34, 131, 91, 92, 85, 6, 102, 172, 131, 178, 141, 76, 84, 121, 49, 19, 66, 127, 45, 23, 159, 33, 138, 47, 36, 106, 39, 83, 164, 83, 16, 126, 126, 118, 84, 171, ]), 143, ), Scan(Key(vec![165]), -26), Get(Key(vec![])), Del(Key(vec![])), Set( Key(vec![ 197, 224, 20, 219, 111, 246, 70, 138, 190, 237, 9, 202, 187, 160, 47, 10, 231, 14, 2, 131, 30, 202, 95, 48, 44, 21, 192, 155, 172, 51, 101, 155, 73, 5, 22, 140, 137, 11, 37, 79, 79, 92, 25, 107, 82, 145, 39, 45, 155, 136, 242, 8, 43, 71, 28, 70, 94, 79, 151, 20, 144, 53, 100, 196, 74, 140, 27, 224, 59, 1, 143, 136, 132, 85, 114, 166, 103, 242, 156, 183, 168, 148, 2, 33, 29, 201, 7, 96, 13, 33, 102, 172, 21, 96, 27, 1, 86, 149, 150, 119, 208, 118, 148, 51, 143, 54, 245, 89, 216, 145, 145, 72, 105, 51, 19, 14, 15, 18, 34, 16, 101, 172, 133, 32, 173, 106, 157, 15, 48, 194, 27, 55, 204, 110, 145, 99, 9, 37, 195, 206, 13, 246, 161, 100, 222, 235, 184, 12, 64, 103, 50, 158, 242, 163, 198, 61, 224, 130, 226, 187, 158, 175, 135, 54, 110, 33, 9, 59, 127, 135, 47, 204, 109, 105, 0, 161, 48, 247, 140, 101, 141, 81, 157, 80, 135, 228, 102, 44, 74, 53, 121, 116, 17, 56, 26, 112, ]), 22, ), Set(Key(vec![110]), 222), Set(Key(vec![94]), 5), GetGt(Key(vec![ 181, 161, 96, 186, 128, 24, 232, 74, 149, 3, 129, 98, 220, 25, 111, 111, 163, 244, 229, 137, 159, 137, 13, 12, 97, 150, 6, 88, 76, 77, 31, 36, 57, 54, 82, 85, 119, 250, 187, 163, 132, 73, 194, 129, 149, 176, 62, 118, 166, 50, 200, 28, 158, 184, 28, 139, 74, 87, 144, 87, 1, 73, 37, 46, 226, 91, 102, 13, 67, 195, 64, 189, 90, 190, 163, 216, 171, 22, 69, 234, 57, 134, 96, 198, 179, 115, 43, 160, 104, 252, 105, 192, 91, 211, 176, 171, 252, 236, 202, 158, 250, 186, 134, 154, 82, 17, 113, 175, 13, 125, 185, 101, 38, 236, 155, 30, 110, 11, 33, 198, 114, 184, 84, 91, 67, 125, 55, 188, 124, 242, 89, 124, 69, 18, 26, 137, 34, 33, 201, 58, 252, 134, 33, 131, 126, 136, 168, 20, 32, 237, 10, 57, 158, 149, 102, 62, 10, 98, 106, 10, 93, 78, 240, 205, 38, 186, 97, 104, 204, 14, 34, 100, 179, 161, 135, 136, 194, 99, ])), Merge(Key(vec![95]), 253), GetLt(Key(vec![99])), Merge(Key(vec![]), 124), Get(Key(vec![61])), Restart, ], false, 0, 256, ); } } */ #[test] #[cfg_attr(miri, ignore)] fn tree_bug_40() { // postmortem: deletions of non-existant keys were // being persisted despite being unneccessary. prop_tree_matches_btreemap( vec![Del(Key(vec![99; 111222333]))], false, 0, 256, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_41() { // postmortem: indexing of values during // iteration was incorrect. prop_tree_matches_btreemap( vec![ Set(Key(vec![]), 131), Set(Key(vec![17; 1]), 214), Set(Key(vec![4; 1]), 202), Set(Key(vec![24; 1]), 79), Set(Key(vec![26; 1]), 235), Scan(Key(vec![]), 19), ], false, 0, 256, ); } /* #[test] #[cfg_attr(miri, ignore)] fn tree_bug_42() { // postmortem: during refactoring, accidentally // messed up the index selection for merge destinations. for _ in 0..100 { prop_tree_matches_btreemap( vec![ Merge(Key(vec![]), 112), Set(Key(vec![110; 1]), 153), Set(Key(vec![15; 1]), 100), Del(Key(vec![110; 1])), GetLt(Key(vec![148; 1])), ], false, 0, 256, ); } } */ #[test] #[cfg_attr(miri, ignore)] fn tree_bug_43() { // postmortem: when changing the PageState to always // include a base node, we did not account for this // in the tag + size compressed value. This was not // caught by the quickcheck tests because PageState's // Arbitrary implementation would ensure that at least // one frag was present, which was the invariant before // the base was extracted away from the vec of frags. prop_tree_matches_btreemap( vec![ Set(Key(vec![241; 1]), 199), Set(Key(vec![]), 198), Set(Key(vec![72; 108]), 175), GetLt(Key(vec![])), Restart, Restart, ], false, 0, 288, ); } /* #[test] #[cfg_attr(miri, ignore)] fn tree_bug_44() { // postmortem: off-by-one bug related to LSN recovery // where 1 was added to the index when the recovered // LSN was actually divisible by the segment size assert!(prop_tree_matches_btreemap( vec![ Merge(Key(vec![]), 97), Merge(Key(vec![]), 41), Merge(Key(vec![]), 241), Set(Key(vec![21; 1]), 24), Del(Key(vec![])), Set(Key(vec![]), 145), Set(Key(vec![151; 1]), 187), Get(Key(vec![])), Restart, Set(Key(vec![]), 151), Restart, ], false, 0, 256 )) } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_45() { // postmortem: recovery was not properly accounting for // the possibility of a segment to be maxed out, similar // to bug 44. for _ in 0..10 { assert!(prop_tree_matches_btreemap( vec![ Merge(Key(vec![206; 77]), 225), Set(Key(vec![88; 190]), 40), Set(Key(vec![162; 1]), 213), Merge(Key(vec![186; 1]), 175), Set(Key(vec![105; 16]), 111), Cas(Key(vec![]), 75, 252), Restart ], false, true, 0, 210 )) } } */ #[test] #[cfg_attr(miri, ignore)] fn tree_bug_46() { // postmortem: while implementing the heap slab, decompression // was failing to account for the fact that the slab allocator // will always write to the end of the slab to be compatible // with O_DIRECT. for _ in 0..1 { assert!(prop_tree_matches_btreemap(vec![Restart], false, 0, 256)) } } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_47() { // postmortem: assert!(prop_tree_matches_btreemap( vec![Set(Key(vec![88; 1]), 40), Restart, Get(Key(vec![88; 1]))], false, 0, 256 )) } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_48() { // postmortem: node value buffer calculations were failing to // account for potential padding added to avoid buffer overreads // while looking up offsets. assert!(prop_tree_matches_btreemap( vec![ Set(Key(vec![23; 1]), 78), Set(Key(vec![120; 1]), 223), Set(Key(vec![123; 1]), 235), Set(Key(vec![60; 1]), 234), Set(Key(vec![]), 71), Del(Key(vec![120; 1])), Scan(Key(vec![]), -9) ], false, 0, 256 )) } /* #[test] #[cfg_attr(miri, ignore)] fn tree_bug_49() { // postmortem: was incorrectly calculating the child offset while searching // for a node with omitted keys, where the distance == the stride, and // as a result we went into an infinite loop trying to apply a parent // split that was already present assert!(prop_tree_matches_btreemap( vec![ Set(Key(vec![39; 1]), 245), Set(Key(vec![108; 1]), 96), Set(Key(vec![147; 1]), 44), Set(Key(vec![102; 1]), 2), Merge(Key(vec![22; 1]), 160), Set(Key(vec![36; 1]), 1), Set(Key(vec![65; 1]), 213), Set(Key(vec![]), 221), Set(Key(vec![84; 1]), 20), Merge(Key(vec![229; 1]), 61), Set(Key(vec![156; 1]), 69), Merge(Key(vec![252; 1]), 85), Set(Key(vec![36; 2]), 57), Set(Key(vec![245; 1]), 143), Set(Key(vec![59; 1]), 209), GetGt(Key(vec![136; 1])), Set(Key(vec![40; 1]), 96), GetGt(Key(vec![59; 2])) ], false, false, 0, 0 )) } */ #[test] #[cfg_attr(miri, ignore)] fn tree_bug_50() { // postmortem: node value buffer calculations were failing to // account for potential padding added to avoid buffer overreads // while looking up offsets. assert!(prop_tree_matches_btreemap( vec![ Set(Key(vec![1; 1]), 44), Set(Key(vec![52; 1]), 108), Set(Key(vec![80; 1]), 177), Set(Key(vec![225; 1]), 59), Set(Key(vec![246; 1]), 34), Set(Key(vec![51; 1]), 233), Set(Key(vec![]), 88), GetLt(Key(vec![1; 1])) ], false, 0, 0 )) } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_51() { // postmortem: prop_tree_matches_btreemap( vec![Set(Key(vec![]), 135), Restart, Scan(Key(vec![]), -38)], false, 0, 0, ); } #[test] #[cfg_attr(miri, ignore)] fn tree_bug_52() { // postmortem: prop_tree_matches_btreemap( vec![ Set(Key(vec![57; 1]), 235), Set(Key(vec![229; 1]), 136), Set(Key(vec![]), 74), Set(Key(vec![57; 2]), 0), Get(Key(vec![57; 1])), GetGt(Key(vec![57; 1])), Get(Key(vec![57; 2])), GetLt(Key(vec![57; 2])), Scan(Key(vec![]), 4), ], false, 0, 0, ); } ================================================ FILE: tests/common/mod.rs ================================================ // the memshred feature causes all allocated and deallocated // memory to be set to a specific non-zero value of 0xa1 for // uninitialized allocations and 0xde for deallocated memory, // in the hope that it will cause memory errors to surface // more quickly. #[cfg(feature = "testing-shred-allocator")] mod alloc { use std::alloc::{Layout, System}; #[global_allocator] static ALLOCATOR: Alloc = Alloc; #[derive(Default, Debug, Clone, Copy)] struct Alloc; unsafe impl std::alloc::GlobalAlloc for Alloc { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { let ret = System.alloc(layout); assert_ne!(ret, std::ptr::null_mut()); std::ptr::write_bytes(ret, 0xa1, layout.size()); ret } unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { std::ptr::write_bytes(ptr, 0xde, layout.size()); System.dealloc(ptr, layout) } } } pub fn setup_logger() { use std::io::Write; fn tn() -> String { std::thread::current().name().unwrap_or("unknown").to_owned() } let mut builder = env_logger::Builder::new(); builder .format(|buf, record| { writeln!( buf, "{:05} {:20} {:10} {}", record.level(), tn(), record.module_path().unwrap().split("::").last().unwrap(), record.args() ) }) .filter(None, log::LevelFilter::Info); if let Ok(env) = std::env::var("RUST_LOG") { builder.parse_filters(&env); } let _r = builder.try_init(); } #[allow(dead_code)] pub fn cleanup(dir: &str) { let dir = std::path::Path::new(dir); if dir.exists() { std::fs::remove_dir_all(dir).unwrap(); } } ================================================ FILE: tests/concurrent_batch_atomicity.rs ================================================ use std::sync::{Arc, Barrier}; use std::thread; use sled::{Config, Db as SledDb}; const CONCURRENCY: usize = 32; const N_KEYS: usize = 1024; type Db = SledDb<8>; fn batch_writer(db: Db, barrier: Arc, thread_number: usize) { barrier.wait(); let mut batch = sled::Batch::default(); for key_number in 0_u128..N_KEYS as _ { // LE is intentionally a little scrambled batch.insert(&key_number.to_le_bytes(), &thread_number.to_le_bytes()); } db.apply_batch(batch).unwrap(); } #[test] fn concurrent_batch_atomicity() { let db: Db = Config { path: "concurrent_batch_atomicity".into(), ..Default::default() } .open() .unwrap(); let mut threads = vec![]; let flusher_barrier = Arc::new(Barrier::new(CONCURRENCY)); for tn in 0..CONCURRENCY { let db = db.clone(); let barrier = flusher_barrier.clone(); let thread = thread::Builder::new() .name(format!("t(thread: {} flusher)", tn)) .spawn(move || { db.flush().unwrap(); barrier.wait(); }) .expect("should be able to spawn thread"); threads.push(thread); } let barrier = Arc::new(Barrier::new(CONCURRENCY + 1)); for thread_number in 0..CONCURRENCY { let db = db.clone(); let barrier = barrier.clone(); let jh = thread::spawn(move || batch_writer(db, barrier, thread_number)); threads.push(jh); } barrier.wait(); let before = std::time::Instant::now(); for thread in threads.into_iter() { thread.join().unwrap(); } println!("writers took {:?}", before.elapsed()); let mut expected_v = None; for key_number in 0_u128..N_KEYS as _ { let actual_v = db.get(&key_number.to_le_bytes()).unwrap().unwrap(); if expected_v.is_none() { expected_v = Some(actual_v.clone()); } assert_eq!(Some(actual_v), expected_v); } let _ = std::fs::remove_dir_all("concurrent_batch_atomicity"); } ================================================ FILE: tests/crash_tests/crash_batches.rs ================================================ use std::thread; use rand::Rng; use super::*; const CACHE_SIZE: usize = 1024 * 1024; const BATCH_SIZE: u32 = 8; const SEGMENT_SIZE: usize = 1024; /// Verifies that the keys in the tree are correctly recovered (i.e., equal). /// Panics if they are incorrect. fn verify_batches(tree: &Db) -> u32 { let mut iter = tree.iter(); let first_value = match iter.next() { Some(Ok((_k, v))) => slice_to_u32(&*v), Some(Err(e)) => panic!("{:?}", e), None => return 0, }; // we now expect all items in the batch to be present and to have the same value for key in 0..BATCH_SIZE { let res = tree.get(u32_to_vec(key)); let option = res.unwrap(); let v = match option { Some(v) => v, None => panic!( "expected key {} to have a value, instead it was missing in db with keys: {}", key, tree_to_string(&tree) ), }; let value = slice_to_u32(&*v); // FIXME BUG 1 count 2 // assertion `left == right` failed: expected key 0 to have value 62003, instead it had value 62375 in db with keys: // {0:62003, 1:62003, 2:62003, 3:62003, 4:62003, 5:62003, 6:62003, 7:62003, // Human: iterating shows correct value, but first get did not // // expected key 1 to have value 1, instead it had value 29469 in db with keys: // {0:1, 1:29469, 2:29469, 3:29469, 4:29469, 5:29469, 6:29469, 7:29469, // Human: 0 didn't get included in later syncs // // expected key 0 to have value 59485, instead it had value 59484 in db with keys: // {0:59485, 1:59485, 2:59485, 3:59485, 4:59485, 5:59485, 6:59485, 7:59485, // Human: had key N during first check, then N + 1 in iteration assert_eq!( first_value, value, "expected key {} to have value {}, instead it had value {}. second get: {:?}. db iter: {}. third get: {:?}", key, first_value, value, slice_to_u32(&*tree.get(u32_to_vec(key)).unwrap().unwrap()), tree_to_string(&tree), slice_to_u32(&*tree.get(u32_to_vec(key)).unwrap().unwrap()), ); } first_value } fn run_batches_inner(db: Db) { fn do_batch(i: u32, db: &Db) { let mut rng = rand::rng(); let base_value = u32_to_vec(i); let mut batch = sled::Batch::default(); if rng.random_bool(0.1) { for key in 0..BATCH_SIZE { batch.remove(u32_to_vec(key)); } } else { for key in 0..BATCH_SIZE { let mut value = base_value.clone(); let additional_len = rng.random_range(0..SEGMENT_SIZE / 3); value.append(&mut vec![0u8; additional_len]); batch.insert(u32_to_vec(key), value); } } db.apply_batch(batch).unwrap(); } let mut i = verify_batches(&db); i += 1; do_batch(i, &db); loop { i += 1; do_batch(i, &db); } } pub fn run_crash_batches() { let crash_during_initialization = rand::rng().random_ratio(1, 10); if crash_during_initialization { spawn_killah(); } let path = std::path::Path::new(CRASH_DIR).join(BATCHES_DIR); let config = Config::new() .cache_capacity_bytes(CACHE_SIZE) .flush_every_ms(Some(1)) .path(path); let db = config.open().expect("couldn't open batch db"); let db2 = db.clone(); let t1 = thread::spawn(|| run_batches_inner(db)); let t2 = thread::spawn(move || { loop { db2.flush().unwrap(); } }); // run_batches_inner(db2)); if !crash_during_initialization { spawn_killah(); } let Err(e) = t1.join().and_then(|_| t2.join()); println!("worker thread failed: {:?}", e); std::process::exit(15); } ================================================ FILE: tests/crash_tests/crash_heap.rs ================================================ use super::*; const FANOUT: usize = 3; pub fn run_crash_heap() { let path = std::path::Path::new(CRASH_DIR).join(HEAP_DIR); let config = Config::new().path(path); let HeapRecovery { heap, recovered_nodes, was_recovered } = Heap::recover(FANOUT, &config).unwrap(); // validate spawn_killah(); loop {} } ================================================ FILE: tests/crash_tests/crash_iter.rs ================================================ use std::sync::{Arc, Barrier}; use std::thread; use super::*; const CACHE_SIZE: usize = 256; pub fn run_crash_iter() { const N_FORWARD: usize = 50; const N_REVERSE: usize = 50; let path = std::path::Path::new(CRASH_DIR).join(ITER_DIR); let config = Config::new() .cache_capacity_bytes(CACHE_SIZE) .path(path) .flush_every_ms(Some(1)); let db: Db = config.open().expect("couldn't open iter db"); let t = db.open_tree(b"crash_iter_test").unwrap(); thread::Builder::new() .name("crash_iter_flusher".to_string()) .spawn({ let t = t.clone(); move || loop { t.flush().unwrap(); } }) .unwrap(); const INDELIBLE: [&[u8]; 16] = [ &[0u8], &[1u8], &[2u8], &[3u8], &[4u8], &[5u8], &[6u8], &[7u8], &[8u8], &[9u8], &[10u8], &[11u8], &[12u8], &[13u8], &[14u8], &[15u8], ]; for item in &INDELIBLE { t.insert(*item, *item).unwrap(); } t.flush().unwrap(); let barrier = Arc::new(Barrier::new(N_FORWARD + N_REVERSE + 2)); let mut threads = vec![]; for i in 0..N_FORWARD { let t = thread::Builder::new() .name(format!("forward({})", i)) .spawn({ let t = t.clone(); let barrier = barrier.clone(); move || { barrier.wait(); loop { let expected = INDELIBLE.iter(); let mut keys = t.iter().keys(); for expect in expected { loop { let k = keys.next().unwrap().unwrap(); assert!( &*k <= *expect, "witnessed key is {:?} but we expected \ one <= {:?}, so we overshot due to a \ concurrent modification", k, expect, ); if &*k == *expect { break; } } } } } }) .unwrap(); threads.push(t); } for i in 0..N_REVERSE { let t = thread::Builder::new() .name(format!("reverse({})", i)) .spawn({ let t = t.clone(); let barrier = barrier.clone(); move || { barrier.wait(); loop { let expected = INDELIBLE.iter().rev(); let mut keys = t.iter().keys().rev(); for expect in expected { loop { if let Some(Ok(k)) = keys.next() { assert!( &*k >= *expect, "witnessed key is {:?} but we expected \ one >= {:?}, so we overshot due to a \ concurrent modification\n{:?}", k, expect, t, ); if &*k == *expect { break; } } else { panic!("undershot key on tree: \n{:?}", t); } } } } } }) .unwrap(); threads.push(t); } let inserter = thread::Builder::new() .name("inserter".into()) .spawn({ let t = t.clone(); let barrier = barrier.clone(); move || { barrier.wait(); loop { for i in 0..(16 * 16 * 8) { let major = i / (16 * 8); let minor = i % 16; let mut base = INDELIBLE[major].to_vec(); base.push(minor as u8); t.insert(base.clone(), base.clone()).unwrap(); } } } }) .unwrap(); threads.push(inserter); let deleter = thread::Builder::new() .name("deleter".into()) .spawn({ move || { barrier.wait(); loop { for i in 0..(16 * 16 * 8) { let major = i / (16 * 8); let minor = i % 16; let mut base = INDELIBLE[major].to_vec(); base.push(minor as u8); t.remove(&base).unwrap(); } } } }) .unwrap(); spawn_killah(); threads.push(deleter); for thread in threads.into_iter() { thread.join().expect("thread should not have crashed"); } } ================================================ FILE: tests/crash_tests/crash_metadata_store.rs ================================================ use super::*; pub fn run_crash_metadata_store() { let (metadata_store, recovered) = MetadataStore::recover(&HEAP_DIR).unwrap(); // validate spawn_killah(); loop {} } ================================================ FILE: tests/crash_tests/crash_object_cache.rs ================================================ use super::*; const FANOUT: usize = 3; pub fn run_crash_object_cache() { let path = std::path::Path::new(CRASH_DIR).join(OBJECT_CACHE_DIR); let config = Config::new().flush_every_ms(Some(1)).path(path); let (oc, collections, was_recovered): (ObjectCache, _, bool) = ObjectCache::recover(&config).unwrap(); // validate spawn_killah(); loop {} } ================================================ FILE: tests/crash_tests/crash_sequential_writes.rs ================================================ use std::thread; use super::*; const CACHE_SIZE: usize = 1024 * 1024; const CYCLE: usize = 256; const SEGMENT_SIZE: usize = 1024; /// Verifies that the keys in the tree are correctly recovered. /// Panics if they are incorrect. /// Returns the key that should be resumed at, and the current cycle value. fn verify(tree: &Db) -> (u32, u32) { // key 0 should always be the highest value, as that's where we increment // at some point, it might go down by one // it should never return, or go down again after that let mut iter = tree.iter(); let highest = match iter.next() { Some(Ok((_k, v))) => slice_to_u32(&*v), Some(Err(e)) => panic!("{:?}", e), None => return (0, 0), }; let highest_vec = u32_to_vec(highest); // find how far we got let mut contiguous: u32 = 0; let mut lowest_with_high_value = 0; for res in iter { let (k, v) = res.unwrap(); if v[..4] == highest_vec[..4] { contiguous += 1; } else { let expected = if highest == 0 { CYCLE as u32 - 1 } else { (highest - 1) % CYCLE as u32 }; let actual = slice_to_u32(&*v); // FIXME BUG 2 // thread '' panicked at tests/test_crash_recovery.rs:159:13: // assertion `left == right` failed // left: 139 // right: 136 assert_eq!( expected, actual, "tree failed assertion with iterated values: {}, k: {:?} v: {:?} expected: {} highest: {}", tree_to_string(&tree), k, v, expected, highest ); lowest_with_high_value = actual; break; } } // ensure nothing changes after this point let low_beginning = u32_to_vec(contiguous + 1); for res in tree.range(&*low_beginning..) { let (k, v): (sled::InlineArray, _) = res.unwrap(); assert_eq!( slice_to_u32(&*v), lowest_with_high_value, "expected key {} to have value {}, instead it had value {} in db: {:?}", slice_to_u32(&*k), lowest_with_high_value, slice_to_u32(&*v), tree ); } (contiguous, highest) } fn run_inner(config: Config) { let crash_during_initialization = rand::rng().random_bool(0.1); if crash_during_initialization { spawn_killah(); } let tree = config.open().expect("couldn't open db"); if !crash_during_initialization { spawn_killah(); } let (key, highest) = verify(&tree); let mut hu = ((highest as usize) * CYCLE) + key as usize; assert_eq!(hu % CYCLE, key as usize); assert_eq!(hu / CYCLE, highest as usize); loop { let key = u32_to_vec((hu % CYCLE) as u32); //dbg!(hu, hu % CYCLE); let mut value = u32_to_vec((hu / CYCLE) as u32); let additional_len = rand::rng().random_range(0..SEGMENT_SIZE / 3); value.append(&mut vec![0u8; additional_len]); tree.insert(&key, value).unwrap(); hu += 1; if hu / CYCLE >= CYCLE { hu = 0; } } } pub fn run_crash_sequential_writes() { let path = std::path::Path::new(CRASH_DIR).join(SEQUENTIAL_WRITES_DIR); let config = Config::new() .cache_capacity_bytes(CACHE_SIZE) .flush_every_ms(Some(1)) .path(path); if let Err(e) = thread::spawn(|| run_inner(config)).join() { println!("worker thread failed: {:?}", e); std::process::exit(15); } } ================================================ FILE: tests/crash_tests/crash_tx.rs ================================================ use super::*; const CACHE_SIZE: usize = 1024 * 1024; pub fn run_crash_tx() { let config = Config::new() .cache_capacity_bytes(CACHE_SIZE) .flush_every_ms(Some(1)) .path(TX_DIR); let _db: Db = config.open().unwrap(); spawn_killah(); loop {} /* db.insert(b"k1", b"cats").unwrap(); db.insert(b"k2", b"dogs").unwrap(); db.insert(b"id", &0_u64.to_le_bytes()).unwrap(); let mut threads = vec![]; const N_WRITERS: usize = 50; const N_READERS: usize = 5; let barrier = Arc::new(Barrier::new(N_WRITERS + N_READERS)); for _ in 0..N_WRITERS { let db = db.clone(); let barrier = barrier.clone(); let thread = std::thread::spawn(move || { barrier.wait(); loop { db.transaction::<_, _, ()>(|db| { let v1 = db.remove(b"k1").unwrap().unwrap(); let v2 = db.remove(b"k2").unwrap().unwrap(); db.insert(b"id", &db.generate_id().unwrap().to_le_bytes()) .unwrap(); db.insert(b"k1", v2).unwrap(); db.insert(b"k2", v1).unwrap(); Ok(()) }) .unwrap(); } }); threads.push(thread); } for _ in 0..N_READERS { let db = db.clone(); let barrier = barrier.clone(); let thread = std::thread::spawn(move || { barrier.wait(); let mut last_id = 0; loop { let read_id = db .transaction::<_, _, ()>(|db| { let v1 = db.get(b"k1").unwrap().unwrap(); let v2 = db.get(b"k2").unwrap().unwrap(); let id = u64::from_le_bytes( TryFrom::try_from( &*db.get(b"id").unwrap().unwrap(), ) .unwrap(), ); let mut results = vec![v1, v2]; results.sort(); assert_eq!( [&results[0], &results[1]], [b"cats", b"dogs"] ); Ok(id) }) .unwrap(); assert!(read_id >= last_id); last_id = read_id; } }); threads.push(thread); } spawn_killah(); for thread in threads.into_iter() { thread.join().expect("threads should not crash"); } let v1 = db.get(b"k1").unwrap().unwrap(); let v2 = db.get(b"k2").unwrap().unwrap(); assert_eq!([v1, v2], [b"cats", b"dogs"]); */ } ================================================ FILE: tests/crash_tests/mod.rs ================================================ use std::mem::size_of; use std::process::exit; use std::thread; use std::time::Duration; use rand::Rng; use sled::{ Config, Db as SledDb, Heap, HeapRecovery, MetadataStore, ObjectCache, }; mod crash_batches; mod crash_heap; mod crash_iter; mod crash_metadata_store; mod crash_object_cache; mod crash_sequential_writes; mod crash_tx; pub use crash_batches::run_crash_batches; pub use crash_heap::run_crash_heap; pub use crash_iter::run_crash_iter; pub use crash_metadata_store::run_crash_metadata_store; pub use crash_object_cache::run_crash_object_cache; pub use crash_sequential_writes::run_crash_sequential_writes; pub use crash_tx::run_crash_tx; type Db = SledDb<8>; // test names, also used as dir names pub const SEQUENTIAL_WRITES_DIR: &str = "crash_sequential_writes"; pub const BATCHES_DIR: &str = "crash_batches"; pub const ITER_DIR: &str = "crash_iter"; pub const TX_DIR: &str = "crash_tx"; pub const METADATA_STORE_DIR: &str = "crash_metadata_store"; pub const HEAP_DIR: &str = "crash_heap"; pub const OBJECT_CACHE_DIR: &str = "crash_object_cache"; const CRASH_DIR: &str = "crash_test_files"; fn spawn_killah() { thread::spawn(|| { let runtime = rand::rng().random_range(0..60_000); thread::sleep(Duration::from_micros(runtime)); exit(9); }); } fn u32_to_vec(u: u32) -> Vec { let buf: [u8; size_of::()] = u.to_be_bytes(); buf.to_vec() } fn slice_to_u32(b: &[u8]) -> u32 { let mut buf = [0u8; size_of::()]; buf.copy_from_slice(&b[..size_of::()]); u32::from_be_bytes(buf) } fn tree_to_string(tree: &Db) -> String { let mut ret = String::from("{"); for kv_res in tree.iter() { let (k, v) = kv_res.unwrap(); let k_s = slice_to_u32(&k); let v_s = slice_to_u32(&v); ret.push_str(&format!("{}:{}, ", k_s, v_s)); } ret.push_str("}"); ret } ================================================ FILE: tests/test_crash_recovery.rs ================================================ mod common; mod crash_tests; use std::alloc::{Layout, System}; use std::env::{self, VarError}; use std::process::Command; use std::thread; use common::cleanup; const TEST_ENV_VAR: &str = "SLED_CRASH_TEST"; const N_TESTS: usize = 100; const TESTS: [&str; 7] = [ crash_tests::SEQUENTIAL_WRITES_DIR, crash_tests::BATCHES_DIR, crash_tests::ITER_DIR, crash_tests::TX_DIR, crash_tests::METADATA_STORE_DIR, crash_tests::HEAP_DIR, crash_tests::OBJECT_CACHE_DIR, ]; const CRASH_CHANCE: u32 = 250; #[global_allocator] static ALLOCATOR: ShredAllocator = ShredAllocator; #[derive(Default, Debug, Clone, Copy)] struct ShredAllocator; unsafe impl std::alloc::GlobalAlloc for ShredAllocator { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { assert!(layout.size() < 1_000_000_000); let ret = unsafe { System.alloc(layout) }; assert_ne!(ret, std::ptr::null_mut()); unsafe { std::ptr::write_bytes(ret, 0xa1, layout.size()); } ret } unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { unsafe { std::ptr::write_bytes(ptr, 0xde, layout.size()); } unsafe { System.dealloc(ptr, layout) } } } fn main() { // Don't actually run this harness=false test under miri, as it requires // spawning and killing child processes. if cfg!(miri) { return; } common::setup_logger(); match env::var(TEST_ENV_VAR) { Err(VarError::NotPresent) => { let filtered: Vec<&'static str> = if let Some(filter) = std::env::args().nth(1) { TESTS .iter() .filter(|name| name.contains(&filter)) .cloned() .collect() } else { TESTS.to_vec() }; let filtered_len = filtered.len(); println!(); println!( "running {} test{}", filtered.len(), if filtered.len() == 1 { "" } else { "s" }, ); let mut tests = vec![]; for test_name in filtered.into_iter() { let test = thread::spawn(move || { let res = std::panic::catch_unwind(|| supervisor(test_name)); println!( "test {} ... {}", test_name, if res.is_ok() { "ok" } else { "panicked" } ); res.unwrap(); }); tests.push((test_name, test)); } for (test_name, test) in tests.into_iter() { test.join().expect(test_name); } println!(); println!( "test result: ok. {} passed; {} filtered out", filtered_len, TESTS.len() - filtered_len, ); println!(); } Ok(ref s) if s == crash_tests::SEQUENTIAL_WRITES_DIR => { crash_tests::run_crash_sequential_writes() } Ok(ref s) if s == crash_tests::BATCHES_DIR => { crash_tests::run_crash_batches() } Ok(ref s) if s == crash_tests::ITER_DIR => { crash_tests::run_crash_iter() } Ok(ref s) if s == crash_tests::TX_DIR => crash_tests::run_crash_tx(), Ok(ref s) if s == crash_tests::METADATA_STORE_DIR => { crash_tests::run_crash_metadata_store() } Ok(ref s) if s == crash_tests::HEAP_DIR => { crash_tests::run_crash_heap() } Ok(ref s) if s == crash_tests::OBJECT_CACHE_DIR => { crash_tests::run_crash_object_cache() } Ok(other) => panic!("invalid crash test case: {other}"), Err(e) => panic!("env var {TEST_ENV_VAR} unable to be read: {e:?}"), } } fn run_child_process(dir: &str) { let bin = env::current_exe().expect("could not get test binary path"); unsafe { env::set_var(TEST_ENV_VAR, dir); } let status_res = Command::new(bin) .env(TEST_ENV_VAR, dir) .env("SLED_CRASH_CHANCE", CRASH_CHANCE.to_string()) .spawn() .unwrap_or_else(|_| { panic!("could not spawn child process for {} test", dir) }) .wait(); match status_res { Ok(status) => { let code = status.code(); if code.is_none() || code.unwrap() != 9 { cleanup(dir); panic!("{} test child exited abnormally", dir); } } Err(e) => { cleanup(dir); panic!("error waiting for {} test child: {}", dir, e); } } } fn supervisor(dir: &str) { cleanup(dir); for _ in 0..N_TESTS { run_child_process(dir); } cleanup(dir); } ================================================ FILE: tests/test_quiescent.rs ================================================ #![cfg(all(target_os = "linux", not(miri)))] mod common; use std::time::{Duration, Instant}; use common::cleanup; #[test] fn quiescent_cpu_time() { const DB_DIR: &str = "sleeper"; cleanup(DB_DIR); fn run() { let start = Instant::now(); let db = sled::open(DB_DIR).unwrap(); std::thread::sleep(Duration::from_secs(10)); drop(db); let end = Instant::now(); let (user_cpu_time, system_cpu_time) = unsafe { let mut resource_usage: libc::rusage = std::mem::zeroed(); let return_value = libc::getrusage( libc::RUSAGE_SELF, (&mut resource_usage) as *mut libc::rusage, ); if return_value != 0 { panic!("error {} from getrusage()", *libc::__errno_location()); } (resource_usage.ru_utime, resource_usage.ru_stime) }; let user_cpu_seconds = user_cpu_time.tv_sec as f64 + user_cpu_time.tv_usec as f64 * 1e-6; let system_cpu_seconds = system_cpu_time.tv_sec as f64 + system_cpu_time.tv_usec as f64 * 1e-6; let real_time_elapsed = end.duration_since(start); if user_cpu_seconds + system_cpu_seconds > 1.0 { panic!( "Database used too much CPU during a quiescent workload. User: {}s, system: {}s (wall clock: {}s)", user_cpu_seconds, system_cpu_seconds, real_time_elapsed.as_secs_f64(), ); } } let child = unsafe { libc::fork() }; if child == 0 { common::setup_logger(); if let Err(e) = std::thread::spawn(run).join() { println!("test failed: {:?}", e); std::process::exit(15); } else { std::process::exit(0); } } else { let mut status = 0; unsafe { libc::waitpid(child, &mut status as *mut libc::c_int, 0); } if status != 0 { cleanup(DB_DIR); panic!("child exited abnormally"); } } cleanup(DB_DIR); } ================================================ FILE: tests/test_space_leaks.rs ================================================ use std::io; mod common; #[test] #[cfg_attr(miri, ignore)] fn size_leak() -> io::Result<()> { common::setup_logger(); let tree: sled::Db<1024> = sled::Config::tmp()?.flush_every_ms(None).open()?; for _ in 0..10_000 { tree.insert(b"", b"")?; } tree.flush()?; let sz = tree.size_on_disk()?; assert!( sz <= 16384, "expected system to use less than or equal to \ 16486 bytes, but actually used {}", sz ); Ok(()) } ================================================ FILE: tests/test_tree.rs ================================================ mod common; mod tree; use std::{ io, sync::{ Arc, Barrier, atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst}, }, }; #[allow(unused_imports)] use log::{debug, warn}; use quickcheck::{Gen, QuickCheck}; // use sled::Transactional; // use sled::transaction::*; use sled::{Config, Db as SledDb, InlineArray}; type Db = SledDb<3>; use tree::{ Op::{self}, prop_tree_matches_btreemap, }; const N_THREADS: usize = 32; const N_PER_THREAD: usize = 10_000; const N: usize = N_THREADS * N_PER_THREAD; // NB N should be multiple of N_THREADS const SPACE: usize = N; #[allow(dead_code)] const INTENSITY: usize = 1; fn kv(i: usize) -> InlineArray { let i = i % SPACE; let k = [(i >> 16) as u8, (i >> 8) as u8, i as u8]; (&k).into() } #[test] #[cfg_attr(miri, ignore)] fn monotonic_inserts() { common::setup_logger(); let db: Db = Config::tmp().unwrap().flush_every_ms(None).open().unwrap(); for len in [1_usize, 16, 32, 1024].iter() { for i in 0_usize..*len { let mut k = vec![]; for c in 0_usize..i { k.push((c % 256) as u8); } db.insert(&k, &[]).unwrap(); } let count = db.iter().count(); assert_eq!(count, *len as usize); let count2 = db.iter().rev().count(); assert_eq!(count2, *len as usize); db.clear().unwrap(); } for len in [1_usize, 16, 32, 1024].iter() { for i in (0_usize..*len).rev() { let mut k = vec![]; for c in (0_usize..i).rev() { k.push((c % 256) as u8); } db.insert(&k, &[]).unwrap(); } let count3 = db.iter().count(); assert_eq!(count3, *len as usize); let count4 = db.iter().rev().count(); assert_eq!(count4, *len as usize); db.clear().unwrap(); } } #[test] #[cfg_attr(miri, ignore)] fn fixed_stride_inserts() { // this is intended to test the fixed stride key omission optimization common::setup_logger(); let db: Db = Config::tmp().unwrap().flush_every_ms(None).open().unwrap(); let mut expected = std::collections::HashSet::new(); for k in 0..4096_u16 { db.insert(&k.to_be_bytes(), &[]).unwrap(); expected.insert(k.to_be_bytes().to_vec()); } let mut count = 0_u16; for kvr in db.iter() { let (k, _) = kvr.unwrap(); assert_eq!(&k, &count.to_be_bytes()); count += 1; } assert_eq!(count, 4096, "tree: {:?}", db); assert_eq!(db.len().unwrap(), 4096); let count = db.iter().rev().count(); assert_eq!(count, 4096); for k in 0..4096_u16 { db.insert(&k.to_be_bytes(), &[1]).unwrap(); } let count = db.iter().count(); assert_eq!(count, 4096); let count = db.iter().rev().count(); assert_eq!(count, 4096); assert_eq!(db.len().unwrap(), 4096); for k in 0..4096_u16 { db.remove(&k.to_be_bytes()).unwrap(); } let count = db.iter().count(); assert_eq!(count, 0); let count = db.iter().rev().count(); assert_eq!(count, 0); assert_eq!(db.len().unwrap(), 0); assert!(db.is_empty().unwrap()); } #[test] #[cfg_attr(miri, ignore)] fn sequential_inserts() { common::setup_logger(); let db: Db = Config::tmp().unwrap().flush_every_ms(None).open().unwrap(); for len in [1, 16, 32, u16::MAX].iter() { for i in 0..*len { db.insert(&i.to_le_bytes(), &[]).unwrap(); } let count = db.iter().count(); assert_eq!(count, *len as usize); let count2 = db.iter().rev().count(); assert_eq!(count2, *len as usize); } } #[test] #[cfg_attr(miri, ignore)] fn reverse_inserts() { common::setup_logger(); let db: Db = Config::tmp().unwrap().flush_every_ms(None).open().unwrap(); for len in [1, 16, 32, u16::MAX].iter() { for i in 0..*len { let i2 = u16::MAX - i; db.insert(&i2.to_le_bytes(), &[]).unwrap(); } let count = db.iter().count(); assert_eq!(count, *len as usize); let count2 = db.iter().rev().count(); assert_eq!(count2, *len as usize); } } #[test] #[cfg_attr(miri, ignore)] fn very_large_reverse_tree_iterator() { let mut a = vec![255; 1024 * 1024]; a.push(0); let mut b = vec![255; 1024 * 1024]; b.push(1); let db: Db = Config::tmp().unwrap().flush_every_ms(Some(1)).open().unwrap(); db.insert(a, "").unwrap(); db.insert(b, "").unwrap(); assert_eq!(db.iter().rev().count(), 2); } #[test] #[cfg(all(target_os = "linux", not(miri)))] fn varied_compression_ratios() { // tests for the compression issue reported in #938 by @Mrmaxmeier. let low_entropy = vec![0u8; 64 << 10]; // 64k zeroes let high_entropy = { // 64mb random use std::fs::File; use std::io::Read; let mut buf = vec![0u8; 64 << 20]; File::open("/dev/urandom").unwrap().read_exact(&mut buf).unwrap(); buf }; let tree: Db = Config::default().path("compression_db_test").open().unwrap(); tree.insert(b"low entropy", &low_entropy[..]).unwrap(); tree.insert(b"high entropy", &high_entropy[..]).unwrap(); println!("reloading database..."); drop(tree); let tree: Db = Config::default().path("compression_db_test").open().unwrap(); drop(tree); let _ = std::fs::remove_dir_all("compression_db_test"); } #[test] fn test_pop_first() -> io::Result<()> { let config = sled::Config::tmp().unwrap(); let db: sled::Db<4> = config.open()?; db.insert(&[0], vec![0])?; db.insert(&[1], vec![10])?; db.insert(&[2], vec![20])?; db.insert(&[3], vec![30])?; db.insert(&[4], vec![40])?; db.insert(&[5], vec![50])?; assert_eq!(&db.pop_first()?.unwrap().0, &[0]); assert_eq!(&db.pop_first()?.unwrap().0, &[1]); assert_eq!(&db.pop_first()?.unwrap().0, &[2]); assert_eq!(&db.pop_first()?.unwrap().0, &[3]); assert_eq!(&db.pop_first()?.unwrap().0, &[4]); assert_eq!(&db.pop_first()?.unwrap().0, &[5]); assert_eq!(db.pop_first()?, None); /* */ Ok(()) } #[test] fn test_pop_last_in_range() -> io::Result<()> { let config = sled::Config::tmp().unwrap(); let db: sled::Db<4> = config.open()?; let data = vec![ (b"key 1", b"value 1"), (b"key 2", b"value 2"), (b"key 3", b"value 3"), ]; for (k, v) in data { db.insert(k, v).unwrap(); } let r1 = db.pop_last_in_range(b"key 1".as_ref()..=b"key 3").unwrap(); assert_eq!(Some((b"key 3".into(), b"value 3".into())), r1); let r2 = db.pop_last_in_range(b"key 1".as_ref()..b"key 3").unwrap(); assert_eq!(Some((b"key 2".into(), b"value 2".into())), r2); let r3 = db.pop_last_in_range(b"key 4".as_ref()..).unwrap(); assert!(r3.is_none()); let r4 = db.pop_last_in_range(b"key 2".as_ref()..=b"key 3").unwrap(); assert!(r4.is_none()); let r5 = db.pop_last_in_range(b"key 0".as_ref()..=b"key 3").unwrap(); assert_eq!(Some((b"key 1".into(), b"value 1".into())), r5); let r6 = db.pop_last_in_range(b"key 0".as_ref()..=b"key 3").unwrap(); assert!(r6.is_none()); Ok(()) } #[test] fn test_interleaved_gets_sets() { common::setup_logger(); let db: Db = Config::tmp().unwrap().cache_capacity_bytes(1024).open().unwrap(); let done = Arc::new(AtomicBool::new(false)); std::thread::scope(|scope| { let db_2 = db.clone(); let done = &done; scope.spawn(move || { for v in 0..500_000_u32 { db_2.insert(v.to_be_bytes(), &[42u8; 4096][..]) .expect("failed to insert"); if v % 10_000 == 0 { log::trace!("WRITING: {}", v); db_2.flush().unwrap(); } } done.store(true, SeqCst); }); scope.spawn(move || { while !done.load(SeqCst) { for v in (0..500_000_u32).rev() { db.get(v.to_be_bytes()).expect("Fatal error?"); if v % 10_000 == 0 { log::trace!("READING: {}", v) } } } }); }); } #[test] #[cfg(not(miri))] // can't create threads fn concurrent_tree_pops() -> std::io::Result<()> { use std::thread; let db: Db = Config::tmp().unwrap().open()?; // Insert values 0..5 for x in 0u32..5 { db.insert(x.to_be_bytes(), &[])?; } let mut threads = vec![]; // Pop 5 values using multiple threads let barrier = Arc::new(Barrier::new(5)); for _ in 0..5 { let barrier = barrier.clone(); let db: Db = db.clone(); threads.push(thread::spawn(move || { barrier.wait(); db.pop_first().unwrap().unwrap(); })); } for thread in threads.into_iter() { thread.join().unwrap(); } assert!( db.is_empty().unwrap(), "elements left in database: {:?}", db.iter().collect::>() ); Ok(()) } #[test] #[cfg(not(miri))] // can't create threads fn concurrent_tree_ops() { use std::thread; common::setup_logger(); for i in 0..INTENSITY { debug!("beginning test {}", i); let config = Config::tmp() .unwrap() .flush_every_ms(Some(1)) .cache_capacity_bytes(1024); macro_rules! par { ($t:ident, $f:expr) => { let mut threads = vec![]; let flusher_barrier = Arc::new(Barrier::new(N_THREADS)); for tn in 0..N_THREADS { let tree = $t.clone(); let barrier = flusher_barrier.clone(); let thread = thread::Builder::new() .name(format!("t(thread: {} flusher)", tn)) .spawn(move || { tree.flush().unwrap(); barrier.wait(); }) .expect("should be able to spawn thread"); threads.push(thread); } let barrier = Arc::new(Barrier::new(N_THREADS)); for tn in 0..N_THREADS { let tree = $t.clone(); let barrier = barrier.clone(); let thread = thread::Builder::new() .name(format!("t(thread: {} test: {})", tn, i)) .spawn(move || { barrier.wait(); for i in (tn * N_PER_THREAD)..((tn + 1) * N_PER_THREAD) { let k = kv(i); $f(&tree, k); } }) .expect("should be able to spawn thread"); threads.push(thread); } while let Some(thread) = threads.pop() { if let Err(e) = thread.join() { panic!("thread failure: {:?}", e); } } }; } debug!("========== initial sets test {} ==========", i); let t: Db = config.open().unwrap(); par! {t, move |tree: &Db, k: InlineArray| { assert_eq!(tree.get(&*k).unwrap(), None); tree.insert(&k, k.clone()).expect("we should write successfully"); assert_eq!(tree.get(&*k).unwrap(), Some(k.clone().into()), "failed to read key {:?} that we just wrote from tree {:?}", k, tree); }}; let n_scanned = t.iter().count(); if n_scanned != N { warn!( "WARNING: test {} only had {} keys present \ in the DB BEFORE restarting. expected {}", i, n_scanned, N, ); } drop(t); let t: Db = config.open().expect("should be able to restart Db"); let n_scanned = t.iter().count(); if n_scanned != N { warn!( "WARNING: test {} only had {} keys present \ in the DB AFTER restarting. expected {}", i, n_scanned, N, ); } debug!("========== reading sets in test {} ==========", i); par! {t, move |tree: &Db, k: InlineArray| { if let Some(v) = tree.get(&*k).unwrap() { if v != k { panic!("expected key {:?} not found", k); } } else { panic!( "could not read key {:?}, which we \ just wrote to tree {:?}", k, tree ); } }}; drop(t); let t: Db = config.open().expect("should be able to restart Db"); debug!("========== CAS test in test {} ==========", i); par! {t, move |tree: &Db, k: InlineArray| { let k1 = k.clone(); let mut k2 = k; k2.make_mut().reverse(); tree.compare_and_swap(&k1, Some(&*k1), Some(k2)).unwrap().unwrap(); }}; drop(t); let t: Db = config.open().expect("should be able to restart Db"); par! {t, move |tree: &Db, k: InlineArray| { let k1 = k.clone(); let mut k2 = k; k2.make_mut().reverse(); assert_eq!(tree.get(&*k1).unwrap().unwrap(), k2); }}; drop(t); let t: Db = config.open().expect("should be able to restart Db"); debug!("========== deleting in test {} ==========", i); par! {t, move |tree: &Db, k: InlineArray| { tree.remove(&*k).unwrap().unwrap(); }}; drop(t); let t: Db = config.open().expect("should be able to restart Db"); par! {t, move |tree: &Db, k: InlineArray| { assert_eq!(tree.get(&*k).unwrap(), None); }}; } } #[test] #[cfg(not(miri))] // can't create threads fn concurrent_tree_iter() -> io::Result<()> { use std::sync::Barrier; use std::thread; common::setup_logger(); const N_FORWARD: usize = INTENSITY; const N_REVERSE: usize = INTENSITY; const N_INSERT: usize = INTENSITY; const N_DELETE: usize = INTENSITY; const N_FLUSHERS: usize = N_THREADS; // items that are expected to always be present at their expected // order, regardless of other inserts or deletes. const INDELIBLE: [&[u8]; 16] = [ &[0u8], &[1u8], &[2u8], &[3u8], &[4u8], &[5u8], &[6u8], &[7u8], &[8u8], &[9u8], &[10u8], &[11u8], &[12u8], &[13u8], &[14u8], &[15u8], ]; let config = Config::tmp() .unwrap() .cache_capacity_bytes(1024 * 1024 * 1024) .flush_every_ms(Some(1)); let t: Db = config.open().unwrap(); let mut threads: Vec>> = vec![]; for tn in 0..N_FLUSHERS { let tree = t.clone(); let thread = thread::Builder::new() .name(format!("t(thread: {} flusher)", tn)) .spawn(move || { tree.flush().unwrap(); Ok(()) }) .expect("should be able to spawn thread"); threads.push(thread); } for item in &INDELIBLE { t.insert(item, item.to_vec())?; } let barrier = Arc::new(Barrier::new(N_FORWARD + N_REVERSE + N_INSERT + N_DELETE)); static I: AtomicUsize = AtomicUsize::new(0); for i in 0..N_FORWARD { let t: Db = t.clone(); let barrier = barrier.clone(); let thread = thread::Builder::new() .name(format!("forward({})", i)) .spawn(move || { I.fetch_add(1, SeqCst); barrier.wait(); for _ in 0..1024 { let expected = INDELIBLE.iter(); let mut keys = t.iter().keys(); for expect in expected { loop { let k = keys.next().unwrap()?; assert!( &*k <= *expect, "witnessed key is {:?} but we expected \ one <= {:?}, so we overshot due to a \ concurrent modification", k, expect, ); if &*k == *expect { break; } } } } I.fetch_sub(1, SeqCst); Ok(()) }) .unwrap(); threads.push(thread); } for i in 0..N_REVERSE { let t: Db = t.clone(); let barrier = barrier.clone(); let thread = thread::Builder::new() .name(format!("reverse({})", i)) .spawn(move || { I.fetch_add(1, SeqCst); barrier.wait(); for _ in 0..1024 { let expected = INDELIBLE.iter().rev(); let mut keys = t.iter().keys().rev(); for expect in expected { loop { if let Some(Ok(k)) = keys.next() { assert!( &*k >= *expect, "witnessed key is {:?} but we expected \ one >= {:?}, so we overshot due to a \ concurrent modification\n{:?}", k, expect, t, ); if &*k == *expect { break; } } else { panic!("undershot key on tree: \n{:?}", t); } } } } I.fetch_sub(1, SeqCst); Ok(()) }) .unwrap(); threads.push(thread); } for i in 0..N_INSERT { let t: Db = t.clone(); let barrier = barrier.clone(); let thread = thread::Builder::new() .name(format!("insert({})", i)) .spawn(move || { barrier.wait(); while I.load(SeqCst) != 0 { for i in 0..(16 * 16 * 8) { let major = i / (16 * 8); let minor = i % 16; let mut base = INDELIBLE[major].to_vec(); base.push(minor as u8); t.insert(base.clone(), base.clone())?; } } Ok(()) }) .unwrap(); threads.push(thread); } for i in 0..N_DELETE { let t: Db = t.clone(); let barrier = barrier.clone(); let thread = thread::Builder::new() .name(format!("deleter({})", i)) .spawn(move || { barrier.wait(); while I.load(SeqCst) != 0 { for i in 0..(16 * 16 * 8) { let major = i / (16 * 8); let minor = i % 16; let mut base = INDELIBLE[major].to_vec(); base.push(minor as u8); t.remove(&base)?; } } Ok(()) }) .unwrap(); threads.push(thread); } for thread in threads.into_iter() { thread.join().expect("thread should not have crashed")?; } t.check_error().expect("Db should have no set error"); dbg!(t.stats()); Ok(()) } /* #[test] #[cfg(not(miri))] // can't create threads fn concurrent_tree_transactions() -> TransactionResult<()> { use std::sync::Barrier; common::setup_logger(); let config = Config::new() .temporary(true) .flush_every_ms(Some(1)) let db: Db = config.open().unwrap(); db.insert(b"k1", b"cats").unwrap(); db.insert(b"k2", b"dogs").unwrap(); let mut threads: Vec>> = vec![]; const N_WRITERS: usize = 30; const N_READERS: usize = 5; const N_SUBSCRIBERS: usize = 5; let barrier = Arc::new(Barrier::new(N_WRITERS + N_READERS + N_SUBSCRIBERS)); for _ in 0..N_WRITERS { let db: Db = db.clone(); let barrier = barrier.clone(); let thread = std::thread::spawn(move || { barrier.wait(); for _ in 0..100 { db.transaction(|db| { let v1 = db.remove(b"k1")?.unwrap(); let v2 = db.remove(b"k2")?.unwrap(); db.insert(b"k1", v2)?; db.insert(b"k2", v1)?; Ok(()) })?; } Ok(()) }); threads.push(thread); } for _ in 0..N_READERS { let db: Db = db.clone(); let barrier = barrier.clone(); let thread = std::thread::spawn(move || { barrier.wait(); for _ in 0..1000 { db.transaction(|db| { let v1 = db.get(b"k1")?.unwrap(); let v2 = db.get(b"k2")?.unwrap(); let mut results = vec![v1, v2]; results.sort(); assert_eq!([&results[0], &results[1]], [b"cats", b"dogs"]); Ok(()) })?; } Ok(()) }); threads.push(thread); } for _ in 0..N_SUBSCRIBERS { let db: Db = db.clone(); let barrier = barrier.clone(); let thread = std::thread::spawn(move || { barrier.wait(); let mut sub = db.watch_prefix(b"k1"); drop(db); while sub.next_timeout(Duration::from_millis(100)).is_ok() {} drop(sub); Ok(()) }); threads.push(thread); } for thread in threads.into_iter() { thread.join().unwrap()?; } let v1 = db.get(b"k1")?.unwrap(); let v2 = db.get(b"k2")?.unwrap(); assert_eq!([v1, v2], [b"cats", b"dogs"]); Ok(()) } #[test] fn tree_flush_in_transaction() { let config = sled::Config::tmp().unwrap(); let db: Db = config.open().unwrap(); let tree = db.open_tree(b"a").unwrap(); tree.transaction::<_, _, sled::transaction::TransactionError>(|tree| { tree.insert(b"k1", b"cats")?; tree.insert(b"k2", b"dogs")?; tree.flush(); Ok(()) }) .unwrap(); } #[test] fn incorrect_multiple_db_transactions() -> TransactionResult<()> { common::setup_logger(); let db1 = Config::tmp().unwrap().flush_every_ms(Some(1)).open().unwrap(); let db2 = Config::tmp().unwrap().flush_every_ms(Some(1)).open().unwrap(); let result: TransactionResult<()> = (&*db1, &*db2).transaction::<_, ()>(|_| Ok(())); assert!(result.is_err()); Ok(()) } #[test] fn many_tree_transactions() -> TransactionResult<()> { common::setup_logger(); let config = Config::tmp().unwrap().flush_every_ms(Some(1)); let db: Db = Arc::new(config.open().unwrap()); let t1 = db.open_tree(b"1")?; let t2 = db.open_tree(b"2")?; let t3 = db.open_tree(b"3")?; let t4 = db.open_tree(b"4")?; let t5 = db.open_tree(b"5")?; let t6 = db.open_tree(b"6")?; let t7 = db.open_tree(b"7")?; let t8 = db.open_tree(b"8")?; let t9 = db.open_tree(b"9")?; (&t1, &t2, &t3, &t4, &t5, &t6, &t7, &t8, &t9).transaction(|trees| { trees.0.insert("hi", "there")?; trees.8.insert("ok", "thanks")?; Ok(()) }) } #[test] fn batch_outside_of_transaction() -> TransactionResult<()> { common::setup_logger(); let config = Config::tmp().unwrap().flush_every_ms(Some(1)); let db: Db = config.open().unwrap(); let t1 = db.open_tree(b"1")?; let mut b1 = Batch::default(); b1.insert(b"k1", b"v1"); b1.insert(b"k2", b"v2"); t1.transaction(|tree| { tree.apply_batch(&b1)?; Ok(()) })?; assert_eq!(t1.get(b"k1")?, Some(b"v1".into())); assert_eq!(t1.get(b"k2")?, Some(b"v2".into())); Ok(()) } */ #[test] fn tree_subdir() { let mut parent_path = std::env::temp_dir(); parent_path.push("test_tree_subdir"); let _ = std::fs::remove_dir_all(&parent_path); let mut path = parent_path.clone(); path.push("test_subdir"); let config = Config::new().path(&path); let t: Db = config.open().unwrap(); t.insert(&[1], vec![1]).unwrap(); drop(t); let config = Config::new().path(&path); let t: Db = config.open().unwrap(); let res = t.get(&*vec![1]); assert_eq!(res.unwrap().unwrap(), vec![1_u8]); drop(t); std::fs::remove_dir_all(&parent_path).unwrap(); } #[test] #[cfg_attr(miri, ignore)] fn tree_small_keys_iterator() { let config = Config::tmp().unwrap().flush_every_ms(Some(1)); let t: Db = config.open().unwrap(); for i in 0..N_PER_THREAD { let k = kv(i); t.insert(&k, k.clone()).unwrap(); } for (i, (k, v)) in t.iter().map(|res| res.unwrap()).enumerate() { let should_be = kv(i); assert_eq!(should_be, &*k); assert_eq!(should_be, &*v); } for (i, (k, v)) in t.iter().map(|res| res.unwrap()).enumerate() { let should_be = kv(i); assert_eq!(should_be, &*k); assert_eq!(should_be, &*v); } let half_way = N_PER_THREAD / 2; let half_key = kv(half_way); let mut tree_scan = t.range(&*half_key..); let r1 = tree_scan.next().unwrap().unwrap(); assert_eq!((r1.0.as_ref(), &*r1.1), (half_key.as_ref(), &*half_key)); let first_key = kv(0); let mut tree_scan = t.range(&*first_key..); let r2 = tree_scan.next().unwrap().unwrap(); assert_eq!((r2.0.as_ref(), &*r2.1), (first_key.as_ref(), &*first_key)); let last_key = kv(N_PER_THREAD - 1); let mut tree_scan = t.range(&*last_key..); let r3 = tree_scan.next().unwrap().unwrap(); assert_eq!((r3.0.as_ref(), &*r3.1), (last_key.as_ref(), &*last_key)); assert!(tree_scan.next().is_none()); } #[test] #[cfg_attr(miri, ignore)] fn tree_big_keys_iterator() { fn kv(i: usize) -> Vec { let k = [(i >> 16) as u8, (i >> 8) as u8, i as u8]; let mut base = vec![0; u8::MAX as usize]; base.extend_from_slice(&k); base } let config = Config::tmp().unwrap().flush_every_ms(Some(1)); let t: Db = config.open().unwrap(); for i in 0..N_PER_THREAD { let k = kv(i); t.insert(&k, k.clone()).unwrap(); } for (i, (k, v)) in t.iter().map(|res| res.unwrap()).enumerate() { let should_be = kv(i); assert_eq!(should_be, &*k, "{:#?}", t); assert_eq!(should_be, &*v); } for (i, (k, v)) in t.iter().map(|res| res.unwrap()).enumerate() { let should_be = kv(i); assert_eq!(should_be, &*k); assert_eq!(should_be, &*v); } let half_way = N_PER_THREAD / 2; let half_key = kv(half_way); let mut tree_scan = t.range(&*half_key..); let r1 = tree_scan.next().unwrap().unwrap(); assert_eq!((r1.0.as_ref(), &*r1.1), (half_key.as_ref(), &*half_key)); let first_key = kv(0); let mut tree_scan = t.range(&*first_key..); let r2 = tree_scan.next().unwrap().unwrap(); assert_eq!((r2.0.as_ref(), &*r2.1), (first_key.as_ref(), &*first_key)); let last_key = kv(N_PER_THREAD - 1); let mut tree_scan = t.range(&*last_key..); let r3 = tree_scan.next().unwrap().unwrap(); assert_eq!((r3.0.as_ref(), &*r3.1), (last_key.as_ref(), &*last_key)); assert!(tree_scan.next().is_none()); } /* #[test] fn tree_subscribers_and_keyspaces() -> io::Result<()> { let config = Config::tmp().unwrap().flush_every_ms(Some(1)); let db: Db = config.open().unwrap(); let t1 = db.open_tree(b"1")?; let mut s1 = t1.watch_prefix(b""); let t2 = db.open_tree(b"2")?; let mut s2 = t2.watch_prefix(b""); t1.insert(b"t1_a", b"t1_a".to_vec())?; t2.insert(b"t2_a", b"t2_a".to_vec())?; assert_eq!(s1.next().unwrap().iter().next().unwrap().1, b"t1_a"); assert_eq!(s2.next().unwrap().iter().next().unwrap().1, b"t2_a"); drop(db); drop(t1); drop(t2); let db: Db = config.open().unwrap(); let t1 = db.open_tree(b"1")?; let mut s1 = t1.watch_prefix(b""); let t2 = db.open_tree(b"2")?; let mut s2 = t2.watch_prefix(b""); assert!(db.is_empty()); assert_eq!(t1.len(), 1); assert_eq!(t2.len(), 1); t1.insert(b"t1_b", b"t1_b".to_vec())?; t2.insert(b"t2_b", b"t2_b".to_vec())?; assert_eq!(s1.next().unwrap().iter().next().unwrap().1, b"t1_b"); assert_eq!(s2.next().unwrap().iter().next().unwrap().1, b"t2_b"); drop(db); drop(t1); drop(t2); let db: Db = config.open().unwrap(); let t1 = db.open_tree(b"1")?; let t2 = db.open_tree(b"2")?; assert!(db.is_empty()); assert_eq!(t1.len(), 2); assert_eq!(t2.len(), 2); db.drop_tree(b"1")?; db.drop_tree(b"2")?; assert_eq!(t1.get(b""), Err(Error::CollectionNotFound)); assert_eq!(t2.get(b""), Err(Error::CollectionNotFound)); let guard = pin(); guard.flush(); drop(guard); drop(db); drop(t1); drop(t2); let db: Db = config.open().unwrap(); let t1 = db.open_tree(b"1")?; let t2 = db.open_tree(b"2")?; assert!(db.is_empty()); assert_eq!(t1.len(), 0); assert_eq!(t2.len(), 0); Ok(()) } */ #[test] fn tree_range() { common::setup_logger(); let config = Config::tmp().unwrap().flush_every_ms(Some(1)); let t: sled::Db<7> = config.open().unwrap(); t.insert(b"0", vec![0]).unwrap(); t.insert(b"1", vec![10]).unwrap(); t.insert(b"2", vec![20]).unwrap(); t.insert(b"3", vec![30]).unwrap(); t.insert(b"4", vec![40]).unwrap(); t.insert(b"5", vec![50]).unwrap(); let start: &[u8] = b"2"; let end: &[u8] = b"4"; let mut r = t.range(start..end); assert_eq!(r.next().unwrap().unwrap().0, b"2"); assert_eq!(r.next().unwrap().unwrap().0, b"3"); assert!(r.next().is_none()); let start = b"2".to_vec(); let end = b"4".to_vec(); let mut r = t.range(start..end).rev(); assert_eq!(r.next().unwrap().unwrap().0, b"3"); assert_eq!(r.next().unwrap().unwrap().0, b"2"); assert!(r.next().is_none()); let start = b"2".to_vec(); let mut r = t.range(start..); assert_eq!(r.next().unwrap().unwrap().0, b"2"); assert_eq!(r.next().unwrap().unwrap().0, b"3"); assert_eq!(r.next().unwrap().unwrap().0, b"4"); assert_eq!(r.next().unwrap().unwrap().0, b"5"); assert!(r.next().is_none()); let start = b"2".to_vec(); let mut r = t.range(..=start).rev(); assert_eq!( r.next().unwrap().unwrap().0, b"2", "failed to find 2 in tree {:?}", t ); assert_eq!(r.next().unwrap().unwrap().0, b"1"); assert_eq!(r.next().unwrap().unwrap().0, b"0"); assert!(r.next().is_none()); } #[test] #[cfg_attr(miri, ignore)] fn recover_tree() { common::setup_logger(); let config = Config::tmp().unwrap().flush_every_ms(Some(1)); let t: sled::Db<7> = config.open().unwrap(); for i in 0..N_PER_THREAD { let k = kv(i); t.insert(&k, k.clone()).unwrap(); } drop(t); let t: sled::Db<7> = config.open().unwrap(); for i in 0..N_PER_THREAD { let k = kv(i as usize); assert_eq!(t.get(&*k).unwrap().unwrap(), k); t.remove(&*k).unwrap(); } drop(t); println!( "---------------- recovering a (hopefully) empty db ----------------------" ); let t: sled::Db<7> = config.open().unwrap(); for i in 0..N_PER_THREAD { let k = kv(i as usize); assert!( t.get(&*k).unwrap().is_none(), "expected key {:?} to have been deleted", i ); } } #[test] #[cfg_attr(miri, ignore)] fn tree_gc() { const FANOUT: usize = 7; common::setup_logger(); let config = Config::tmp().unwrap().flush_every_ms(None); let t: sled::Db = config.open().unwrap(); for i in 0..N { let k = kv(i); t.insert(&k, k.clone()).unwrap(); } for _ in 0..100 { t.flush().unwrap(); } let size_on_disk_after_inserts = t.size_on_disk().unwrap(); for i in 0..N { let k = kv(i); t.insert(&k, k.clone()).unwrap(); } for _ in 0..100 { t.flush().unwrap(); } let size_on_disk_after_rewrites = t.size_on_disk().unwrap(); for i in 0..N { let k = kv(i); assert_eq!(t.get(&*k).unwrap(), Some(k.clone().into()), "{k:?}"); t.remove(&*k).unwrap(); } for _ in 0..100 { t.flush().unwrap(); } let size_on_disk_after_deletes = t.size_on_disk().unwrap(); t.check_error().expect("Db should have no set error"); let stats = t.stats(); dbg!(stats); assert!( stats.cache.heap.allocator.objects_allocated >= (N / FANOUT) as u64, "{stats:?}" ); assert!( stats.cache.heap.allocator.objects_freed >= (stats.cache.heap.allocator.objects_allocated / 2) as u64, "{stats:?}" ); assert!( stats.cache.heap.allocator.heap_slots_allocated >= (N / FANOUT) as u64, "{stats:?}" ); assert!( stats.cache.heap.allocator.heap_slots_freed >= (stats.cache.heap.allocator.heap_slots_allocated / 2) as u64, "{stats:?}" ); let expected_max_size = size_on_disk_after_inserts / 15; assert!( size_on_disk_after_deletes <= expected_max_size, "expected file truncation to take size under {expected_max_size} \ but it was {size_on_disk_after_deletes}" ); // TODO assert!(stats.cache.heap.truncated_file_bytes > 0); println!( "after writing {N} items and removing them, disk size went \ from {}kb after inserts to {}kb after rewriting to {}kb after deletes", size_on_disk_after_inserts / 1024, size_on_disk_after_rewrites / 1024, size_on_disk_after_deletes / 1024, ); } /* #[test] fn create_exclusive() { common::setup_logger(); let path = "create_exclusive_db"; let _ = std::fs::remove_dir_all(path); { let config = Config::new().create_new(true).path(path); config.open().unwrap(); } let config = Config::new().create_new(true).path(path); config.open().unwrap_err(); std::fs::remove_dir_all(path).unwrap(); } */ #[test] fn contains_tree() { let db: Db = Config::tmp().unwrap().flush_every_ms(None).open().unwrap(); let tree_one = db.open_tree("tree 1").unwrap(); let tree_two = db.open_tree("tree 2").unwrap(); drop(tree_one); drop(tree_two); assert_eq!(false, db.contains_tree("tree 3").unwrap()); assert_eq!(true, db.contains_tree("tree 1").unwrap()); assert_eq!(true, db.contains_tree("tree 2").unwrap()); assert!(db.drop_tree("tree 1").unwrap()); assert_eq!(false, db.contains_tree("tree 1").unwrap()); } #[test] #[cfg_attr(miri, ignore)] fn tree_import_export() -> io::Result<()> { common::setup_logger(); let config_1 = Config::tmp().unwrap(); let config_2 = Config::tmp().unwrap(); let db: Db = config_1.open()?; for db_id in 0..N_THREADS { let tree_id = format!("tree_{}", db_id); let tree = db.open_tree(tree_id.as_bytes())?; for i in 0..N_THREADS { let k = kv(i); tree.insert(&k, k.clone()).unwrap(); } } let checksum_a = db.checksum().unwrap(); drop(db); let exporter: Db = config_1.open()?; let importer: Db = config_2.open()?; let export = exporter.export(); importer.import(export); drop(exporter); drop(config_1); drop(importer); let db: Db = config_2.open()?; let checksum_b = db.checksum().unwrap(); assert_eq!(checksum_a, checksum_b); for db_id in 0..N_THREADS { let tree_id = format!("tree_{}", db_id); let tree = db.open_tree(tree_id.as_bytes())?; for i in 0..N_THREADS { let k = kv(i as usize); assert_eq!(tree.get(&*k).unwrap().unwrap(), k); tree.remove(&*k).unwrap(); } } let checksum_c = db.checksum().unwrap(); drop(db); let db: Db = config_2.open()?; for db_id in 0..N_THREADS { let tree_id = format!("tree_{}", db_id); let tree = db.open_tree(tree_id.as_bytes())?; for i in 0..N_THREADS { let k = kv(i as usize); assert_eq!(tree.get(&*k).unwrap(), None); } } let checksum_d = db.checksum().unwrap(); assert_eq!(checksum_c, checksum_d); Ok(()) } #[test] #[cfg_attr(any(target_os = "fuchsia", miri), ignore)] fn quickcheck_tree_matches_btreemap() { let n_tests = if cfg!(windows) { 25 } else { 100 }; QuickCheck::new() .r#gen(Gen::new(100)) .tests(n_tests) .max_tests(n_tests * 10) .quickcheck( prop_tree_matches_btreemap as fn(Vec, bool, i32, usize) -> bool, ); } ================================================ FILE: tests/test_tree_failpoints.rs ================================================ #![cfg(feature = "failpoints")] mod common; use std::collections::BTreeMap; use std::convert::TryInto; use std::sync::Mutex; use quickcheck::{Arbitrary, Gen, QuickCheck, StdGen}; use rand::{Rng, seq::SliceRandom}; use sled::*; const SEGMENT_SIZE: usize = 256; const BATCH_COUNTER_KEY: &[u8] = b"batch_counter"; #[derive(Debug, Clone)] enum Op { Set, Del(u8), Id, Batched(Vec), Restart, Flush, FailPoint(&'static str, u64), } #[derive(Debug, Clone)] enum BatchOp { Set, Del(u8), } impl Arbitrary for BatchOp { fn arbitrary(g: &mut G) -> BatchOp { if g.gen_ratio(1, 2) { BatchOp::Set } else { BatchOp::Del(g.r#gen::()) } } } use self::Op::*; impl Arbitrary for Op { fn arbitrary(g: &mut G) -> Op { let fail_points = vec![ "buffer write", "zero garbage segment", "zero garbage segment post", "zero garbage segment SA", "buffer write post", "write_config bytes", "write_config crc", "write_config fsync", "write_config rename", "write_config dir fsync", "write_config post", "segment initial free zero", "snap write", "snap write len", "snap write crc", "snap write post", "snap write mv", "snap write dir fsync", "snap write mv post", "snap write rm old", "blob blob write", "write_blob write crc", "write_blob write kind_byte", "write_blob write buf", "file truncation", "pwrite", "pwrite partial", ]; if g.gen_bool(1. / 30.) { return FailPoint(fail_points.choose(g).unwrap(), g.r#gen::()); } if g.gen_bool(1. / 10.) { return Restart; } let choice = g.gen_range(0, 5); match choice { 0 => Set, 1 => Del(g.r#gen::()), 2 => Id, 3 => Batched(Arbitrary::arbitrary(g)), 4 => Flush, _ => panic!("impossible choice"), } } fn shrink(&self) -> Box> { match self { Del(ref lid) if *lid > 0 => { Box::new(vec![Del(*lid / 2), Del(*lid - 1)].into_iter()) } Batched(batch_ops) => Box::new(batch_ops.shrink().map(Batched)), FailPoint(name, bitset) => { if bitset.count_ones() > 1 { Box::new( vec![ // clear last failure bit FailPoint( name, bitset ^ (1 << (63 - bitset.leading_zeros())), ), // clear first failure bit FailPoint( name, bitset ^ (1 << bitset.trailing_zeros()), ), // rewind all failure bits by one call FailPoint(name, bitset >> 1), ] .into_iter(), ) } else if *bitset > 1 { Box::new(vec![FailPoint(name, bitset >> 1)].into_iter()) } else { Box::new(vec![].into_iter()) } } _ => Box::new(vec![].into_iter()), } } } fn v(b: &[u8]) -> u16 { if b[0] % 4 != 0 { assert_eq!(b.len(), 2); } (u16::from(b[0]) << 8) + u16::from(b[1]) } fn value_factory(set_counter: u16) -> Vec { let hi = (set_counter >> 8) as u8; let lo = set_counter as u8; if hi % 4 == 0 { let mut val = vec![hi, lo]; val.extend(vec![ lo; hi as usize * SEGMENT_SIZE / 4 * set_counter as usize ]); val } else { vec![hi, lo] } } fn tear_down_failpoints() { sled::fail::reset(); } #[derive(Debug)] struct ReferenceVersion { value: Option, batch: Option, } #[derive(Debug)] struct ReferenceEntry { versions: Vec, crash_epoch: u32, } fn prop_tree_crashes_nicely(ops: Vec, flusher: bool) -> bool { // forces quickcheck to run one thread at a time static M: Lazy, fn() -> Mutex<()>> = Lazy::new(|| Mutex::new(())); let _lock = M.lock().expect("our test lock should not be poisoned"); // clear all failpoints that may be left over from the last run tear_down_failpoints(); let res = std::panic::catch_unwind(|| { run_tree_crashes_nicely(ops.clone(), flusher) }); tear_down_failpoints(); match res { Err(e) => { println!( "failed with {:?} on ops {:?} flusher {}", e, ops, flusher ); false } Ok(res) => { if !res { println!("failed with ops {:?} flusher: {}", ops, flusher); } res } } } fn run_tree_crashes_nicely(ops: Vec, flusher: bool) -> bool { common::setup_logger(); let config = Config::new() .temporary(true) .flush_every_ms(if flusher { Some(1) } else { None }) .cache_capacity(256) .idgen_persist_interval(1) .segment_size(SEGMENT_SIZE); let mut tree = config.open().expect("tree should start"); let mut reference = BTreeMap::new(); let mut max_id: isize = -1; let mut crash_counter = 0; let mut batch_counter: u32 = 1; // For each Set operation, one entry is inserted to the tree with a two-byte // key, and a variable-length value. The key is set to the encoded value // of the `set_counter`, which increments by one with each Set // operation. The value starts with the same two bytes as the // key does, but some values are extended to be many segments long. // // Del operations delete one entry from the tree. Only keys from 0 to 255 // are eligible for deletion. macro_rules! restart { () => { drop(tree); let tree_res = config.global_error().and_then(|_| config.open()); tree = match tree_res { Err(Error::FailPoint) => return true, Err(e) => { println!("could not start database: {}", e); return false; } Ok(tree) => tree, }; let stable_batch = match tree.get(BATCH_COUNTER_KEY) { Ok(Some(value)) => u32::from_be_bytes(value.as_ref().try_into().unwrap()), Ok(None) => 0, Err(Error::FailPoint) => return true, Err(other) => panic!("failed to fetch batch counter after restart: {:?}", other), }; for (_, ref_entry) in reference.iter_mut() { if ref_entry.versions.len() == 1 { continue; } // find the last version from a stable batch, if there is one, // throw away all preceeding versions let committed_find_result = ref_entry.versions.iter().enumerate().rev().find(|(_, ReferenceVersion{ batch, value: _ })| match batch { Some(batch) => *batch <= stable_batch, None => false, }); if let Some((committed_index, _)) = committed_find_result { let tail_versions = ref_entry.versions.split_off(committed_index); let _ = std::mem::replace(&mut ref_entry.versions, tail_versions); } // find the first version from a batch that wasn't committed, // throw away it and all subsequent versions let discarded_find_result = ref_entry.versions.iter().enumerate().find(|(_, ReferenceVersion{ batch, value: _})| match batch { Some(batch) => *batch > stable_batch, None => false, }); if let Some((discarded_index, _)) = discarded_find_result { let _ = ref_entry.versions.split_off(discarded_index); } } let mut ref_iter = reference.iter().map(|(ref rk, ref rv)| (**rk, *rv)); for res in tree.iter() { let actual = match res { Ok((ref tk, _)) => { if tk == BATCH_COUNTER_KEY { continue; } v(tk) } Err(Error::FailPoint) => return true, Err(other) => panic!("failed to iterate over items in tree after restart: {:?}", other), }; // make sure the tree value is in there while let Some((ref_key, ref_expected)) = ref_iter.next() { if ref_expected.versions.iter().all(|version| version.value.is_none()) { // this key should not be present in the tree, skip it and move on to the // next entry in the reference continue; } else if ref_expected.versions.iter().all(|version| version.value.is_some()) { // this key must be present in the tree, check if the keys from both // iterators match if actual != ref_key { panic!( "expected to iterate over key {:?} but got {:?} instead due to it being missing in \n\ntree: {:?}\n\nref: {:?}\n", ref_key, actual, tree, reference, ); } break; } else { // according to the reference, this key could either be present or absent, // depending on whether recent writes were successful. check whether the // keys from the two iterators match, if they do, the key happens to be // present, which is okay, if they don't, and the tree iterator is further // ahead than the reference iterator, the key happens to be absent, so we // skip the entry in the reference. if the reference iterator ever gets // further than the tree iterator, that means the tree has a key that it // should not. if actual == ref_key { // tree and reference agree, we can move on to the next tree item break; } else if ref_key > actual { // we have a bug, the reference iterator should always be <= tree // (this means that the key t was in the tree, but it wasn't in // the reference, so the reference iterator has advanced on past t) println!( "tree verification failed: expected {:?} got {:?}", ref_key, actual ); return false; } else { // we are iterating through the reference until we have an item that // must be present or an uncertain item that matches the tree's real // item anyway continue; } } } } // finish the rest of the reference iterator, and confirm the tree isn't missing // any keys it needs to have at the end while let Some((ref_key, ref_expected)) = ref_iter.next() { if ref_expected.versions.iter().all(|version| version.value.is_some()) { // this key had to be present, but we got to the end of the tree without // seeing it println!("tree verification failed: expected {:?} got end", ref_key); println!("expected: {:?}", ref_expected); println!("tree: {:?}", tree); return false; } } println!("finished verification"); } } macro_rules! fp_crash { ($e:expr) => { match $e { Ok(thing) => thing, Err(Error::FailPoint) => { tear_down_failpoints(); crash_counter += 1; restart!(); continue; } other => { println!("got non-failpoint err: {:?}", other); return false; } } }; } let mut set_counter = 0u16; println!("ops: {:?}", ops); for op in ops.into_iter() { match op { Set => { // update the reference to show that this key could be present. // the next Flush operation will update the // reference again, and require this key to be present // (unless there's a crash before then). let reference_entry = reference .entry(set_counter) .or_insert_with(|| ReferenceEntry { versions: vec![ReferenceVersion { value: None, batch: None, }], crash_epoch: crash_counter, }); reference_entry.versions.push(ReferenceVersion { value: Some(set_counter), batch: None, }); reference_entry.crash_epoch = crash_counter; fp_crash!(tree.insert( &u16::to_be_bytes(set_counter), value_factory(set_counter), )); set_counter += 1; } Del(k) => { // if this key was already set, update the reference to show // that this key could either be present or // absent. the next Flush operation will update the reference // again, and require this key to be absent (unless there's a // crash before then). reference.entry(u16::from(k)).and_modify(|v| { v.versions .push(ReferenceVersion { value: None, batch: None }); v.crash_epoch = crash_counter; }); fp_crash!(tree.remove(&*vec![0, k])); } Id => { let id = fp_crash!(tree.generate_id()); assert!( id as isize > max_id, "generated id of {} is not larger \ than previous max id of {}", id, max_id, ); max_id = id as isize; } Batched(batch_ops) => { let mut batch = Batch::default(); batch.insert( BATCH_COUNTER_KEY, batch_counter.to_be_bytes().to_vec(), ); for batch_op in batch_ops { match batch_op { BatchOp::Set => { let reference_entry = reference .entry(set_counter) .or_insert_with(|| ReferenceEntry { versions: vec![ReferenceVersion { value: None, batch: None, }], crash_epoch: crash_counter, }); reference_entry.versions.push(ReferenceVersion { value: Some(set_counter), batch: Some(batch_counter), }); reference_entry.crash_epoch = crash_counter; batch.insert( u16::to_be_bytes(set_counter).to_vec(), value_factory(set_counter), ); set_counter += 1; } BatchOp::Del(k) => { reference.entry(u16::from(k)).and_modify(|v| { v.versions.push(ReferenceVersion { value: None, batch: Some(batch_counter), }); v.crash_epoch = crash_counter; }); batch.remove(u16::to_be_bytes(k.into()).to_vec()); } } } batch_counter += 1; fp_crash!(tree.apply_batch(batch)); } Flush => { fp_crash!(tree.flush()); // once a flush has been successfully completed, recent Set/Del // operations should be durable. go through the // reference, and if a Set/Del operation was done since // the last crash, keep the value for that key corresponding to // the most recent operation, and toss the rest. for (_key, reference_entry) in reference.iter_mut() { if reference_entry.versions.len() > 1 && reference_entry.crash_epoch == crash_counter { let last = std::mem::take(&mut reference_entry.versions) .pop() .unwrap(); reference_entry.versions.push(last); } } } Restart => { restart!(); } FailPoint(fp, bitset) => { sled::fail::set(fp, bitset); } } } true } #[test] #[cfg_attr(any(target_os = "fuchsia", miri), ignore)] fn quickcheck_tree_with_failpoints() { // use fewer tests for travis OSX builds that stall out all the time let mut n_tests = 50; if let Ok(Ok(value)) = std::env::var("QUICKCHECK_TESTS").map(|s| s.parse()) { n_tests = value; } let generator_sz = 100; QuickCheck::new() .r#gen(StdGen::new(rand::rng(), generator_sz)) .tests(n_tests) .quickcheck(prop_tree_crashes_nicely as fn(Vec, bool) -> bool); } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_01() { // postmortem 1: model did not account for proper reasons to fail to start assert!(prop_tree_crashes_nicely( vec![FailPoint("snap write", 0xFFFFFFFFFFFFFFFF), Restart], false, )); } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_02() { // postmortem 1: the system was assuming the happy path across failpoints assert!(prop_tree_crashes_nicely( vec![ FailPoint("buffer write post", 0xFFFFFFFFFFFFFFFF), Set, Set, Restart ], false, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_03() { // postmortem 1: this was a regression that happened because we // chose to eat errors about advancing snapshots, which trigger // log flushes. We should not trigger flushes from snapshots, // but first we need to make sure we are better about detecting // tears, by not also using 0 as a failed flush signifier. assert!(prop_tree_crashes_nicely( vec![Set, Set, Set, Set, Set, Set, Set, Set, Restart,], false, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_04() { // postmortem 1: the test model was not properly accounting for // writes that may-or-may-not be present due to an error. assert!(prop_tree_crashes_nicely( vec![ Set, FailPoint("snap write", 0xFFFFFFFFFFFFFFFF), Del(0), Set, Restart ], false, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_05() { // postmortem 1: assert!(prop_tree_crashes_nicely( vec![ Set, FailPoint("snap write mv post", 0xFFFFFFFFFFFFFFFF), Set, FailPoint("snap write", 0xFFFFFFFFFFFFFFFF), Set, Set, Set, Restart, FailPoint("zero segment", 0xFFFFFFFFFFFFFFFF), Set, Set, Set, Restart, ], false, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_06() { // postmortem 1: assert!(prop_tree_crashes_nicely( vec![ Set, Del(0), Set, Set, Set, Restart, FailPoint("zero segment post", 0xFFFFFFFFFFFFFFFF), Set, Set, Set, Restart, ], false, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_07() { // postmortem 1: We were crashing because a Segment was // in the SegmentAccountant's to_clean Vec, but it had // no present pages. This can legitimately happen when // a Segment only contains failed log flushes. assert!(prop_tree_crashes_nicely( vec![ Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Del(17), Del(29), Del(246), Del(248), Set, ], false, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_08() { // postmortem 1: we were assuming that deletes would fail if buffer writes // are disabled, but that's not true, because deletes might not cause any // writes if the value was not present. assert!(prop_tree_crashes_nicely( vec![ Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Del(0), FailPoint("buffer write post", 0xFFFFFFFFFFFFFFFF), Del(179), ], false, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_09() { // postmortem 1: recovery was not properly accounting for // ordering issues around allocation and freeing of pages. assert!(prop_tree_crashes_nicely( vec![ Set, Restart, Del(110), Del(0), Set, Restart, Set, Del(255), Set, Set, Set, Set, Set, Del(38), Set, Set, Del(253), Set, Restart, Set, Del(19), Set, Del(118), Set, Set, Set, Set, Set, Del(151), Set, Set, Del(201), Set, Restart, Set, Set, Del(17), Set, Set, Set, Del(230), Set, Restart, ], true, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_10() { // expected to iterate over 50 but got 49 instead // postmortem 1: assert!(prop_tree_crashes_nicely( vec![ Del(175), Del(19), Restart, Del(155), Del(111), Set, Del(4), Set, Set, Set, Set, Restart, Del(94), Set, Del(83), Del(181), Del(218), Set, Set, Del(60), Del(248), Set, Set, Set, Del(167), Del(180), Del(180), Set, Restart, Del(14), Set, Set, Del(156), Del(29), Del(190), Set, Set, Del(245), Set, Del(231), Del(95), Set, Restart, Set, Del(189), Set, Restart, Set, Del(249), Set, Set, Del(110), Del(75), Set, Restart, Del(156), Del(140), Del(101), Del(45), Del(115), Del(162), Set, Set, Del(192), Del(31), Del(224), Set, Del(84), Del(6), Set, Del(191), Set, Set, Set, Del(86), Del(143), Del(168), Del(175), Set, Restart, Set, Set, Set, Set, Set, Restart, Del(14), Set, Set, Set, Set, Set, Set, Del(60), Set, Del(115), Restart, Set, Del(203), Del(12), Del(134), Del(118), Del(26), Del(161), Set, Del(6), Del(23), Set, Del(122), Del(251), Set, Restart, Set, Set, Del(252), Del(88), Set, Del(140), Del(164), Del(203), Del(165), Set, Set, Restart, Del(0), Set, Del(146), Del(83), Restart, Del(0), Set, Del(55), Set, Set, Del(89), Set, Set, Del(105), Restart, Set, Restart, Del(145), Set, Del(17), Del(123), Set, Del(203), Set, Set, Set, Set, Del(192), Del(58), Restart, Set, Restart, Set, Restart, Set, Del(142), Set, Del(220), Del(185), Set, Del(86), Set, Set, Del(123), Set, Restart, Del(56), Del(191), Set, Set, Set, Set, Set, Del(123), Set, Set, Set, Restart, Del(20), Del(47), Del(207), Del(45), Set, Set, Set, Del(83), Set, Del(92), Del(117), Set, Set, Restart, Del(241), Set, Del(49), Set, ], false, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_11() { // dupe lsn detected // postmortem 1: assert!(prop_tree_crashes_nicely( vec![ Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Restart, Del(21), Set, Set, FailPoint("buffer write post", 0xFFFFFFFFFFFFFFFF), Set, Set, Restart, ], false, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_12() { // postmortem 1: we were not sorting the recovery state, which // led to divergent state across recoveries. assert!(prop_tree_crashes_nicely( vec![ Set, Del(0), Set, Set, Set, Set, Set, Set, Restart, Set, Set, Set, Restart, ], false, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_13() { // postmortem 1: assert!(prop_tree_crashes_nicely( vec![ Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Del(0), Set, Set, Set, Del(2), Set, Set, Set, Set, Del(1), Del(3), Del(18), Set, Set, Set, Restart, Set, Set, Set, Set, FailPoint("snap write", 0xFFFFFFFFFFFFFFFF), Del(4), ], false, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_14() { // postmortem 1: improper bounds on splits caused a loop to happen assert!(prop_tree_crashes_nicely( vec![ FailPoint("blob blob write", 0xFFFFFFFFFFFFFFFF), Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, ], false, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_15() { // postmortem 1: assert!(prop_tree_crashes_nicely( vec![FailPoint("buffer write", 0xFFFFFFFFFFFFFFFF), Id, Restart, Id], false, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_16() { // postmortem 1: assert!(prop_tree_crashes_nicely( vec![FailPoint("zero garbage segment", 0xFFFFFFFFFFFFFFFF), Id, Id], false, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_17() { // postmortem 1: during recovery we were not properly // filtering replaced pages in segments by the source // segment still assert!(prop_tree_crashes_nicely( vec![ Del(0), Set, Set, Set, Del(3), Id, Id, Set, Id, Id, Del(3), Id, Id, Del(3), Restart, Id, FailPoint("blob blob write", 0xFFFFFFFFFFFFFFFF), Id, Restart, Id, Set, Id, Del(3), Set ], false, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_18() { // postmortem 1: assert!(prop_tree_crashes_nicely( vec![Id, Id, Set, Id, Id, Id, Set, Del(0), Restart, Del(0), Id, Set], false, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_19() { // postmortem 1: assert!(prop_tree_crashes_nicely( vec![ Set, Set, Set, Set, Del(4), Id, Del(4), Id, Id, Set, Set, Set, Set, Set, Id, Set, Set, Del(11), Del(13), Id, Del(122), Del(134), Del(101), Del(81), Set, Del(15), Del(76), Restart, Set, Id, Id, Set, Restart ], false, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_20() { // postmortem 1: failed to filter out segments with // uninitialized segment ID's when creating a segment // iterator. assert!(prop_tree_crashes_nicely( vec![Restart, Set, Set, Del(0), Id, Id, Set, Del(0), Id, Set], false, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_21() { // postmortem 1: assert!(prop_tree_crashes_nicely( vec![ Id, Del(242), Set, Del(172), Id, Del(142), Del(183), Set, Set, Set, Set, Set, Id, Id, Set, Id, Set, Id, Del(187), Set, Id, Set, Id, Del(152), Del(231), Del(45), Del(181), Restart, Id, Id, Id, Id, Id, Set, Del(53), Restart, Set, Del(202), Id, Set, Set, Set, Id, Restart, Del(99), Set, Set, Id, Restart, Del(93), Id, Set, Del(38), Id, Del(158), Del(49), Id, Del(145), Del(35), Set, Del(94), Del(115), Id, Restart, ], false, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_22() { // postmortem 1: assert!(prop_tree_crashes_nicely( vec![Id, FailPoint("buffer write", 0xFFFFFFFFFFFFFFFF), Set, Id], false, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_23() { // postmortem 1: failed to handle allocation failures assert!(prop_tree_crashes_nicely( vec![ Set, FailPoint("blob blob write", 0xFFFFFFFFFFFFFFFF), Set, Set, Set ], false, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_24() { // postmortem 1: was incorrectly setting global // errors, and they were being used-after-free assert!(prop_tree_crashes_nicely( vec![FailPoint("buffer write", 0xFFFFFFFFFFFFFFFF), Id,], false, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_25() { // postmortem 1: after removing segment trailers, we // no longer have the invariant that a write // must be more than one byte assert!(prop_tree_crashes_nicely( vec![ Del(103), Restart, Del(242), Del(125), Restart, Set, Restart, Id, Del(183), Id, FailPoint("snap write crc", 0xFFFFFFFFFFFFFFFF), Del(141), Del(8), Del(188), Set, Set, Restart, Id, Id, Id, Set, Id, Id, Set, Del(65), Del(6), Del(198), Del(57), Id, FailPoint("snap write mv", 0xFFFFFFFFFFFFFFFF), Set, Del(164), Del(43), Del(161), Id, Restart, Set, Id, Id, Set, Set, Restart, Restart, Set, Set, Del(252), Set, Del(111), Id, Del(55) ], false, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_26() { // postmortem 1: after removing segment trailers, we // no longer handled maxed segment recovery properly assert!(prop_tree_crashes_nicely( vec![ Id, Set, Set, Del(167), Del(251), Del(24), Set, Del(111), Id, Del(133), Del(187), Restart, Set, Del(52), Set, Restart, Set, Set, Id, Set, Set, Id, Id, Set, Set, Del(95), Set, Id, Del(59), Del(133), Del(209), Id, Del(89), Id, Set, Del(46), Set, Del(246), Restart, Set, Restart, Restart, Del(28), Set, Del(9), Del(101), Id, Del(73), Del(192), Set, Set, Set, Id, Set, Set, Set, Id, Restart, Del(92), Del(212), Del(215) ], false, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_27() { // postmortem 1: a segment is recovered as empty at recovery, // which prevented its lsn from being known, and when the SA // was recovered it erroneously calculated its lsn as being -1 assert!(prop_tree_crashes_nicely( vec![ Id, Id, Set, Set, Restart, Set, Id, Id, Set, Del(197), Del(148), Restart, Id, Set, Del(165), Set, Set, Set, Set, Id, Del(29), Set, Set, Del(75), Del(170), Restart, Restart, Set ], true, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_28() { // postmortem 1: assert!(prop_tree_crashes_nicely( vec![ Del(61), Id, Del(127), Set, Restart, Del(219), Id, Set, Id, Del(41), Id, Id, Set, Del(227), Set, Del(191), Id, Del(78), Set, Id, Set, Del(123), Restart, Restart, Restart, Id ], true, )) } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_29() { // postmortem 1: the test model was turning uncertain entries // into certain entries even when there was an intervening crash // between the Set and the Flush assert!(prop_tree_crashes_nicely( vec![ FailPoint("buffer write", 0xFFFFFFFFFFFFFFFF), Set, Flush, Restart ], false, )); assert!(prop_tree_crashes_nicely( vec![ Set, Set, Set, FailPoint("snap write mv", 0xFFFFFFFFFFFFFFFF), Set, Flush, Restart ], false, )); } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_30() { // postmortem 1: assert!(prop_tree_crashes_nicely( vec![ Set, FailPoint("buffer write", 0xFFFFFFFFFFFFFFFF), Restart, Flush, Id ], false, )); } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_31() { // postmortem 1: apply_batch_inner drops a RecoveryGuard, which in turn // drops a Reservation, and Reservation's drop implementation flushes // itself and unwraps the Result returned, which has the FailPoint error // in it for _ in 0..10 { assert!(prop_tree_crashes_nicely( vec![ Del(0), FailPoint("snap write", 0xFFFFFFFFFFFFFFFF), Batched(vec![]) ], true, )); } } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_32() { // postmortem 1: for _ in 0..10 { assert!(prop_tree_crashes_nicely( vec![Batched(vec![BatchOp::Set, BatchOp::Set]), Restart], false )); } } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_33() { // postmortem 1: assert!(prop_tree_crashes_nicely( vec![ Batched(vec![ BatchOp::Set, BatchOp::Set, BatchOp::Del(85), BatchOp::Set, BatchOp::Set, BatchOp::Set, BatchOp::Del(148), BatchOp::Set, BatchOp::Set ]), Restart, Batched(vec![ BatchOp::Del(255), BatchOp::Del(42), BatchOp::Del(150), BatchOp::Del(16), BatchOp::Set, BatchOp::Set, BatchOp::Set, BatchOp::Set, BatchOp::Set, BatchOp::Del(111), BatchOp::Del(65), BatchOp::Del(102), BatchOp::Del(99), BatchOp::Del(25), BatchOp::Del(156), BatchOp::Set, BatchOp::Set, BatchOp::Set, BatchOp::Del(73), BatchOp::Set, BatchOp::Set, BatchOp::Set, BatchOp::Set, BatchOp::Del(238), BatchOp::Del(211), BatchOp::Del(14), BatchOp::Del(7), BatchOp::Del(137), BatchOp::Del(115), BatchOp::Del(91), BatchOp::Set, BatchOp::Del(172), BatchOp::Del(49), BatchOp::Del(152), BatchOp::Set, BatchOp::Del(189), BatchOp::Set, BatchOp::Del(37), BatchOp::Set, BatchOp::Set, BatchOp::Del(96), BatchOp::Set, BatchOp::Set, BatchOp::Del(159), BatchOp::Del(126) ]) ], false )); } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_34() { // postmortem 1: the implementation of make_durable was not properly // exiting the function when local durability was detected use BatchOp::*; assert!(prop_tree_crashes_nicely( vec![Batched(vec![ Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, ])], false )); } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_35() { // postmortem 1: use BatchOp::*; for _ in 0..50 { assert!(prop_tree_crashes_nicely( vec![ Batched(vec![Del(106), Set, Del(32), Del(149), Set]), Flush, Batched(vec![Del(136), Set, Set, Del(61), Set, Del(202)]), Flush, Batched(vec![Del(106), Set, Del(32), Del(149), Set]), Flush, Batched(vec![Del(136), Set, Set, Del(61), Set, Del(202)]), Flush, Batched(vec![Del(106), Set, Del(32), Del(149), Set]), Flush, Batched(vec![Del(136), Set, Set, Del(61), Set, Del(202)]), Flush, ], true )); } } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_36() { // postmortem 1: in `Tree::attempt_fmt` a result from the pagecache // was asserted on rather than propagated, which caused failpoints // to turn into panics. use BatchOp::*; for _ in 0..50 { assert!(prop_tree_crashes_nicely( vec![ Op::Batched(vec![ Set, Set, Del(203), Set, Del(14), Set, Set, Set, Del(209), Set, Set, Set, Set, Set ]), Op::Set, Op::Restart, Op::FailPoint("buffer write post", 17420268517488604084), Op::Restart ], true )) } } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_37() { // postmortem 1: global errors were not being properly set use BatchOp::*; for _ in 0..100 { assert!(prop_tree_crashes_nicely( vec![ Op::Batched(vec![Set, Set, Set, Set, Set, Set, Set]), Op::FailPoint("pwrite", 13605093379298630254), Op::Restart, ], false )) } } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_38() { // postmortem 1: global errors were not being properly set use BatchOp::*; for _ in 0..100 { assert!(prop_tree_crashes_nicely( vec![ Op::Batched(vec![ Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, Set, ]), Op::FailPoint("pwrite partial", 18422008228777642734), Op::Set, ], false )) } } #[test] #[cfg_attr(miri, ignore)] fn failpoints_bug_39() { // postmortem 1: use BatchOp::*; for i in 0..100 { assert!(prop_tree_crashes_nicely( vec![Op::Batched(vec![Set; i % 50]), Op::Restart], true )) } } ================================================ FILE: tests/tree/mod.rs ================================================ use std::{collections::BTreeMap, convert::TryInto, fmt, panic}; use quickcheck::{Arbitrary, Gen}; use rand_distr::{Distribution, Gamma}; use sled::{Config, Db as SledDb, InlineArray}; type Db = SledDb<3>; #[derive(Clone, Ord, PartialOrd, Eq, PartialEq)] pub struct Key(pub Vec); impl fmt::Debug for Key { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if !self.0.is_empty() { write!( f, "Key(vec![{}; {}])", self.0.first().copied().unwrap_or(0), self.0.len() ) } else { write!(f, "Key(vec!{:?})", self.0) } } } fn range(g: &mut Gen, min_inclusive: usize, max_exclusive: usize) -> usize { assert!(max_exclusive > min_inclusive); let range = max_exclusive - min_inclusive; let generated = usize::arbitrary(g) % range; min_inclusive + generated } impl Arbitrary for Key { #![allow(clippy::cast_possible_truncation)] #![allow(clippy::cast_precision_loss)] #![allow(clippy::cast_sign_loss)] fn arbitrary(g: &mut Gen) -> Self { if bool::arbitrary(g) { let gs = g.size(); let gamma = Gamma::new(0.3, gs as f64).unwrap(); let v = gamma.sample(&mut rand::rng()); let len = if v > 3000.0 { 10000 } else { (v % 300.) as usize }; let space = range(g, 0, gs) + 1; let inner = (0..len).map(|_| range(g, 0, space) as u8).collect(); Self(inner) } else { let len = range(g, 0, 2); let mut inner = vec![]; for _ in 0..len { inner.push(u8::arbitrary(g)); } Self(inner) } } fn shrink(&self) -> Box> { // we only want to shrink on length, not byte values Box::new( self.0 .len() .shrink() .zip(std::iter::repeat(self.0.clone())) .map(|(len, underlying)| Self(underlying[..len].to_vec())), ) } } #[derive(Debug, Clone)] pub enum Op { Set(Key, u8), // Merge(Key, u8), Get(Key), GetLt(Key), GetGt(Key), Del(Key), Cas(Key, u8, u8), Scan(Key, isize), Restart, } use self::Op::*; impl Arbitrary for Op { fn arbitrary(g: &mut Gen) -> Self { if range(g, 0, 10) == 0 { return Restart; } let choice = range(g, 0, 7); match choice { 0 => Set(Key::arbitrary(g), u8::arbitrary(g)), 1 => Get(Key::arbitrary(g)), 2 => GetLt(Key::arbitrary(g)), 3 => GetGt(Key::arbitrary(g)), 4 => Del(Key::arbitrary(g)), 5 => Cas(Key::arbitrary(g), u8::arbitrary(g), u8::arbitrary(g)), 6 => Scan(Key::arbitrary(g), range(g, 0, 80) as isize - 40), //7 => Merge(Key::arbitrary(g), u8::arbitrary(g)), _ => panic!("impossible choice"), } } fn shrink(&self) -> Box> { match *self { Set(ref k, v) => Box::new(k.shrink().map(move |sk| Set(sk, v))), /* Merge(ref k, v) => Box::new( k.shrink() .flat_map(move |k| vec![Set(k.clone(), v), Merge(k, v)]), ), */ Get(ref k) => Box::new(k.shrink().map(Get)), GetLt(ref k) => Box::new(k.shrink().map(GetLt)), GetGt(ref k) => Box::new(k.shrink().map(GetGt)), Cas(ref k, old, new) => { Box::new(k.shrink().map(move |k| Cas(k, old, new))) } Scan(ref k, len) => Box::new(k.shrink().map(move |k| Scan(k, len))), Del(ref k) => Box::new(k.shrink().map(Del)), Restart => Box::new(vec![].into_iter()), } } } fn bytes_to_u16(v: &[u8]) -> u16 { assert_eq!(v.len(), 2); (u16::from(v[0]) << 8) + u16::from(v[1]) } fn u16_to_bytes(u: u16) -> Vec { u.to_be_bytes().to_vec() } /* // just adds up values as if they were u16's fn merge_operator( _k: &[u8], old: Option<&[u8]>, to_merge: &[u8], ) -> Option> { let base = old.unwrap_or(&[0, 0]); let base_n = bytes_to_u16(base); let new_n = base_n + u16::from(to_merge[0]); let ret = u16_to_bytes(new_n); Some(ret) } */ pub fn prop_tree_matches_btreemap( ops: Vec, flusher: bool, compression_level: i32, cache_size: usize, ) -> bool { if let Err(e) = prop_tree_matches_btreemap_inner( ops, flusher, compression_level, cache_size, ) { eprintln!("hit error while running quickcheck on tree: {:?}", e); false } else { true } } fn prop_tree_matches_btreemap_inner( ops: Vec, flusher: bool, compression: i32, cache_size: usize, ) -> std::io::Result<()> { use self::*; super::common::setup_logger(); let config = Config::tmp()? .zstd_compression_level(compression) .flush_every_ms(if flusher { Some(1) } else { None }) .cache_capacity_bytes(cache_size); let mut tree: Db = config.open().unwrap(); //tree.set_merge_operator(merge_operator); let mut reference: BTreeMap = BTreeMap::new(); for op in ops { match op { Set(k, v) => { let old_actual = tree.insert(&k.0, vec![0, v]).unwrap(); let old_reference = reference.insert(k.clone(), u16::from(v)); assert_eq!( old_actual.map(|v| bytes_to_u16(&*v)), old_reference, "when setting key {:?}, expected old returned value to be {:?}\n{:?}", k, old_reference, tree ); } /* Merge(k, v) => { tree.merge(&k.0, vec![v]).unwrap(); let entry = reference.entry(k).or_insert(0_u16); *entry += u16::from(v); } */ Get(k) => { let res1 = tree.get(&*k.0).unwrap().map(|v| bytes_to_u16(&*v)); let res2 = reference.get(&k).cloned(); assert_eq!(res1, res2); } GetLt(k) => { let res1 = tree.get_lt(&*k.0).unwrap().map(|v| v.0); let res2 = reference .iter() .rev() .find(|(key, _)| **key < k) .map(|(k, _v)| InlineArray::from(&*k.0)); assert_eq!( res1, res2, "get_lt({:?}) should have returned {:?} \ but it returned {:?} instead. \ \n Db: {:?}", k, res2, res1, tree ); } GetGt(k) => { let res1 = tree.get_gt(&*k.0).unwrap().map(|v| v.0); let res2 = reference .iter() .find(|(key, _)| **key > k) .map(|(k, _v)| InlineArray::from(&*k.0)); assert_eq!( res1, res2, "get_gt({:?}) expected {:?} in tree {:?}", k, res2, tree ); } Del(k) => { tree.remove(&*k.0).unwrap(); reference.remove(&k); } Cas(k, old, new) => { let tree_old = tree.get(&*k.0).unwrap(); if let Some(old_tree) = tree_old { if old_tree == *vec![0, old] { tree.insert(&k.0, vec![0, new]).unwrap(); } } let ref_old = reference.get(&k).cloned(); if ref_old == Some(u16::from(old)) { reference.insert(k, u16::from(new)); } } Scan(k, len) => { if len > 0 { let mut tree_iter = tree .range(&*k.0..) .take(len.abs().try_into().unwrap()) .map(Result::unwrap); let ref_iter = reference .iter() .filter(|&(rk, _rv)| *rk >= k) .take(len.abs().try_into().unwrap()) .map(|(rk, rv)| (rk.0.clone(), *rv)); for r in ref_iter { let tree_next = tree_iter .next() .expect("iterator incorrectly stopped early"); let lhs = (tree_next.0, &*tree_next.1); let rhs = (r.0.clone(), &*u16_to_bytes(r.1)); assert_eq!( (lhs.0.as_ref(), lhs.1), (rhs.0.as_ref(), rhs.1), "expected {:?} while iterating from {:?} on tree: {:?}", rhs, k, tree ); } assert!(tree_iter.next().is_none()); } else { let mut tree_iter = tree .range(&*k.0..) .rev() .take(len.abs().try_into().unwrap()) .map(Result::unwrap); let ref_iter = reference .iter() .rev() .filter(|&(rk, _rv)| *rk >= k) .take(len.abs().try_into().unwrap()) .map(|(rk, rv)| (rk.0.clone(), *rv)); for r in ref_iter { let tree_next = tree_iter.next().unwrap(); let lhs = (tree_next.0, &*tree_next.1); let rhs = (r.0.clone(), &*u16_to_bytes(r.1)); assert_eq!( (lhs.0.as_ref(), lhs.1), (rhs.0.as_ref(), rhs.1), "expected {:?} while reverse iterating from {:?} on tree: {:?}", rhs, k, tree ); } assert!(tree_iter.next().is_none()); } } Restart => { drop(tree); tree = config.open().unwrap(); //tree.set_merge_operator(merge_operator); } } if let Err(e) = tree.check_error() { eprintln!("quickcheck test encountered error: {:?}", e); return Err(e); } } let _ = std::fs::remove_dir_all(config.path); tree.check_error() }