chadtmiller.com/monolith
An atproto PDS
0
0
The store benchmark: reads, sizes and the firehose, RocksDB and fjall
.knotless/workflows/store-bench.yml+7−3
| @@ -1,7 +1,8 @@ | ||
# The store benchmark (bench/store/README.md), as `just store-bench` runs | ||
# it: the server's logs beside SQLite under the same commits, a log | ||
# replayed, and the server's start and memory by the number of accounts in | ||
# its service log. Its log is the tables, for bench/store/RESULTS.md. On a | ||
# it: the server's logs and tables beside SQLite, RocksDB and fjall under | ||
# the same commits (writes, a log and a firehose replayed, reads, sizes), | ||
# and the server's start and memory by the number of accounts in its | ||
# service log. Its log is the tables, for bench/store/RESULTS.md. On a | ||
# pull that changes the benchmark, or the formats it writes itself: a log's | ||
# frames (crates/pds-store), an account's commit frames and the service | ||
# log's entries (the server's log.rs, compact.rs and store.rs), so that a | ||
| @@ -27,5 +28,8 @@ steps: | ||
run: cd web && PATH=/opt/node/bin:$PATH npm run build | ||
- name: build | ||
run: cargo build --release -p pds | ||
# RocksDB's bindings are generated as it builds, which needs libclang. | ||
- name: libclang | ||
run: apt-get update -q && apt-get install -y -q libclang-dev | ||
- name: store-bench | ||
run: PATH=/opt/node/bin:$PATH bench/store/run.sh | ||
bench/store/.cargo/config.tomlnew+14−0
| @@ -0,0 +1,14 @@ | ||
# SQLite built as a server that reads it from many threads would build it, | ||
# not as `rusqlite` bundles it: without the page cache all connections | ||
# share behind one lock (`SQLITE_ENABLE_MEMORY_MANAGEMENT`), and without | ||
# the count of its allocations kept behind another (README.md). | ||
# | ||
# RocksDB built, on macOS, so that its syncs are `F_FULLFSYNC`, as its own | ||
# Makefile and CMake build it there: `librocksdb-sys` leaves | ||
# `HAVE_FULLFSYNC` undefined, and a synced write is then an `fdatasync`, | ||
# or an `fsync` with `use_fsync`, neither of which flushes the drive's | ||
# cache. | ||
[env] | ||
LIBSQLITE3_FLAGS = "-USQLITE_ENABLE_MEMORY_MANAGEMENT -DSQLITE_DEFAULT_MEMSTATUS=0" | ||
CXXFLAGS_aarch64_apple_darwin = "-DHAVE_FULLFSYNC" | ||
CXXFLAGS_x86_64_apple_darwin = "-DHAVE_FULLFSYNC" | ||
bench/store/src/check.rsnew+75−0
| @@ -0,0 +1,75 @@ | ||
//! The check a frame or a table's block carries, four ways: the first 8 | ||
//! bytes of SHA-256, as `pds-store` computes it, and what could stand in | ||
//! its place: CRC32C, XXH3-64, and the first 8 bytes of BLAKE3. Each is | ||
//! over the same bytes; only SHA-256 and BLAKE3 withstand someone who | ||
//! means to forge one, and CRC32C is 4 bytes of the 8. | ||
| ||
use sha2::{Digest, Sha256}; | ||
| ||
#[derive(Clone, Copy, PartialEq)] | ||
pub enum Check { | ||
Sha256, | ||
Crc32c, | ||
Xxh3, | ||
Blake3, | ||
} | ||
| ||
impl Check { | ||
pub const ALL: [Check; 4] = [Check::Sha256, Check::Crc32c, Check::Xxh3, Check::Blake3]; | ||
| ||
pub fn name(self) -> &'static str { | ||
match self { | ||
Check::Sha256 => "SHA-256", | ||
Check::Crc32c => "CRC32C", | ||
Check::Xxh3 => "XXH3-64", | ||
Check::Blake3 => "BLAKE3", | ||
} | ||
} | ||
| ||
/// The check named `name`, as `name` gives it or in lower case. | ||
pub fn named(name: &str) -> Option<Check> { | ||
Check::ALL | ||
.into_iter() | ||
.find(|c| c.name().eq_ignore_ascii_case(name)) | ||
} | ||
| ||
/// The check of a table's block: of its bytes. | ||
pub fn of(self, bytes: &[u8]) -> [u8; 8] { | ||
match self { | ||
Check::Sha256 => Sha256::digest(bytes)[..8].try_into().expect("8 bytes"), | ||
Check::Crc32c => u64::from(crc32c::crc32c(bytes)).to_le_bytes(), | ||
Check::Xxh3 => xxhash_rust::xxh3::xxh3_64(bytes).to_le_bytes(), | ||
Check::Blake3 => blake3::hash(bytes).as_bytes()[..8] | ||
.try_into() | ||
.expect("8 bytes"), | ||
} | ||
} | ||
| ||
/// The check of a frame: of its payload's length, as the 4 bytes its | ||
/// header has, and its payload. | ||
pub fn of_frame(self, payload: &[u8]) -> [u8; 8] { | ||
let len = (payload.len() as u32).to_le_bytes(); | ||
match self { | ||
Check::Sha256 => { | ||
let mut h = Sha256::new(); | ||
h.update(len); | ||
h.update(payload); | ||
h.finalize()[..8].try_into().expect("8 bytes") | ||
} | ||
Check::Crc32c => { | ||
u64::from(crc32c::crc32c_append(crc32c::crc32c(&len), payload)).to_le_bytes() | ||
} | ||
// The length is the seed: one pass over the payload. | ||
Check::Xxh3 => { | ||
xxhash_rust::xxh3::xxh3_64_with_seed(payload, u64::from(u32::from_le_bytes(len))) | ||
.to_le_bytes() | ||
} | ||
Check::Blake3 => { | ||
let mut h = blake3::Hasher::new(); | ||
h.update(&len); | ||
h.update(payload); | ||
h.finalize().as_bytes()[..8].try_into().expect("8 bytes") | ||
} | ||
} | ||
} | ||
} | ||
bench/store/src/data.rsnew+671−0
671 lines changed: not loaded until asked for.
bench/store/src/firehose.rsnew+429−0
429 lines changed: not loaded until asked for.
bench/store/src/fj.rsnew+137−0
| @@ -0,0 +1,137 @@ | ||
//! fjall beside RocksDB, set up the same way: one database with three | ||
//! keyspaces, as fjall calls its column families, `block`, `record` and | ||
//! `event`, under one journal, so that a commit is one batch across the | ||
//! three. Its keys and values are RocksDB's (`rocks`), byte for byte. | ||
//! | ||
//! Blocks are 4 KiB before compression, each with a check, XXH3, computed | ||
//! when it is read from its file, and every keyspace has bloom filters, 10 | ||
//! bits a key but in its first level: fjall's own of all three. As it | ||
//! comes it compresses with LZ4 from the third level down and nothing | ||
//! above; it has no other compression. | ||
| ||
use crate::data::Commit; | ||
use crate::rocks::{event, key, record_value}; | ||
use crate::stores::block_value; | ||
use fjall::config::CompressionPolicy; | ||
use fjall::{CompressionType, Database, Keyspace, KeyspaceCreateOptions, PersistMode}; | ||
use std::path::Path; | ||
use std::time::Duration; | ||
| ||
/// The bytes a block cache may hold where a part gives it no other size: | ||
/// what fjall gives one it makes for itself. | ||
pub const CACHE: u64 = 32 << 20; | ||
| ||
/// How the blocks of a database's files are compressed: with LZ4 below | ||
/// its second level, as fjall does when it is not told, or not at all. | ||
#[derive(Clone, Copy, PartialEq)] | ||
pub enum Pack { | ||
Lz4, | ||
None, | ||
} | ||
| ||
/// Both ways. | ||
pub const PACKS: [Pack; 2] = [Pack::Lz4, Pack::None]; | ||
| ||
impl Pack { | ||
pub fn name(self) -> &'static str { | ||
match self { | ||
Pack::Lz4 => "LZ4 below the second level", | ||
Pack::None => "no compression", | ||
} | ||
} | ||
} | ||
| ||
/// A database and its three keyspaces. | ||
pub struct Store { | ||
pub db: Database, | ||
pub block: Keyspace, | ||
pub record: Keyspace, | ||
pub event: Keyspace, | ||
} | ||
| ||
impl Store { | ||
/// The database at `path`, made if it is not there: its block cache | ||
/// may hold `cache` bytes. `small` is a database for one account: a | ||
/// keyspace's memtable holds 1 MiB before it is written out, where it | ||
/// has fjall's own 64 MiB otherwise, and one thread writes its files | ||
/// and compacts them, where it has up to four. | ||
pub fn open(path: &Path, cache: u64, pack: Pack, small: bool) -> Store { | ||
let buffer = small.then_some(1 << 20); | ||
let mut builder = Database::builder(path).cache_size(cache); | ||
if small { | ||
builder = builder.worker_threads(1); | ||
} | ||
let db = builder.open().expect("a fjall database"); | ||
let keyspace = |name: &str| { | ||
db.keyspace(name, || { | ||
let mut options = KeyspaceCreateOptions::default(); | ||
if pack == Pack::None { | ||
options = options.data_block_compression_policy(CompressionPolicy::all( | ||
CompressionType::None, | ||
)); | ||
} | ||
match buffer { | ||
Some(bytes) => options.max_memtable_size(bytes), | ||
None => options, | ||
} | ||
}) | ||
.expect("a keyspace") | ||
}; | ||
Store { | ||
block: keyspace("block"), | ||
record: keyspace("record"), | ||
event: keyspace("event"), | ||
db, | ||
} | ||
} | ||
| ||
/// What a commit puts in the database, as one batch, as | ||
/// `rocks::commit`: made durable as `mode` says before it is answered, | ||
/// or left in the journal's buffer if it says nothing. | ||
pub fn commit(&self, account: usize, c: &Commit, last: &[Vec<u8>], mode: Option<PersistMode>) { | ||
let mut batch = self.db.batch().durability(mode); | ||
for (cid, b) in &c.blocks { | ||
batch.insert(&self.block, key(account, cid), block_value(&c.rev, b)); | ||
} | ||
for cid in last { | ||
batch.remove(&self.block, key(account, cid)); | ||
} | ||
batch.insert( | ||
&self.record, | ||
key(account, c.path.as_bytes()), | ||
record_value(&c.blocks[1].0, &c.rev), | ||
); | ||
batch.insert( | ||
&self.event, | ||
c.op.to_be_bytes(), | ||
event(account, c.op, &c.event), | ||
); | ||
batch.commit().expect("a commit"); | ||
} | ||
| ||
/// Write what the database holds in memory to its files, and wait | ||
/// until it has no compaction left to do of its own accord. | ||
pub fn settle(&self) { | ||
for keyspace in [&self.block, &self.record, &self.event] { | ||
keyspace.rotate_memtable_and_wait().expect("a flush"); | ||
} | ||
// It says how many compactions are going on and how many are done, | ||
// not whether another is due: idle is none of either for a while. | ||
let (mut done, mut idle) = (self.db.compactions_completed(), 0); | ||
while idle < 50 { | ||
std::thread::sleep(Duration::from_millis(10)); | ||
let now = self.db.compactions_completed(); | ||
if self.db.active_compactions() == 0 && now == done { | ||
idle += 1; | ||
} else { | ||
(done, idle) = (now, 0); | ||
} | ||
} | ||
} | ||
} | ||
| ||
/// The bytes of the files of the database at `path`, its journal left | ||
/// out: that is 64 MiB allocated ahead, whatever it holds. | ||
pub fn disk(path: &Path) -> u64 { | ||
crate::util::dir_bytes(&path.join("keyspaces")) | ||
} | ||
bench/store/src/frame.rsnew+261−0
| @@ -0,0 +1,261 @@ | ||
//! A commit's frame, two ways: the server's, a JSON array with every byte | ||
//! string in hex, and a binary one of the same content; and a reader of a | ||
//! log of the binary ones. | ||
//! | ||
//! A binary frame's payload is its fields in the order the JSON has them, | ||
//! every length and number a varint, every string and byte string its | ||
//! length then its bytes: | ||
//! | ||
//! - `1`, one byte: a commit and its event; | ||
//! - the rev, and the commit's block; | ||
//! - the records put, a count, then each one's path, CID and bytes; | ||
//! - the paths deleted, a count, then each; | ||
//! - the tree's nodes made, a count, then each one's CID and bytes; | ||
//! - the nodes taken out, a count, then each one's CID; | ||
//! - the records whose count of paths changed, a count, then each one's | ||
//! CID and count; | ||
//! - the counts of records and of blocks; | ||
//! - the event's seq, its time, and its frame. | ||
| ||
use crate::check::Check; | ||
use crate::data::Commit; | ||
use pds_store::HEADER; | ||
use serde_json::{Value as Json, json}; | ||
use std::io::{self, Read}; | ||
| ||
/// How a commit's frame is written. | ||
#[derive(Clone, Copy, PartialEq)] | ||
pub enum Encoding { | ||
Json, | ||
Binary, | ||
} | ||
| ||
impl Encoding { | ||
/// The frame of commit `c`, header and all, of an account whose commit | ||
/// before made the nodes `gone`. | ||
pub fn frame(self, c: &Commit, gone: &[Vec<u8>]) -> Vec<u8> { | ||
match self { | ||
Encoding::Json => pds_store::frame(&entries(c, gone)), | ||
Encoding::Binary => binary(c, gone), | ||
} | ||
} | ||
} | ||
| ||
/// When a commit's event was made, as its entry says. | ||
fn time(c: &Commit) -> u64 { | ||
1_700_000_000_000 + c.op | ||
} | ||
| ||
/// The frame the server writes of a commit (`pds-server`'s `log`): its | ||
/// commit entry and its event's, bytes as hex. | ||
pub fn entries(c: &Commit, gone: &[Vec<u8>]) -> Vec<Json> { | ||
vec![ | ||
json!({ | ||
"t": "commit", "rev": c.rev, "head": hex::encode(&c.blocks[0].1), | ||
"puts": [[c.path, hex::encode(&c.blocks[1].0), hex::encode(&c.blocks[1].1)]], | ||
"dels": [], | ||
"tree": c.blocks[2..].iter().map(|(cid, b)| json!([hex::encode(cid), hex::encode(b)])).collect::<Vec<_>>(), | ||
"gone": gone.iter().map(hex::encode).collect::<Vec<_>>(), | ||
"refs": [], "counts": [c.op, c.op * 2], | ||
}), | ||
json!({ "t": "event", "seq": c.op, "time": time(c), "frame": hex::encode(&c.event) }), | ||
] | ||
} | ||
| ||
const COMMIT: u8 = 1; | ||
| ||
fn varint(out: &mut Vec<u8>, mut n: u64) { | ||
while n >= 0x80 { | ||
out.push(n as u8 | 0x80); | ||
n >>= 7; | ||
} | ||
out.push(n as u8); | ||
} | ||
| ||
fn bytes(out: &mut Vec<u8>, b: &[u8]) { | ||
varint(out, b.len() as u64); | ||
out.extend_from_slice(b); | ||
} | ||
| ||
/// The same content as `entries`, as a binary frame. | ||
pub fn binary(c: &Commit, gone: &[Vec<u8>]) -> Vec<u8> { | ||
let size = c | ||
.blocks | ||
.iter() | ||
.map(|(k, b)| k.len() + b.len() + 6) | ||
.sum::<usize>() | ||
+ gone.iter().map(|g| g.len() + 1).sum::<usize>() | ||
+ c.event.len() | ||
+ c.rev.len() | ||
+ c.path.len() | ||
+ 48; | ||
pds_store::frame_of(size, |out| { | ||
out.push(COMMIT); | ||
bytes(out, c.rev.as_bytes()); | ||
bytes(out, &c.blocks[0].1); | ||
varint(out, 1); | ||
bytes(out, c.path.as_bytes()); | ||
bytes(out, &c.blocks[1].0); | ||
bytes(out, &c.blocks[1].1); | ||
varint(out, 0); | ||
varint(out, c.blocks.len() as u64 - 2); | ||
for (cid, b) in &c.blocks[2..] { | ||
bytes(out, cid); | ||
bytes(out, b); | ||
} | ||
varint(out, gone.len() as u64); | ||
for cid in gone { | ||
bytes(out, cid); | ||
} | ||
varint(out, 0); | ||
varint(out, c.op); | ||
varint(out, c.op * 2); | ||
varint(out, c.op); | ||
varint(out, time(c)); | ||
bytes(out, &c.event); | ||
}) | ||
} | ||
| ||
/// A binary payload, read field by field. | ||
struct Walk<'a> { | ||
b: &'a [u8], | ||
at: usize, | ||
} | ||
| ||
impl<'a> Walk<'a> { | ||
fn varint(&mut self) -> Option<u64> { | ||
let mut n = 0u64; | ||
for shift in (0..64).step_by(7) { | ||
let b = *self.b.get(self.at)?; | ||
self.at += 1; | ||
n |= u64::from(b & 0x7f) << shift; | ||
if b & 0x80 == 0 { | ||
return Some(n); | ||
} | ||
} | ||
None | ||
} | ||
| ||
fn bytes(&mut self) -> Option<&'a [u8]> { | ||
let n = self.varint()? as usize; | ||
let b = self.b.get(self.at..self.at.checked_add(n)?)?; | ||
self.at += n; | ||
Some(b) | ||
} | ||
| ||
fn text(&mut self) -> Option<&'a str> { | ||
std::str::from_utf8(self.bytes()?).ok() | ||
} | ||
} | ||
| ||
/// A commit's event, as its frame holds it. | ||
pub struct Event<'a> { | ||
pub seq: u64, | ||
pub frame: &'a [u8], | ||
} | ||
| ||
/// Walk every field of a binary payload, as a replay does, each string | ||
/// checked to be one: its event, or `None` if the payload is not a | ||
/// commit's, whole. | ||
pub fn walk(payload: &[u8]) -> Option<Event<'_>> { | ||
let mut w = Walk { b: payload, at: 0 }; | ||
if *payload.first()? != COMMIT { | ||
return None; | ||
} | ||
w.at = 1; | ||
w.text()?; | ||
w.bytes()?; | ||
for _ in 0..w.varint()? { | ||
w.text()?; | ||
w.bytes()?; | ||
w.bytes()?; | ||
} | ||
for _ in 0..w.varint()? { | ||
w.text()?; | ||
} | ||
for _ in 0..w.varint()? { | ||
w.bytes()?; | ||
w.bytes()?; | ||
} | ||
for _ in 0..w.varint()? { | ||
w.bytes()?; | ||
} | ||
for _ in 0..w.varint()? { | ||
w.bytes()?; | ||
w.varint()?; | ||
} | ||
w.varint()?; | ||
w.varint()?; | ||
let seq = w.varint()?; | ||
w.varint()?; | ||
let frame = w.bytes()?; | ||
(w.at == payload.len()).then_some(Event { seq, frame }) | ||
} | ||
| ||
/// The frames of a log, one at a time, over the header `pds-store` gives | ||
/// every frame (`[len u32 LE][8-byte check][payload]`), through a buffer | ||
/// of the size `pds_store::scan_file` reads with. | ||
pub struct Frames<R> { | ||
r: io::BufReader<R>, | ||
/// The bytes left to read, and those of the whole frames read. | ||
left: u64, | ||
pub pos: u64, | ||
payload: Vec<u8>, | ||
check: Option<Check>, | ||
} | ||
| ||
impl<R: Read> Frames<R> { | ||
/// The frames `r` holds in its next `left` bytes, each one's check | ||
/// computed, as `check`, if there is one. | ||
pub fn new(r: R, left: u64, check: Option<Check>) -> Frames<R> { | ||
Frames { | ||
r: io::BufReader::with_capacity(1 << 16, r), | ||
left, | ||
pos: 0, | ||
payload: Vec::new(), | ||
check, | ||
} | ||
} | ||
| ||
/// The next frame's payload: `None` at the first that is cut short or | ||
/// fails its check, where a log ends. | ||
pub fn next_payload(&mut self) -> Option<&[u8]> { | ||
let mut head = [0u8; HEADER]; | ||
if self.left < HEADER as u64 || self.r.read_exact(&mut head).is_err() { | ||
return None; | ||
} | ||
let len = u64::from(u32::from_le_bytes(head[..4].try_into().expect("4 bytes"))); | ||
if self.left - (HEADER as u64) < len { | ||
return None; | ||
} | ||
self.payload.resize(len as usize, 0); | ||
if self.r.read_exact(&mut self.payload).is_err() | ||
|| self | ||
.check | ||
.is_some_and(|c| head[4..] != c.of_frame(&self.payload)) | ||
{ | ||
return None; | ||
} | ||
self.left -= HEADER as u64 + len; | ||
self.pos += HEADER as u64 + len; | ||
Some(&self.payload) | ||
} | ||
} | ||
| ||
/// The commits in the binary log at `path`, each frame checked and walked. | ||
pub fn count(path: &std::path::Path) -> io::Result<u64> { | ||
let file = std::fs::File::open(path)?; | ||
let size = file.metadata()?.len(); | ||
let mut frames = Frames::new(file, size, Some(Check::Sha256)); | ||
let mut n = 0; | ||
while let Some(p) = frames.next_payload() { | ||
walk(p).ok_or_else(|| { | ||
io::Error::new( | ||
io::ErrorKind::InvalidData, | ||
format!("{}: a frame that is no commit's", path.display()), | ||
) | ||
})?; | ||
n += 1; | ||
} | ||
Ok(n) | ||
} | ||
bench/store/src/main.rs+64−401
465 lines changed: not loaded until asked for.
bench/store/src/reads.rsnew+713−0
713 lines changed: not loaded until asked for.
bench/store/src/rocks.rsnew+198−0
| @@ -0,0 +1,198 @@ | ||
//! RocksDB beside SQLite, set up as a server built on it would set it up: | ||
//! three column families, `block` (an account's blocks by CID), `record` | ||
//! (a path's CID and rev) and `event` (the firehose's frames by seq), | ||
//! which share one log (WAL), so that a commit is one `WriteBatch` across | ||
//! the three and one sync. The families are apart because their keys are: | ||
//! events come in order of seq and are never written again, so their files | ||
//! never overlap and a compaction moves them without rewriting them, and | ||
//! an iterator over them steps over no block; blocks come at random keys | ||
//! and are deleted, and are only ever looked up, so they get a bloom | ||
//! filter; paths are few bytes each and are listed in order. | ||
//! | ||
//! A key of `block` and `record` begins with its account, four bytes big | ||
//! end first, so that one database holds every account's and an account's | ||
//! keys are together. Blocks are 4 KiB before compression and each carries | ||
//! a check, XXH3, computed when it is read from its file: RocksDB's own of | ||
//! both. | ||
| ||
use crate::data::Commit; | ||
use crate::stores::block_value; | ||
use rocksdb::statistics::{Histogram, Ticker}; | ||
use rocksdb::{ | ||
BlockBasedOptions, Cache, ColumnFamily, ColumnFamilyDescriptor, DB, DBCompressionType, Options, | ||
WriteBatch, | ||
}; | ||
use std::path::Path; | ||
| ||
pub const BLOCK: &str = "block"; | ||
pub const RECORD: &str = "record"; | ||
pub const EVENT: &str = "event"; | ||
| ||
/// The bytes a block cache may hold where a part gives it no other size: | ||
/// what RocksDB gives one it makes for itself. | ||
pub const CACHE: usize = 32 << 20; | ||
| ||
/// How the blocks of a database's files are compressed: with Snappy, as | ||
/// RocksDB does when it is not told; not at all; or with zstd. | ||
#[derive(Clone, Copy, PartialEq)] | ||
pub enum Pack { | ||
Snappy, | ||
None, | ||
Zstd, | ||
} | ||
| ||
impl Pack { | ||
pub fn name(self) -> &'static str { | ||
match self { | ||
Pack::Snappy => "Snappy", | ||
Pack::None => "no compression", | ||
Pack::Zstd => "zstd", | ||
} | ||
} | ||
} | ||
| ||
/// The options of a database and of its families: every database opened | ||
/// from one `Setup` shares its block cache, its background threads and | ||
/// its statistics. | ||
pub struct Setup { | ||
options: Options, | ||
/// A family that is looked up by key, and one that is only iterated. | ||
keyed: Options, | ||
ordered: Options, | ||
} | ||
| ||
impl Setup { | ||
/// `cache` is the block cache; `more` is options in RocksDB's own | ||
/// words, as `write_buffer_size=1048576`, or nothing; with `counted`, | ||
/// the databases count their syncs and the bytes they write (`syncs`, | ||
/// `written`), which they do not unless asked. | ||
pub fn new(cache: &Cache, pack: Pack, more: &str, counted: bool) -> Setup { | ||
let mut options = Options::default(); | ||
options.create_if_missing(true); | ||
options.create_missing_column_families(true); | ||
// Its syncs are RocksDB's own: `fdatasync`, as a log's is | ||
// `File::sync_data`; on macOS that is `F_FULLFSYNC`, as this | ||
// workspace builds RocksDB (.cargo/config.toml). | ||
options.increase_parallelism(crate::util::cores() as i32); | ||
if counted { | ||
options.enable_statistics(); | ||
} | ||
match pack { | ||
Pack::Snappy => {} | ||
Pack::None => options.set_compression_type(DBCompressionType::None), | ||
Pack::Zstd => options.set_compression_type(DBCompressionType::Zstd), | ||
} | ||
if !more.is_empty() { | ||
options = options.get_options_from_string(more).expect("options"); | ||
} | ||
let family = |bloom: bool| { | ||
let mut table = BlockBasedOptions::default(); | ||
table.set_block_cache(cache); | ||
if bloom { | ||
table.set_bloom_filter(10.0, false); | ||
} | ||
let mut o = options.clone(); | ||
o.set_block_based_table_factory(&table); | ||
o | ||
}; | ||
Setup { | ||
keyed: family(true), | ||
ordered: family(false), | ||
options, | ||
} | ||
} | ||
| ||
fn families(&self) -> [ColumnFamilyDescriptor; 3] { | ||
[ | ||
ColumnFamilyDescriptor::new(BLOCK, self.keyed.clone()), | ||
ColumnFamilyDescriptor::new(RECORD, self.keyed.clone()), | ||
ColumnFamilyDescriptor::new(EVENT, self.ordered.clone()), | ||
] | ||
} | ||
| ||
/// The database at `path`, made if it is not there. | ||
pub fn open(&self, path: &Path) -> DB { | ||
DB::open_cf_descriptors(&self.options, path, self.families()).expect("a RocksDB") | ||
} | ||
| ||
/// The syncs of a log (WAL) the databases made, and the nanoseconds | ||
/// they took. | ||
pub fn syncs(&self) -> (u64, u64) { | ||
let h = self | ||
.options | ||
.get_histogram_data(Histogram::WalFileSyncMicros); | ||
(h.count(), h.sum() * 1000) | ||
} | ||
| ||
/// The bytes written since the databases were opened: what they were | ||
/// given (keys and values), and what went to their logs, to files | ||
/// written from memory, and to files written by compactions. | ||
pub fn written(&self) -> [u64; 4] { | ||
[ | ||
Ticker::BytesWritten, | ||
Ticker::WalFileBytes, | ||
Ticker::FlushWriteBytes, | ||
Ticker::CompactWriteBytes, | ||
] | ||
.map(|t| self.options.get_ticker_count(t)) | ||
} | ||
} | ||
| ||
/// A family of `db`. | ||
pub fn family<'a>(db: &'a DB, name: &str) -> &'a ColumnFamily { | ||
db.cf_handle(name).expect("the family") | ||
} | ||
| ||
/// A key of `block` or `record`: the account, then the CID or the path. | ||
pub fn key(account: usize, k: &[u8]) -> Vec<u8> { | ||
let mut out = Vec::with_capacity(4 + k.len()); | ||
out.extend_from_slice(&(account as u32).to_be_bytes()); | ||
out.extend_from_slice(k); | ||
out | ||
} | ||
| ||
/// A value of `record`, as a table's `P` value: `[CID length u8][CID][rev]`. | ||
pub fn record_value(cid: &[u8], rev: &str) -> Vec<u8> { | ||
let mut out = Vec::with_capacity(1 + cid.len() + rev.len()); | ||
out.push(cid.len() as u8); | ||
out.extend_from_slice(cid); | ||
out.extend_from_slice(rev.as_bytes()); | ||
out | ||
} | ||
| ||
/// What a commit puts in a database, as one batch: its blocks, the nodes | ||
/// the account's commit before made taken out, its record's path, and its | ||
/// event under its seq, big end first, with its account and time. | ||
pub fn commit(db: &DB, account: usize, c: &Commit, last: &[Vec<u8>]) -> WriteBatch { | ||
let mut batch = WriteBatch::default(); | ||
let block = family(db, BLOCK); | ||
for (cid, b) in &c.blocks { | ||
batch.put_cf(block, key(account, cid), block_value(&c.rev, b)); | ||
} | ||
for cid in last { | ||
batch.delete_cf(block, key(account, cid)); | ||
} | ||
batch.put_cf( | ||
family(db, RECORD), | ||
key(account, c.path.as_bytes()), | ||
record_value(&c.blocks[1].0, &c.rev), | ||
); | ||
let event = event(account, c.op, &c.event); | ||
batch.put_cf(family(db, EVENT), c.op.to_be_bytes(), event); | ||
batch | ||
} | ||
| ||
/// A value of `event`, under its seq: `[account u32 LE][time u64 LE]`, then | ||
/// the frame. | ||
pub fn event(account: usize, seq: u64, frame: &[u8]) -> Vec<u8> { | ||
let mut out = Vec::with_capacity(12 + frame.len()); | ||
out.extend_from_slice(&(account as u32).to_le_bytes()); | ||
out.extend_from_slice(&(1_700_000_000_000u64 + seq).to_le_bytes()); | ||
out.extend_from_slice(frame); | ||
out | ||
} | ||
| ||
/// The frame a value of `event` holds. | ||
pub fn frame(value: &[u8]) -> &[u8] { | ||
&value[12..] | ||
} | ||
bench/store/src/scan.rsnew+147−0
| @@ -0,0 +1,147 @@ | ||
//! How fast a log is replayed: the server's frames of random bytes, then | ||
//! the same realistic commits as the server's frames and as binary ones. | ||
| ||
use crate::check::Check; | ||
use crate::data::{self, SEED}; | ||
use crate::frame::{self, Encoding, Frames}; | ||
use crate::util::{mib, ms, scratch}; | ||
use pds_store::Wal; | ||
use std::fs::File; | ||
use std::io::Write; | ||
use std::path::Path; | ||
use std::time::{Duration, Instant}; | ||
| ||
/// The least of three times of `f`: the file is in the system's cache by | ||
/// the second. | ||
fn best(mut f: impl FnMut()) -> Duration { | ||
(0..3) | ||
.map(|_| { | ||
let at = Instant::now(); | ||
f(); | ||
at.elapsed() | ||
}) | ||
.min() | ||
.expect("three times") | ||
} | ||
| ||
/// Replay the log at `path` as the server does (`pds_store::scan_file`): | ||
/// each frame's check computed and its JSON parsed. | ||
fn json(path: &Path, frames: u64) { | ||
let mut found = 0u64; | ||
pds_store::scan_file(path, |_, _, _| { | ||
found += 1; | ||
Ok(()) | ||
}) | ||
.expect("the log read") | ||
.expect("every frame"); | ||
assert_eq!(found, frames, "every frame replayed"); | ||
} | ||
| ||
/// A log of the server's frames of random bytes, `size` MiB of them, | ||
/// replayed: a row. | ||
fn random(size: u64) { | ||
let dir = scratch("scan"); | ||
let path = dir.join("repo.log"); | ||
let (wal, _) = Wal::open(&path, None).expect("a log"); | ||
let mut op = 0u64; | ||
let mut gone: Vec<Vec<u8>> = Vec::new(); | ||
while wal.len() < size << 20 { | ||
op += 1; | ||
let c = data::random(op); | ||
wal.append(&frame::entries(&c, &gone)).expect("an append"); | ||
gone = data::nodes(&c); | ||
} | ||
wal.wait(wal.written()).expect("a sync"); | ||
drop(wal); | ||
let size = mib(std::fs::metadata(&path).expect("the log").len()); | ||
let took = best(|| json(&path, op)); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
println!( | ||
"| {size:.0} | {op} | {:.0} | {:.0} |", | ||
ms(took), | ||
size / took.as_secs_f64() | ||
); | ||
} | ||
| ||
/// One account's realistic commits, as many as make `size` MiB of the | ||
/// server's frames, in a log of those and in one of binary frames, each | ||
/// replayed: two rows. | ||
fn real(size: u64) { | ||
let dir = scratch("scan"); | ||
let paths = [dir.join("json.log"), dir.join("binary.log")]; | ||
let mut logs = paths | ||
.each_ref() | ||
.map(|p| std::io::BufWriter::new(File::create(p).expect("a log"))); | ||
let mut commits = 0u64; | ||
let mut written = 0u64; | ||
let mut gone: Vec<Vec<u8>> = Vec::new(); | ||
while written < size << 20 { | ||
commits += 1; | ||
let c = data::real(SEED, commits, 0); | ||
let frame = Encoding::Json.frame(&c, &gone); | ||
written += frame.len() as u64; | ||
logs[0].write_all(&frame).expect("an append"); | ||
logs[1] | ||
.write_all(&Encoding::Binary.frame(&c, &gone)) | ||
.expect("an append"); | ||
gone = data::nodes(&c); | ||
} | ||
for log in logs { | ||
log.into_inner() | ||
.expect("a log written") | ||
.sync_all() | ||
.expect("a sync"); | ||
} | ||
let row = |name: &str, path: &Path, took: Duration| { | ||
let bytes = std::fs::metadata(path).expect("the log").len(); | ||
println!( | ||
"| {name} | {commits} | {:.0} | {} | {:.0} | {:.0} | {:.0} |", | ||
mib(bytes), | ||
bytes / commits, | ||
ms(took), | ||
mib(bytes) / took.as_secs_f64(), | ||
commits as f64 / took.as_secs_f64(), | ||
); | ||
}; | ||
row( | ||
"JSON frames (the server's)", | ||
&paths[0], | ||
best(|| json(&paths[0], commits)), | ||
); | ||
row( | ||
"binary frames", | ||
&paths[1], | ||
best(|| { | ||
let file = File::open(&paths[1]).expect("the log"); | ||
let size = file.metadata().expect("the log").len(); | ||
let mut frames = Frames::new(file, size, Some(Check::Sha256)); | ||
let (mut found, mut bytes) = (0u64, 0usize); | ||
while let Some(p) = frames.next_payload() { | ||
bytes += frame::walk(p).expect("a commit's frame").frame.len(); | ||
found += 1; | ||
} | ||
std::hint::black_box(bytes); | ||
assert_eq!(found, commits, "every frame replayed"); | ||
}), | ||
); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
| ||
/// A table of each: logs of the sizes given, in MiB, replayed. | ||
pub fn scan(sizes: &[u64]) { | ||
println!("| log MiB | frames | replay ms | MiB per s |"); | ||
println!("|--:|--:|--:|--:|"); | ||
for &size in sizes { | ||
random(size); | ||
} | ||
println!( | ||
"\nRealistic commits, the same in both logs, as many as make that many MiB of the server's frames.\n" | ||
); | ||
println!( | ||
"| frames | commits | log MiB | bytes a commit | replay ms | MiB per s | commits per s |" | ||
); | ||
println!("|---|--:|--:|--:|--:|--:|--:|"); | ||
for &size in sizes { | ||
real(size); | ||
} | ||
} | ||
bench/store/src/size.rsnew+487−0
487 lines changed: not loaded until asked for.
bench/store/src/stores.rsnew+316−0
| @@ -0,0 +1,316 @@ | ||
//! What accounts hold after their commits (`data::State`), kept four ways | ||
//! for the read and size parts: a table for each account, as the server's | ||
//! checkpoint of one has its blocks and paths; a SQLite database for | ||
//! each; one SQLite database for all; and one RocksDB for all. Each holds | ||
//! the same: every record's block and every tree node's by CID, and every | ||
//! record's CID by its path. None holds an event. | ||
| ||
use crate::data::{self, Block, Record, SEED, State}; | ||
use crate::fj; | ||
use crate::rocks::{self, Pack, Setup}; | ||
use crate::util::{cores, par}; | ||
use crate::write::SCHEMA; | ||
use pds_store::table::TableWriter; | ||
use rocksdb::{Cache, DB, WaitForCompactOptions, WriteBatch}; | ||
use rusqlite::{Connection, params}; | ||
use std::fs::File; | ||
use std::io::BufWriter; | ||
use std::path::{Path, PathBuf}; | ||
| ||
/// A table's key: its section, `B` for a block or `P` for a path, and the | ||
/// CID or path. | ||
pub fn key(section: u8, k: &[u8]) -> Vec<u8> { | ||
let mut out = Vec::with_capacity(1 + k.len()); | ||
out.push(section); | ||
out.extend_from_slice(k); | ||
out | ||
} | ||
| ||
/// A `B` value, as the server writes one: `[refs u32 LE][rev length | ||
/// u8][rev][bytes]`. | ||
pub fn block_value(rev: &str, bytes: &[u8]) -> Vec<u8> { | ||
let mut out = Vec::with_capacity(5 + rev.len() + bytes.len()); | ||
out.extend_from_slice(&1u32.to_le_bytes()); | ||
out.push(rev.len() as u8); | ||
out.extend_from_slice(rev.as_bytes()); | ||
out.extend_from_slice(bytes); | ||
out | ||
} | ||
| ||
/// The bytes of the block a `B` value holds. | ||
pub fn block_bytes(value: &[u8]) -> &[u8] { | ||
&value[5 + usize::from(value[4])..] | ||
} | ||
| ||
/// The CID a `P` value holds: `[CID length u8][CID][rev]`. | ||
pub fn path_cid(value: &[u8]) -> &[u8] { | ||
&value[1..1 + usize::from(value[0])] | ||
} | ||
| ||
pub fn table_path(dir: &Path, account: usize) -> PathBuf { | ||
dir.join(format!("tables/{account}.table")) | ||
} | ||
| ||
pub fn dbs_path(dir: &Path, account: usize) -> PathBuf { | ||
dir.join(format!("dbs/{account}.sqlite")) | ||
} | ||
| ||
pub fn db_path(dir: &Path) -> PathBuf { | ||
dir.join("db/store.sqlite") | ||
} | ||
| ||
/// Write an account's table: its blocks in order of CID, then its paths. | ||
fn write_table(path: &Path, s: &State) { | ||
let mut blocks: Vec<(&[u8], Vec<u8>)> = s | ||
.records | ||
.iter() | ||
.map(|r| (r.cid.as_slice(), block_value(&r.rev, &r.bytes))) | ||
.chain( | ||
s.nodes() | ||
.map(|n| (n.cid.as_slice(), block_value(&n.rev, &n.bytes))), | ||
) | ||
.collect(); | ||
blocks.sort(); | ||
let file = File::create(path).expect("a table"); | ||
let mut w = TableWriter::new( | ||
BufWriter::new(file), | ||
(blocks.len() + s.records.len()) as u64, | ||
); | ||
for (cid, value) in &blocks { | ||
w.add(&key(b'B', cid), value).expect("a block"); | ||
} | ||
for r in &s.records { | ||
let mut value = Vec::with_capacity(1 + r.cid.len() + r.rev.len()); | ||
value.push(r.cid.len() as u8); | ||
value.extend_from_slice(&r.cid); | ||
value.extend_from_slice(r.rev.as_bytes()); | ||
w.add(&key(b'P', r.path.as_bytes()), &value) | ||
.expect("a path"); | ||
} | ||
w.finish().expect("a table written"); | ||
} | ||
| ||
/// A database to load or rewrite: in WAL mode as the write part's, but | ||
/// unsynced, which changes how long the writes take and not what they | ||
/// leave; with `cache` KiB of pages, or SQLite's own 2 MiB. | ||
pub fn open_db(path: &Path, cache: Option<u64>) -> Connection { | ||
let db = Connection::open(path).expect("a database"); | ||
db.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=OFF;") | ||
.expect("pragmas"); | ||
if let Some(kib) = cache { | ||
db.execute_batch(&format!("PRAGMA cache_size=-{kib};")) | ||
.expect("a cache"); | ||
} | ||
db | ||
} | ||
| ||
/// Fold a database's WAL into it and close it, leaving one file. | ||
pub fn close_db(db: Connection) { | ||
db.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(())) | ||
.expect("a checkpoint"); | ||
db.close().map_err(|(_, e)| e).expect("a database closed"); | ||
} | ||
| ||
fn put_record(db: &Connection, account: usize, r: &Record) { | ||
let a = account as i64; | ||
db.prepare_cached("INSERT INTO block(account, cid, rev, bytes) VALUES (?1, ?2, ?3, ?4)") | ||
.expect("a statement") | ||
.execute(params![a, r.cid, r.rev, r.bytes]) | ||
.expect("a block"); | ||
db.prepare_cached( | ||
"INSERT OR REPLACE INTO record(account, path, cid, rev) VALUES (?1, ?2, ?3, ?4)", | ||
) | ||
.expect("a statement") | ||
.execute(params![a, r.path, r.cid, r.rev]) | ||
.expect("a record"); | ||
} | ||
| ||
fn put_node(db: &Connection, account: usize, n: &Block) { | ||
db.prepare_cached("INSERT INTO block(account, cid, rev, bytes) VALUES (?1, ?2, ?3, ?4)") | ||
.expect("a statement") | ||
.execute(params![account as i64, n.cid, n.rev, n.bytes]) | ||
.expect("a block"); | ||
} | ||
| ||
/// Put another record in record `i`'s place, in `s` and in `db`, as a | ||
/// commit does: one transaction that takes out the record's block and each | ||
/// node's from it to the root, and puts in the new ones and the path's row. | ||
pub fn rewrite(db: &Connection, account: usize, s: &mut State, i: usize, version: u64) { | ||
let (gone, made) = s.rewrite(i, version); | ||
db.execute_batch("BEGIN").expect("a transaction"); | ||
{ | ||
let mut out = db | ||
.prepare_cached("DELETE FROM block WHERE account = ?1 AND cid = ?2") | ||
.expect("a statement"); | ||
for cid in &gone { | ||
out.execute(params![account as i64, cid]) | ||
.expect("a block taken out"); | ||
} | ||
} | ||
put_record(db, account, &s.records[i]); | ||
for n in &made { | ||
put_node(db, account, n); | ||
} | ||
db.execute_batch("COMMIT").expect("a commit"); | ||
} | ||
| ||
/// The three stores of `accounts` accounts of `records` records each, | ||
/// under `dir`: `tables/`, `dbs/` and `db/`. The databases get their rows | ||
/// in the order commits would give them, the records as they are made (in | ||
/// the one for all, the accounts' taking turns) and the tree after, and | ||
/// are not vacuumed. | ||
pub fn build(dir: &Path, accounts: usize, records: usize) { | ||
for d in ["tables", "dbs", "db"] { | ||
std::fs::create_dir_all(dir.join(d)).expect("a directory"); | ||
} | ||
let state = |a: usize| State::new(SEED, a as u64, accounts as u64, records); | ||
std::thread::scope(|s| { | ||
s.spawn(|| { | ||
let db = open_db(&db_path(dir), Some(1 << 20)); | ||
db.execute_batch(SCHEMA).expect("a schema"); | ||
db.execute_batch("BEGIN").expect("a transaction"); | ||
for i in 0..records { | ||
for a in 0..accounts { | ||
let op = (i * accounts + a + 1) as u64; | ||
put_record(&db, a, &data::record(SEED, op, a as u64, 0)); | ||
} | ||
} | ||
for a in 0..accounts { | ||
for n in state(a).nodes() { | ||
put_node(&db, a, n); | ||
} | ||
} | ||
db.execute_batch("COMMIT").expect("a commit"); | ||
close_db(db); | ||
}); | ||
par(accounts, cores().saturating_sub(1), |a| { | ||
let s = state(a); | ||
write_table(&table_path(dir, a), &s); | ||
let db = open_db(&dbs_path(dir, a), None); | ||
db.execute_batch(SCHEMA).expect("a schema"); | ||
db.execute_batch("BEGIN").expect("a transaction"); | ||
for r in &s.records { | ||
put_record(&db, a, r); | ||
} | ||
for n in s.nodes() { | ||
put_node(&db, a, n); | ||
} | ||
db.execute_batch("COMMIT").expect("a commit"); | ||
close_db(db); | ||
}); | ||
}); | ||
} | ||
| ||
pub fn rocks_path(dir: &Path, pack: Pack) -> PathBuf { | ||
dir.join(match pack { | ||
Pack::Snappy => "rocks", | ||
Pack::None => "rocks-plain", | ||
Pack::Zstd => "rocks-zstd", | ||
}) | ||
} | ||
| ||
pub fn fjall_path(dir: &Path, pack: fj::Pack) -> PathBuf { | ||
dir.join(match pack { | ||
fj::Pack::Lz4 => "fjall", | ||
fj::Pack::None => "fjall-plain", | ||
}) | ||
} | ||
| ||
/// The rows a RocksDB or a fjall database is given at once as it is loaded. | ||
const BATCH: usize = 1000; | ||
| ||
/// Give each of `dbs` and of `stores` what `accounts` accounts of | ||
/// `records` records hold, in the order the one SQLite database for all | ||
/// gets it: the records as they are made, the accounts' taking turns, and | ||
/// the tree after. Written through each database's log, unsynced. | ||
pub fn load(dbs: &[&DB], stores: &[&fj::Store], accounts: usize, records: usize) { | ||
let mut batches: Vec<WriteBatch> = dbs.iter().map(|_| WriteBatch::default()).collect(); | ||
let mut others: Vec<_> = stores.iter().map(|s| s.db.batch()).collect(); | ||
let mut rows = 0; | ||
let mut put = |family: &str, key: Vec<u8>, value: Vec<u8>, end: bool| { | ||
let full = rows % BATCH == BATCH - 1 || end; | ||
for (db, batch) in dbs.iter().zip(&mut batches) { | ||
batch.put_cf(rocks::family(db, family), &key, &value); | ||
if full { | ||
db.write(std::mem::take(batch)).expect("a batch"); | ||
} | ||
} | ||
for (store, batch) in stores.iter().zip(&mut others) { | ||
let keyspace = if family == rocks::BLOCK { | ||
&store.block | ||
} else { | ||
&store.record | ||
}; | ||
batch.insert(keyspace, key.as_slice(), value.as_slice()); | ||
if full { | ||
let batch = std::mem::replace(batch, store.db.batch()); | ||
batch.commit().expect("a batch"); | ||
} | ||
} | ||
rows += 1; | ||
}; | ||
for i in 0..records { | ||
for a in 0..accounts { | ||
let r = data::record(SEED, (i * accounts + a + 1) as u64, a as u64, 0); | ||
let block = block_value(&r.rev, &r.bytes); | ||
put(rocks::BLOCK, rocks::key(a, &r.cid), block, false); | ||
let at = rocks::record_value(&r.cid, &r.rev); | ||
put(rocks::RECORD, rocks::key(a, r.path.as_bytes()), at, false); | ||
} | ||
} | ||
for a in 0..accounts { | ||
let s = State::new(SEED, a as u64, accounts as u64, records); | ||
let nodes: Vec<&Block> = s.nodes().collect(); | ||
for (i, n) in nodes.iter().enumerate() { | ||
let end = a + 1 == accounts && i + 1 == nodes.len(); | ||
let block = block_value(&n.rev, &n.bytes); | ||
put(rocks::BLOCK, rocks::key(a, &n.cid), block, end); | ||
} | ||
} | ||
} | ||
| ||
/// Write what a RocksDB holds in memory to its files, and wait until it | ||
/// has no compaction left to do of its own accord: as a database that has | ||
/// been let alone a while is. | ||
pub fn settle(db: &DB) { | ||
for family in [rocks::BLOCK, rocks::RECORD, rocks::EVENT] { | ||
db.flush_cf(rocks::family(db, family)).expect("a flush"); | ||
} | ||
db.wait_for_compact(&WaitForCompactOptions::default()) | ||
.expect("the compactions done"); | ||
} | ||
| ||
/// One RocksDB for all at `rocks_path` for each of `packs`, and one fjall | ||
/// database for all at `fjall_path` for each of `others`, loaded and | ||
/// settled: the setups the RocksDB were opened from. | ||
pub fn build_trees( | ||
dir: &Path, | ||
accounts: usize, | ||
records: usize, | ||
packs: &[Pack], | ||
others: &[fj::Pack], | ||
) -> Vec<Setup> { | ||
let cache = Cache::new_lru_cache(rocks::CACHE); | ||
let setups: Vec<Setup> = packs | ||
.iter() | ||
.map(|p| Setup::new(&cache, *p, "", true)) | ||
.collect(); | ||
let dbs: Vec<DB> = setups | ||
.iter() | ||
.zip(packs) | ||
.map(|(s, p)| s.open(&rocks_path(dir, *p))) | ||
.collect(); | ||
let stores: Vec<fj::Store> = others | ||
.iter() | ||
.map(|p| fj::Store::open(&fjall_path(dir, *p), fj::CACHE, *p, false)) | ||
.collect(); | ||
load( | ||
&dbs.iter().collect::<Vec<_>>(), | ||
&stores.iter().collect::<Vec<_>>(), | ||
accounts, | ||
records, | ||
); | ||
dbs.iter().for_each(settle); | ||
stores.iter().for_each(fj::Store::settle); | ||
setups | ||
} | ||
bench/store/src/tables.rsnew+293−0
| @@ -0,0 +1,293 @@ | ||
//! A table's file (`pds_store::table`) taken apart and put together other | ||
//! ways, to measure what the server's does not do: its blocks compressed, | ||
//! its blocks smaller, and a reader with a check of its choice that holds | ||
//! its file open. What these write, `pds_store::table::Table` reads, but | ||
//! for blocks compressed; what the reader reads is any of them. | ||
| ||
use crate::check::Check; | ||
use pds_store::table::MAGIC; | ||
use std::collections::HashMap; | ||
use std::fs::File; | ||
use std::hint::black_box; | ||
use std::os::unix::fs::FileExt; | ||
use std::path::Path; | ||
use std::sync::{Arc, Mutex, PoisonError}; | ||
| ||
const FOOTER: usize = 40; | ||
| ||
fn varint(out: &mut Vec<u8>, mut n: u64) { | ||
while n >= 0x80 { | ||
out.push(n as u8 | 0x80); | ||
n >>= 7; | ||
} | ||
out.push(n as u8); | ||
} | ||
| ||
fn read_varint(bytes: &[u8], pos: &mut usize) -> u64 { | ||
let mut n = 0u64; | ||
for shift in (0..64).step_by(7) { | ||
let b = bytes[*pos]; | ||
*pos += 1; | ||
n |= u64::from(b & 0x7f) << shift; | ||
if b & 0x80 == 0 { | ||
break; | ||
} | ||
} | ||
n | ||
} | ||
| ||
/// The entries of a block, each with where it begins and ends in it. | ||
fn entries(block: &[u8]) -> impl Iterator<Item = (&[u8], &[u8], std::ops::Range<usize>)> { | ||
let mut pos = 0; | ||
std::iter::from_fn(move || { | ||
(pos < block.len()).then(|| { | ||
let start = pos; | ||
let k = read_varint(block, &mut pos) as usize; | ||
let key = &block[pos..pos + k]; | ||
pos += k; | ||
let v = read_varint(block, &mut pos) as usize; | ||
let value = &block[pos..pos + v]; | ||
pos += v; | ||
(key, value, start..pos) | ||
}) | ||
}) | ||
} | ||
| ||
/// One data block's place: its last key, its offset and its length, check | ||
/// and all. | ||
struct Place { | ||
last: Vec<u8>, | ||
offset: u64, | ||
len: usize, | ||
} | ||
| ||
/// The four numbers a table's footer holds: where its index is, the bytes | ||
/// of its index and of its bloom filter, and its entries. | ||
fn footer(tail: &[u8]) -> [u64; 4] { | ||
assert_eq!(&tail[..8], MAGIC, "a table"); | ||
[0, 1, 2, 3].map(|i| u64::from_le_bytes(tail[8 + i * 8..16 + i * 8].try_into().expect("8"))) | ||
} | ||
| ||
/// A table's index: where each data block is. | ||
fn places(index: &[u8]) -> Vec<Place> { | ||
let index = &index[..index.len() - 8]; | ||
let mut out = Vec::new(); | ||
let mut pos = 0; | ||
while pos < index.len() { | ||
let k = read_varint(index, &mut pos) as usize; | ||
let last = index[pos..pos + k].to_vec(); | ||
pos += k; | ||
let offset = read_varint(index, &mut pos); | ||
let len = read_varint(index, &mut pos) as usize; | ||
out.push(Place { last, offset, len }); | ||
} | ||
out | ||
} | ||
| ||
/// A table being put together again: its blocks as they are given, each | ||
/// with SHA-256's check over what is stored, and the index of where they | ||
/// are. | ||
#[derive(Default)] | ||
struct Again { | ||
out: Vec<u8>, | ||
index: Vec<u8>, | ||
} | ||
| ||
impl Again { | ||
fn block(&mut self, last: &[u8], stored: &[u8]) { | ||
varint(&mut self.index, last.len() as u64); | ||
self.index.extend_from_slice(last); | ||
varint(&mut self.index, self.out.len() as u64); | ||
varint(&mut self.index, stored.len() as u64 + 8); | ||
self.out.extend_from_slice(stored); | ||
self.out.extend_from_slice(&Check::Sha256.of(stored)); | ||
} | ||
| ||
/// The file: the blocks, the index, and the bloom filter and count of | ||
/// entries `table` had. | ||
fn finish(mut self, table: &[u8]) -> Vec<u8> { | ||
let [index_at, index_len, bloom_len, count] = footer(&table[table.len() - FOOTER..]); | ||
let blocks = self.out.len() as u64; | ||
let c = Check::Sha256.of(&self.index); | ||
self.index.extend_from_slice(&c); | ||
self.out.extend_from_slice(&self.index); | ||
self.out | ||
.extend_from_slice(&table[(index_at + index_len) as usize..table.len() - FOOTER]); | ||
self.out.extend_from_slice(MAGIC); | ||
for n in [blocks, self.index.len() as u64, bloom_len, count] { | ||
self.out.extend_from_slice(&n.to_le_bytes()); | ||
} | ||
self.out | ||
} | ||
} | ||
| ||
/// The entries of each of a table's data blocks, in order. | ||
fn blocks(table: &[u8]) -> impl Iterator<Item = (Vec<u8>, &[u8])> { | ||
let [index_at, index_len, _, _] = footer(&table[table.len() - FOOTER..]); | ||
places(&table[index_at as usize..(index_at + index_len) as usize]) | ||
.into_iter() | ||
.map(move |p| { | ||
( | ||
p.last, | ||
&table[p.offset as usize..p.offset as usize + p.len - 8], | ||
) | ||
}) | ||
} | ||
| ||
/// The same table with each data block's entries put through `pack`. | ||
pub fn packed(table: &[u8], mut pack: impl FnMut(&[u8]) -> Vec<u8>) -> Vec<u8> { | ||
let mut again = Again::default(); | ||
for (last, block) in blocks(table) { | ||
again.block(&last, &pack(block)); | ||
} | ||
again.finish(table) | ||
} | ||
| ||
/// The same table in blocks of `size` bytes, ended as | ||
/// `pds_store::table::TableWriter` ends its own of 16 KiB. | ||
pub fn reblocked(table: &[u8], size: usize) -> Vec<u8> { | ||
let mut again = Again::default(); | ||
let mut block: Vec<u8> = Vec::with_capacity(size * 2); | ||
let mut last: &[u8] = &[]; | ||
for (_, old) in blocks(table) { | ||
for (key, value, at) in entries(old) { | ||
if !block.is_empty() && block.len() + key.len() + value.len() > size { | ||
again.block(last, &block); | ||
block.clear(); | ||
} | ||
block.extend_from_slice(&old[at]); | ||
last = key; | ||
if block.len() >= size { | ||
again.block(last, &block); | ||
block.clear(); | ||
} | ||
} | ||
} | ||
if !block.is_empty() { | ||
again.block(last, &block); | ||
} | ||
again.finish(table) | ||
} | ||
| ||
/// A table read by this benchmark: its file held open and its index held, | ||
/// no bloom filter, each block read checked with the check of its choice, | ||
/// unpacked if it is stored compressed, and searched. It keeps every block | ||
/// it has read, or none: with none, every read is of a block from the | ||
/// file. | ||
/// | ||
/// The files hold SHA-256's checks. Another check is computed over the | ||
/// same bytes and compared with nothing: what it costs, not what it finds. | ||
pub struct Reader { | ||
file: File, | ||
places: Vec<Place>, | ||
check: Check, | ||
kept: Option<Mutex<HashMap<usize, Arc<[u8]>>>>, | ||
} | ||
| ||
/// What unpacks a table's blocks, if they are stored compressed. | ||
pub type Unpack<'a, 'b> = &'a mut Option<zstd::bulk::Decompressor<'b>>; | ||
| ||
impl Reader { | ||
pub fn open(path: &Path, check: Check, keep: bool) -> Reader { | ||
let file = File::open(path).expect("a table"); | ||
let size = file.metadata().expect("a table").len(); | ||
let mut tail = [0u8; FOOTER]; | ||
file.read_exact_at(&mut tail, size - FOOTER as u64) | ||
.expect("a footer"); | ||
let [index_at, index_len, _, _] = footer(&tail); | ||
let mut index = vec![0u8; index_len as usize]; | ||
file.read_exact_at(&mut index, index_at).expect("an index"); | ||
let r = Reader { | ||
places: places(&index), | ||
file, | ||
check, | ||
kept: keep.then(Mutex::default), | ||
}; | ||
let (body, c) = index.split_at(index.len() - 8); | ||
r.checked(body, c); | ||
r | ||
} | ||
| ||
/// Compute the check of `bytes`, and see that it is `stored` if that | ||
/// is the check the files hold. | ||
fn checked(&self, bytes: &[u8], stored: &[u8]) { | ||
let c = black_box(self.check.of(bytes)); | ||
assert!(self.check != Check::Sha256 || c == stored, "a check"); | ||
} | ||
| ||
/// Block `i`'s entries, read from the file. | ||
fn read(&self, i: usize, unpack: Unpack) -> Vec<u8> { | ||
let p = &self.places[i]; | ||
let mut stored = vec![0u8; p.len]; | ||
self.file | ||
.read_exact_at(&mut stored, p.offset) | ||
.expect("a block"); | ||
let (body, c) = stored.split_at(p.len - 8); | ||
self.checked(body, c); | ||
match unpack { | ||
Some(z) => { | ||
let mut plain = Vec::with_capacity(1 << 16); | ||
z.decompress_to_buffer(body, &mut plain) | ||
.expect("a block unpacked"); | ||
plain | ||
} | ||
None => { | ||
stored.truncate(p.len - 8); | ||
stored | ||
} | ||
} | ||
} | ||
| ||
/// Give `f` block `i`'s entries: those kept, or read now. | ||
fn with<T>(&self, i: usize, unpack: Unpack, f: impl FnOnce(&[u8]) -> T) -> T { | ||
let Some(kept) = &self.kept else { | ||
return f(&self.read(i, unpack)); | ||
}; | ||
let held = kept | ||
.lock() | ||
.unwrap_or_else(PoisonError::into_inner) | ||
.get(&i) | ||
.cloned(); | ||
let block = held.unwrap_or_else(|| { | ||
let block: Arc<[u8]> = self.read(i, unpack).into(); | ||
kept.lock() | ||
.unwrap_or_else(PoisonError::into_inner) | ||
.insert(i, block.clone()); | ||
block | ||
}); | ||
f(&block) | ||
} | ||
| ||
/// The value of `key`, which the table holds. | ||
pub fn get(&self, key: &[u8], unpack: Unpack) -> Vec<u8> { | ||
let i = self.places.partition_point(|p| p.last.as_slice() < key); | ||
self.with(i, unpack, |block| { | ||
entries(block) | ||
.find(|(k, _, _)| *k == key) | ||
.map(|(_, v, _)| v.to_vec()) | ||
.expect("a key the table holds") | ||
}) | ||
} | ||
| ||
/// The first `n` entries from `from` on whose keys begin as it does. | ||
pub fn list(&self, from: &[u8], n: usize) -> Vec<(Vec<u8>, Vec<u8>)> { | ||
let mut out = Vec::with_capacity(n); | ||
let mut i = self.places.partition_point(|p| p.last.as_slice() < from); | ||
while out.len() < n && i < self.places.len() { | ||
let ended = self.with(i, &mut None, |block| { | ||
for (k, v, _) in entries(block).filter(|(k, _, _)| *k >= from) { | ||
if k[0] != from[0] || out.len() == n { | ||
return true; | ||
} | ||
out.push((k.to_vec(), v.to_vec())); | ||
} | ||
false | ||
}); | ||
if ended { | ||
break; | ||
} | ||
i += 1; | ||
} | ||
out | ||
} | ||
} | ||
bench/store/src/util.rsnew+237−0
bench/store/src/write.rsnew+1346−0
1346 lines changed: not loaded until asked for.
bench/store/Cargo.lock+620−3
623 lines changed: not loaded until asked for.
bench/store/Cargo.toml+16−0
bench/store/README.md+468−34
502 lines changed: not loaded until asked for.
bench/store/RESULTS.md+818−73
891 lines changed: not loaded until asked for.