chadtmiller.com/monolith
An atproto PDS
0
0
The logs and tables open at once are a share of the descriptor limit
bench/store/src/reads.rs+13−13
| @@ -10,8 +10,8 @@ use crate::fj; | ||
use crate::rocks::{self, Pack, Setup}; | ||
use crate::stores::{self, block_bytes, key, path_cid}; | ||
use crate::tables::{self, Reader}; | ||
use crate::util::{Rng, at, cores, dir_bytes, mib, par, rss_kib, scratch, us}; | ||
use pds_store::table::{BLOCK, BlockCache, OPEN, Table}; | ||
use crate::util::{Rng, at, cores, dir_bytes, mib, par, rss_kib, scratch, share, us}; | ||
use pds_store::table::{BLOCK, BlockCache, Table}; | ||
use rocksdb::DB; | ||
use rusqlite::{Connection, params}; | ||
use std::collections::HashMap; | ||
| @@ -41,8 +41,8 @@ const LIST: &str = "SELECT r.path, b.bytes FROM record r JOIN block b ON b.accou | ||
enum Store { | ||
/// A table for each account read as the server reads one | ||
/// (`pds_store::table::Table`), through one block cache, which keeps | ||
/// the tables' files open: at most `OPEN` of them, as the server's | ||
/// does, or every one. | ||
/// the tables' files open: at most the server's share of them | ||
/// (`util::share`), or every one. | ||
Tables { | ||
dir: PathBuf, | ||
tables: Vec<OnceLock<Table>>, | ||
| @@ -113,7 +113,7 @@ impl Store { | ||
tables: cells(accounts), | ||
cache: match flag { | ||
"open" => BlockCache::with_open(CACHE, accounts), | ||
_ => BlockCache::new(CACHE), | ||
_ => BlockCache::with_open(CACHE, share()), | ||
}, | ||
}, | ||
("dbs", _) => Store::Dbs { | ||
| @@ -553,12 +553,12 @@ pub fn reads(accounts: usize, records: usize) { | ||
}); | ||
stores::build(&dir, accounts, records); | ||
}); | ||
let share = share(); | ||
let as_the_server = format!( | ||
"a table for each account, as the server reads one, at most {share} of their files open" | ||
); | ||
let stores = [ | ||
( | ||
"tables", | ||
"a table for each account, as the server reads one", | ||
"", | ||
), | ||
("tables", as_the_server.as_str(), ""), | ||
( | ||
"dbs", | ||
"SQLite for each account", | ||
| @@ -659,7 +659,7 @@ pub fn reads(accounts: usize, records: usize) { | ||
}); | ||
let blocks = format!("{} KiB", BLOCK >> 10); | ||
println!( | ||
"\nThe tables read other ways. By `pds_store::table::Table`: as the server reads one (as above), its block cache holding at most {OPEN} of the tables' files open, the least recently read closed to make room and opened again when next read; and with every file held open, which the server does not do. By this benchmark's reader, which holds every file open, keeps the blocks it reads in a map for each table where `Table` has one cache for all, has no bloom filter, and computes the check named over each block it reads (compared with what the file holds for SHA-256 alone). And by that reader from the layout before: the same entries in blocks of 16 KiB, each block's last key whole in the index, the file opened for each block read. The first read of an account is its table opened and a record read.\n" | ||
"\nThe tables read other ways. By `pds_store::table::Table`: as the server reads one (as above), its block cache holding at most {share} of the tables' files open, the server's share of the file descriptors this process may have, the least recently read closed to make room and opened again when next read; and with every file held open, whatever the share. By this benchmark's reader, which holds every file open, keeps the blocks it reads in a map for each table where `Table` has one cache for all, has no bloom filter, and computes the check named over each block it reads (compared with what the file holds for SHA-256 alone). And by that reader from the layout before: the same entries in blocks of 16 KiB, each block's last key whole in the index, the file opened for each block read. The first read of an account is its table opened and a record read.\n" | ||
); | ||
println!( | ||
"| read by | blocks | check | file | a record by path, cold: p50 µs | p99 µs | a listing of {LISTED}, cold: p50 µs | p99 µs | first read of an account: p50 µs | p99 µs | on {THREADS} threads, cold: per s | warm: per s |" | ||
| @@ -679,12 +679,12 @@ pub fn reads(accounts: usize, records: usize) { | ||
); | ||
}; | ||
way( | ||
&format!("`Table`, as the server's | {blocks} | SHA-256 | at most {OPEN} held open"), | ||
&format!("`Table`, as the server's | {blocks} | SHA-256 | at most {share} held open"), | ||
&figures[0], | ||
); | ||
let mut ways = vec![( | ||
"tables+open".to_string(), | ||
format!("`Table`, not as the server's | {blocks} | SHA-256 | all held open"), | ||
format!("`Table`, every file open | {blocks} | SHA-256 | all held open"), | ||
)]; | ||
ways.extend(Check::ALL.map(|c| { | ||
( | ||
bench/store/src/util.rs+12−25
| @@ -187,36 +187,23 @@ impl Drop for Rss { | ||
} | ||
} | ||
| ||
/// Let the process hold a file for each of a few thousand accounts, three | ||
/// for a SQLite database in WAL mode and nine for a RocksDB, where the | ||
/// limit it was started with is lower and may be raised. | ||
/// Let the process hold as many files as it may, as the server does when | ||
/// it starts (`pds_store::files::raise`): one for each of a few thousand | ||
/// accounts, three for a SQLite database in WAL mode and nine for a | ||
/// RocksDB. | ||
pub fn raise_files() { | ||
use rustix::process::{Resource, Rlimit, getrlimit, setrlimit}; | ||
let now = getrlimit(Resource::Nofile); | ||
for want in [65536u64, 16384, 8192] { | ||
if now.current.is_some_and(|c| c >= want) || now.current.is_none() { | ||
return; | ||
} | ||
let want = now.maximum.map_or(want, |m| m.min(want)); | ||
if setrlimit( | ||
Resource::Nofile, | ||
Rlimit { | ||
current: Some(want), | ||
maximum: now.maximum, | ||
}, | ||
) | ||
.is_ok() | ||
{ | ||
return; | ||
} | ||
} | ||
pds_store::files::raise(); | ||
} | ||
| ||
/// The files the process may hold open at once. | ||
pub fn files() -> u64 { | ||
rustix::process::getrlimit(rustix::process::Resource::Nofile) | ||
.current | ||
.unwrap_or(u64::MAX) | ||
pds_store::files::limit().unwrap_or(u64::MAX) | ||
} | ||
| ||
/// The tables' files the server would hold open at once in this process: | ||
/// its share of the files the process may hold. | ||
pub fn share() -> usize { | ||
pds_store::files::share(pds_store::files::limit()) | ||
} | ||
| ||
/// The time `per_cent` of `sorted` are within. | ||
bench/store/Cargo.lock+1−0
| @@ -558,6 +558,7 @@ dependencies = [ | ||
name = "pds-store" | ||
version = "0.1.0" | ||
dependencies = [ | ||
"rustix", | ||
"serde_json", | ||
"sha2", | ||
] | ||
bench/store/Cargo.toml+2−2
| @@ -16,8 +16,8 @@ hex = "0.4" | ||
sha2 = { version = "0.10", features = ["asm"] } | ||
# The size part's compressed blocks. | ||
zstd = "0.13" | ||
# A log's room allocated ahead, and the limit on open files raised. | ||
rustix = { version = "1", features = ["fs", "process"] } | ||
# A log's room allocated ahead. | ||
rustix = { version = "1", features = ["fs"] } | ||
# The checks that could stand in SHA-256's place. | ||
crc32c = "0.6" | ||
xxhash-rust = { version = "0.8", features = ["xxh3"] } | ||
bench/store/README.md+14−9
| @@ -33,9 +33,9 @@ harness's; without a server | ||
at `target/release/pds` (or `PDS_BIN`) the last part is left out, and says | ||
so. The parts before the last take about sixteen minutes on a laptop, at | ||
most 5 GiB under `BENCH_DIR` and 1.5 GiB of memory, and a limit on open | ||
files of 20,000 or more, which the benchmark raises itself where it may: | ||
under a lower one the row of a RocksDB for each of 2000 accounts is left | ||
out, and says so. | ||
files of 20,000 or more: the benchmark raises its limit to the most it is | ||
allowed, as the server does when it starts, and under a lower one the row | ||
of a RocksDB for each of 2000 accounts is left out, and says so. | ||
| ||
On the runner, the `store-bench` workflow runs the same script when the | ||
owner asks, on `main` or a branch (`knotless run rerun | ||
| @@ -291,7 +291,10 @@ them, kept these ways with the same content (`src/stores.rs`): | ||
count and rev, under `P` and a path its record's CID and rev, in data | ||
blocks of 4 KiB; read as the server reads one, with `Table::get` and | ||
`Table::iter` through one `BlockCache` for all, which keeps the blocks | ||
read and holds at most 64 of the tables' files open; | ||
read and holds at most a share of the tables' files open: the share the | ||
server takes of the file descriptors the process may have, a quarter of | ||
them and at most 4096 (`pds_store::files::share`; `spec/LIMITS.md`, | ||
"Open files and threads"), which the row's name says; | ||
- SQLite for each account, the first part's `block` and `record` tables, | ||
one connection each; | ||
- one SQLite for all, a connection for each thread that reads; | ||
| @@ -344,9 +347,10 @@ would keep. Measured: | ||
| ||
The table reads blocks of 4 KiB and computes each one's check, SHA-256, | ||
as it reads it, from a file its block cache holds open: of the 2000 | ||
tables' files at most 64 are open at once, as in the server, the least | ||
recently read closed to make room, so that a read of an account whose | ||
file is not among them opens it again, once for the blocks it then reads. | ||
tables' files at most a share are open at once, as in the server, the | ||
least recently read closed to make room, so that where the share is fewer | ||
than the accounts a read of an account whose file is not among them opens | ||
it again, once for the blocks it then reads. | ||
A read of a block the cache holds asks the bloom filter nothing; one that | ||
must read the file asks it first. SQLite checks nothing and reads 4 KiB | ||
pages from files it holds open. RocksDB reads blocks of 4 KiB before | ||
| @@ -374,8 +378,9 @@ takes its count of allocations from behind another. | ||
| ||
A last table reads the tables cold other ways, to tell what of a cold | ||
read is which choice. By `Table` with every table's file held open | ||
(`BlockCache::with_open`), which the server does not do: what the limit | ||
of 64 open files costs. By this benchmark's reader (`src/tables.rs`) | ||
(`BlockCache::with_open`), whatever the share: what a share fewer than | ||
the accounts costs, and the same as the row before where the share is no | ||
fewer. By this benchmark's reader (`src/tables.rs`) | ||
from the same files, which holds every file open, keeps the blocks it | ||
reads in a map of each table's own, where `Table` has the one cache for | ||
all, has no bloom filter, and computes one of four checks over each | ||
crates/pds-server/src/cache.rs+4−1
| @@ -64,6 +64,8 @@ const TAKEDOWN_COST: u64 = 192; | ||
/// a store needs. | ||
pub(crate) struct Ctx { | ||
pub dir: PathBuf, | ||
/// The accounts' logs, of which at most a share are open at once | ||
/// (`Config::share`). | ||
pub files: Arc<Files>, | ||
pub policy: Policy, | ||
/// The backfill window, in milliseconds. | ||
| @@ -72,7 +74,8 @@ pub(crate) struct Ctx { | ||
pub eager: Arc<Eager>, | ||
pub cache: Cache, | ||
/// The blocks of the stores' tables and logs read from disk, and of | ||
/// the service checkpoint's (`directory`), shared. | ||
/// the service checkpoint's (`directory`), shared, and the tables' | ||
/// files, of which at most a share are open at once. | ||
pub blocks: Arc<pds_store::table::BlockCache>, | ||
/// While the server starts: a store loaded then with no commit gets | ||
/// its first from the start, once it knows where seqs go on from. | ||
crates/pds-server/src/checkpoint.rs+7−7
| @@ -48,8 +48,8 @@ | ||
//! each record whose count of paths changed, and each record put, with its | ||
//! CID. Bytes are read from the log's frames, or the table, as they are | ||
//! asked for, through the block cache all the stores share (`BlockCache`), | ||
//! which keeps the files of the tables read last open, at most | ||
//! `pds_store::table::OPEN` of them. What reads a store's tree after its | ||
//! which keeps the files of the tables read last open, at most a share of | ||
//! them (`Config::share`). What reads a store's tree after its | ||
//! lock is let go (`Snapshot`) holds the table's file itself, and so reads | ||
//! the table it began with to the end, though a compaction replaces it or | ||
//! the account is deleted meanwhile. | ||
| @@ -2946,7 +2946,6 @@ mod tests { | ||
/// from its file all the same; and a store let go closes its table's. | ||
#[tokio::test] | ||
async fn tables_replaced_and_held_open() { | ||
use pds_store::table::OPEN; | ||
let plc = plc().await; | ||
let dir = scratch("ckpt-open"); | ||
let s = open_with(&dir, &plc, |c| { | ||
| @@ -2992,15 +2991,16 @@ mod tests { | ||
assert_eq!(open(), 1); | ||
| ||
let mut dids = vec![did]; | ||
for i in 0..OPEN + 5 { | ||
let share = s.config.share; | ||
for i in 0..share + 5 { | ||
let (did, token) = create(&s, &format!("user{i}")).await; | ||
let value = json!({ "$type": "a.b.c", "t": "x".repeat(3000) }); | ||
put(&s, &did, &token, "k00", &value).await; | ||
assert!(compacted(&s, &did) > 0, "never compacted"); | ||
assert!(open() <= OPEN); | ||
assert!(open() <= share); | ||
dids.push(did); | ||
} | ||
assert_eq!(open(), OPEN); | ||
assert_eq!(open(), share); | ||
for did in &dids { | ||
// Nothing of its table in memory: the record is read from its file. | ||
store_of(&s, did, |st| { | ||
| @@ -3016,7 +3016,7 @@ mod tests { | ||
.await | ||
.unwrap(); | ||
assert_eq!(got["value"]["$type"], "a.b.c"); | ||
assert_eq!(open(), OPEN); | ||
assert_eq!(open(), share); | ||
} | ||
for (i, did) in dids.iter().enumerate() { | ||
assert!(s.account(did).unwrap().store.evict()); | ||
crates/pds-server/src/events.rs+1−1
| @@ -2497,7 +2497,7 @@ mod tests { | ||
accounts.push(m.await.unwrap()); | ||
} | ||
} | ||
assert!(accounts.len() > crate::log::OPEN_LOGS); | ||
assert!(accounts.len() > s.config.share); | ||
drop(s); | ||
let s = start(); | ||
for i in [0, 1, 78, 79] { | ||
crates/pds-server/src/lib.rs+10−0
| @@ -158,6 +158,10 @@ pub(crate) struct Config { | ||
pub log_floor: u64, | ||
/// `PDS_CACHE_BYTES`: the most held in memory of accounts' state and data read from disk (`spec/STORE.md`). | ||
pub cache_bytes: u64, | ||
/// The accounts' logs open at once, and as many of their tables: a | ||
/// share of the file descriptors the process may have (`spec/LIMITS.md`, | ||
/// "Open files and threads"). | ||
pub share: usize, | ||
/// Whether a start loads every account's state, to find every fault in | ||
/// the data directory before serving: the tests' way; the server's own | ||
/// loads each on first use. | ||
| @@ -229,6 +233,7 @@ impl Config { | ||
)?), | ||
log_floor: store::FLOOR, | ||
cache_bytes: limits::env_u64("PDS_CACHE_BYTES", 256 << 20)?, | ||
share: pds_store::files::share(pds_store::files::limit()), | ||
load_all: false, | ||
blobstore: blobstore::Settings::from_env()?, | ||
}) | ||
| @@ -715,6 +720,10 @@ fn fail(why: String) -> ! { | ||
/// Run the server, configured by the environment as `spec/PDS.md` says, | ||
/// until a SIGTERM or SIGINT shuts it down (`spec/OPERATIONS.md`). | ||
pub fn run() { | ||
// The file descriptors it may have, before the share of them the | ||
// configuration takes is read, and before anything is opened: left as | ||
// they are where they cannot be raised. | ||
pds_store::files::raise(); | ||
let Environment { | ||
port, | ||
dir, | ||
| @@ -1401,6 +1410,7 @@ mod testing { | ||
backfill: std::time::Duration::from_millis(86_400_000), | ||
log_floor: crate::store::FLOOR, | ||
cache_bytes: 256 << 20, | ||
share: 64, | ||
load_all: true, | ||
blobstore: None, | ||
} | ||
crates/pds-server/src/log.rs+29−21
| @@ -58,9 +58,11 @@ | ||
//! the one its last landed change gave it, or else the one the service log | ||
//! has. | ||
//! | ||
//! At most `OPEN_LOGS` accounts' logs are open at once, and at most | ||
//! `pds_store::table::OPEN` of their tables' files, and they are recovered | ||
//! on at most as many threads as the machine has cores. | ||
//! At most a share of accounts' logs are open at once (`Config::share`: a | ||
//! quarter of the file descriptors the process may have, as | ||
//! `pds_store::files::share` counts it), and at most a share of their | ||
//! tables' files, and they are recovered on at most as many threads as the | ||
//! machine has cores. | ||
| ||
use crate::blobs::blob_dir; | ||
use crate::cache::{Ctx, Slot}; | ||
| @@ -87,9 +89,6 @@ use std::sync::{Arc, Mutex, PoisonError, RwLock}; | ||
/// What error messages call the service log. | ||
pub(crate) const ACCOUNTS_LOG: &str = "the service log"; | ||
| ||
/// The most accounts' logs open at once. | ||
pub(crate) const OPEN_LOGS: usize = 64; | ||
| ||
/// The service log of generation 0, by its name. | ||
#[cfg(test)] | ||
pub(crate) const ACCOUNTS_LOG_FILE: &str = "accounts.0.log"; | ||
| @@ -630,7 +629,10 @@ impl Service { | ||
})?; | ||
// Of `PDS_CACHE_BYTES`: half the stores held, a quarter the blocks | ||
// read, and the firehose's tail (`events::TAIL`) the rest. | ||
let blocks = Arc::new(pds_store::table::BlockCache::new(config.cache_bytes / 4)); | ||
let blocks = Arc::new(pds_store::table::BlockCache::with_open( | ||
config.cache_bytes / 4, | ||
config.share, | ||
)); | ||
let table = ServiceTable::open(&layout.checkpoint(), blocks.clone())?; | ||
let (generation, size, service_seq, mut ceiling) = | ||
table.as_ref().map_or((0, 0, 0, None), |t| { | ||
| @@ -794,7 +796,7 @@ impl Service { | ||
let mut marks: Vec<String> = marked.iter().cloned().collect(); | ||
marks.sort_unstable(); | ||
let eager = Arc::new(crate::cache::Eager::new(log.clone(), marked)); | ||
let files = Files::new(OPEN_LOGS); | ||
let files = Files::new(config.share); | ||
let bucket = match config.blobstore.clone() { | ||
Some(s) => { | ||
let b = crate::blobstore::Bucket::new(s)?; | ||
| @@ -4442,14 +4444,15 @@ mod tests { | ||
} | ||
| ||
/// Accounts are loaded on no more threads than the machine has cores, | ||
/// with no more of their logs open than `OPEN_LOGS`. | ||
/// with no more of their logs open than a share. | ||
#[tokio::test] | ||
async fn recovery_is_bounded() { | ||
let plc = plc().await; | ||
let dir = scratch("recover-threads"); | ||
let s = open(&dir, &plc); | ||
let cores = std::thread::available_parallelism().unwrap().get(); | ||
let n = (cores * 3).max(OPEN_LOGS + 8); | ||
let share = s.config.share; | ||
let n = (cores * 3).max(share + 8); | ||
for i in 0..n { | ||
let body = | ||
json!({ "handle": format!("user{i}.test"), "email": format!("u{i}@mail.com") }); | ||
| @@ -4457,7 +4460,7 @@ mod tests { | ||
.await | ||
.unwrap(); | ||
} | ||
assert!(s.ctx.files.open_count() <= OPEN_LOGS); | ||
assert!(s.ctx.files.open_count() <= share); | ||
drop(s); | ||
let s = open(&dir, &plc); | ||
let d = crate::read(&s.directory); | ||
| @@ -4473,7 +4476,7 @@ mod tests { | ||
"{} threads, {cores} cores", | ||
threads.len() | ||
); | ||
assert!(s.ctx.files.open_count() <= OPEN_LOGS); | ||
assert!(s.ctx.files.open_count() <= share); | ||
drop(d); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
| @@ -4524,15 +4527,20 @@ mod tests { | ||
std::fs::read_dir(dir).unwrap().count() | ||
} | ||
| ||
/// With 256 file descriptors, 300 accounts are made, and the server | ||
/// started again serves every one of them, and takes writes from the | ||
/// first and the last: what it holds open does not grow with them. | ||
/// With 256 file descriptors, and the share of them the server takes | ||
/// under that limit, 300 accounts are made, and the server started | ||
/// again serves every one of them, and takes writes from the first and | ||
/// the last: what it holds open does not grow with them, and is no more | ||
/// than a share of logs, a share of tables and 72 files besides. | ||
#[test] | ||
fn many_accounts_few_files() { | ||
if !in_child("many_accounts_few_files") { | ||
return; | ||
} | ||
set_limit(Resource::Nofile, Some(256)); | ||
let share = store::files::share(store::files::limit()); | ||
assert_eq!(share, 64); | ||
let most = 2 * share + 72; | ||
let rt = tokio::runtime::Builder::new_multi_thread() | ||
.worker_threads(2) | ||
.enable_all() | ||
| @@ -4541,17 +4549,17 @@ mod tests { | ||
rt.block_on(async { | ||
let plc = plc().await; | ||
let dir = scratch("many-accounts"); | ||
let s = open(&dir, &plc); | ||
let s = open_with(&dir, &plc, |c| c.share = share); | ||
let mut made = Vec::new(); | ||
for i in 0..300 { | ||
let body = json!({ "handle": format!("user{i}.test"), "email": format!("u{i}@mail.com"), "password": "" }); | ||
made.push(call(&s, "com.atproto.server.createAccount", None, body).await.unwrap()); | ||
} | ||
assert!(s.ctx.files.open_count() <= OPEN_LOGS); | ||
assert!(open_fds() < 200, "{} open", open_fds()); | ||
assert!(s.ctx.files.open_count() <= share); | ||
assert!(open_fds() < most, "{} open", open_fds()); | ||
drop(s); | ||
let s = open(&dir, &plc); | ||
assert!(open_fds() < 200, "{} open", open_fds()); | ||
let s = open_with(&dir, &plc, |c| c.share = share); | ||
assert!(open_fds() < most, "{} open", open_fds()); | ||
for m in &made { | ||
let p = [("did".to_string(), m["did"].as_str().unwrap().to_string())]; | ||
call_with(&s, "com.atproto.sync.getLatestCommit", None, &p, Json::Null).await.unwrap(); | ||
| @@ -4560,7 +4568,7 @@ mod tests { | ||
let body = json!({ "repo": m["did"], "collection": "a.b.c", "record": { "n": 1 } }); | ||
call(&s, "com.atproto.repo.createRecord", m["accessJwt"].as_str(), body).await.unwrap(); | ||
} | ||
assert!(s.ctx.files.open_count() <= OPEN_LOGS); | ||
assert!(s.ctx.files.open_count() <= share); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
}); | ||
} | ||