chadtmiller.com/monolith
An atproto PDS
0
0
pds-server: a cold first use replays at most 4 MiB of an account's log
bench/store/README.md+1−1
| @@ -555,7 +555,7 @@ two blocks, each read from its file, its check computed over what is | ||
stored, decompressed if it is, and searched. The files are in the system's | ||
cache. A table is not rewritten in place, so it has no row for rewrites: | ||
between compactions an account takes its table and its log, and a log may | ||
grow to its table's size before it is compacted. | ||
grow to its table's size, or 4 MiB if that is less, before it is compacted. | ||
| ||
**The service log by the number of accounts** (`node service.mjs | ||
[accounts...]`). For each count, without and with an email and a password | ||
crates/pds-server/src/cache.rs+105−11
| @@ -20,7 +20,10 @@ | ||
//! compacted, whatever the log's size, and what the table then holds is | ||
//! let go; past twice that while the compaction runs, a writer waits for | ||
//! it (`Slot::write_lock`): written faster than its log can be compacted, | ||
//! a store holds no more for it. The compaction holds as much again of | ||
//! a store holds no more for it. So too once its log holds `store::BEHIND` | ||
//! past what compacts it by size (`store::ACCOUNT_CAP` at most, past its | ||
//! table): its first use after a start replays no more of it, however | ||
//! large its table. The compaction holds as much again of | ||
//! the logs it folds, with the account's state and a few blocks | ||
//! (`Cache::fold_blocks`), counted with the store while it runs | ||
//! (`Slot::folding`). A store is let go only with nothing of it in flight: no write | ||
| @@ -267,9 +270,10 @@ impl Cache { | ||
/// What one store's memtable may count before its log is compacted, | ||
/// whatever the log's size: an eighth of the stores' share of the cache. | ||
/// A store being written holds where each entry of its log after its | ||
/// table is, and its log grows to its table's size before it is | ||
/// compacted for that (`store::policy`): past this, it is compacted | ||
/// for what it holds in memory. | ||
/// table is, and its log grows to its table's size, or | ||
/// `store::ACCOUNT_CAP` if that is less, before it is compacted for that | ||
/// (`store::policy`): past this, it is compacted for what it holds in | ||
/// memory. | ||
pub fn memtable(&self) -> u64 { | ||
(self.budget / 8).max(MEMTABLE_FLOOR) | ||
} | ||
| @@ -768,19 +772,32 @@ impl Locked for Slot { | ||
} | ||
} | ||
| ||
/// A writer of a store whose memtable counts more than | ||
/// `Cache::memtable_most` while its log is compacted waits for the | ||
/// compaction, which lets go of what it folded: what a store being | ||
/// written holds does not follow how fast the writes come | ||
/// (`spec/STORE.md`, "Bounds"). The wait gives up its place among the | ||
/// runtime's workers, so that other requests go on meanwhile. | ||
/// A writer of a store whose log is compacted waits for the compaction, | ||
/// which lets go of what it folded, once the store's memtable counts | ||
/// more than `Cache::memtable_most`, or its log holds more than | ||
/// `store::BEHIND` past what compacts it by size (`store::policy`): what | ||
/// a store being written holds, and what its first use after a start | ||
/// replays of its log, do not follow how fast the writes come | ||
/// (`spec/STORE.md`, "Bounds", "The first request to a cold account"). | ||
/// The wait gives up its place among the runtime's workers, so that | ||
/// other requests go on meanwhile. | ||
fn write_lock(&self) -> StoreWrite<'_> { | ||
let most = self.ctx.cache.memtable_most(); | ||
let behind = |wal: &Wal| { | ||
wal.log_bytes() | ||
> self | ||
.ctx | ||
.policy | ||
.limit(wal.checkpoint_bytes()) | ||
.saturating_add(crate::store::BEHIND) | ||
}; | ||
loop { | ||
self.used.store(clock(), Ordering::Relaxed); | ||
let g = crate::write(&self.store); | ||
match g.as_deref() { | ||
Some(st) if st.disk.mem.cost() > most && st.wal.compacting() => { | ||
Some(st) | ||
if st.wal.compacting() && (st.disk.mem.cost() > most || behind(&st.wal)) => | ||
{ | ||
let wal = st.wal.clone(); | ||
drop(g); | ||
off_worker(|| wal.wait_compacted()); | ||
| @@ -1064,6 +1081,83 @@ mod tests { | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
| ||
/// `spec/STORE.md`, "The first request to a cold account": an account's | ||
/// log is compacted once it holds the cap (`Config::account_cap`) past | ||
/// its table, however large the table: written past it twice over since | ||
/// its last compaction, with a table several times it, it is left | ||
/// holding no more, and its first load after a start replays no more of | ||
/// it, and reads little of the table. At a small cap, so that its data | ||
/// directory stays within a couple of MB. | ||
#[tokio::test] | ||
async fn a_first_load_replays_a_capped_log() { | ||
const CAP: u64 = 32 << 10; | ||
let plc = plc().await; | ||
let dir = scratch("cold-capped"); | ||
let start = || { | ||
open_with(&dir, &plc, |c| { | ||
(c.load_all, c.cache_bytes) = (false, 1 << 30); | ||
(c.log_floor, c.account_cap) = (2048, CAP); | ||
}) | ||
}; | ||
let s = start(); | ||
let (alice, ta) = create(&s, "alice").await; | ||
let big = | ||
|n: usize| json!({ "$type": "a.b.c", "text": format!("{n}{}", "e".repeat(1_000)) }); | ||
let write = async |s: &crate::Shared, n: usize| { | ||
let body = json!({ "repo": alice, "collection": "a.b.c", "rkey": format!("r{n}"), "record": big(n) }); | ||
call(s, "com.atproto.repo.putRecord", Some(&ta), body) | ||
.await | ||
.unwrap(); | ||
}; | ||
// A table of several times the cap: the log compacted as it passes | ||
// the table's size, while that is less than the cap. | ||
let wal = crate::read(&s.account(&alice).unwrap().store).wal.clone(); | ||
let mut n = 0; | ||
while wal.checkpoint_bytes() <= 4 * CAP { | ||
write(&s, n).await; | ||
n += 1; | ||
} | ||
compact(&s, &alice); | ||
wal.wait_compacted(); | ||
let generation = wal.checkpoint_generation(); | ||
// Written past the cap twice over since: each write's frame holds | ||
// its record, of 1000 bytes and more. | ||
for n in n..n + (2 * CAP / 1000 + 1) as usize { | ||
write(&s, n).await; | ||
} | ||
// Once no compaction runs: one that ends begins the next if due. | ||
loop { | ||
wal.wait_compacted(); | ||
tokio::time::sleep(Duration::from_millis(20)).await; | ||
if !wal.compacting() { | ||
break; | ||
} | ||
} | ||
let log = wal.log_bytes(); | ||
assert!( | ||
wal.checkpoint_generation() > generation && log <= CAP, | ||
"a log of {log} bytes past a table of {}", | ||
wal.checkpoint_bytes() | ||
); | ||
drop(wal); | ||
shut_down(s); | ||
let s = start(); | ||
s.events.find_old(); | ||
let a = s.account(&alice).unwrap(); | ||
let checkpoint = std::fs::metadata(crate::store::account_layout(&dir, &alice).checkpoint()) | ||
.unwrap() | ||
.len(); | ||
let replayed = crate::directory::files_bytes(&dir, &alice) - checkpoint; | ||
let before = s.ctx.blocks.read_bytes(); | ||
a.store.load().unwrap(); | ||
let read = s.ctx.blocks.read_bytes() - before; | ||
assert!( | ||
replayed <= CAP && read < checkpoint / 4, | ||
"its first load replayed {replayed} bytes of log, read {read} of a table of {checkpoint}" | ||
); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
| ||
/// After a start with every event out of the backfill window, a | ||
/// subscriber at the last event made has missed none, though seqs are | ||
/// reserved past it; one before it has. | ||
crates/pds-server/src/directory.rs+24−8
| @@ -18,8 +18,11 @@ | ||
//! and app passwords (`sessions::Sessions`), its preferences | ||
//! (`preferences::Preferences`) and its password reset token | ||
//! (`email::Resets`). Loaded, it stays, and every change to it is made in | ||
//! memory as it is logged: so nothing is noted of what this run logs. One | ||
//! load runs at a time, so two requests for one account make one `Account`. | ||
//! memory as it is logged: so nothing is noted of what this run logs. The | ||
//! loads of one account run one at a time, so two requests for it make one | ||
//! `Account`; those of other accounts run beside it, each reading its own | ||
//! entries as the others read theirs, as many as come at once (`LOADING`, | ||
//! `spec/STORE.md`, "The first request to a cold account"). | ||
//! What cannot be parsed stops the server (`cache::unrecoverable`). | ||
//! | ||
//! **Lookups.** By DID: the accounts loaded, or else a load. By handle, | ||
| @@ -520,11 +523,26 @@ impl Directory { | ||
} | ||
} | ||
| ||
/// How many stripes the loads of accounts are of (`Accounts::loading`): | ||
/// loads of accounts of one stripe wait for each other, so many that few | ||
/// do, however many accounts are loaded at once, and few enough that the | ||
/// locks cost nothing to hold. | ||
const LOADING: usize = 64; | ||
| ||
/// The stripe of the loads of the account `did`. | ||
fn stripe(did: &str) -> usize { | ||
use std::hash::{Hash, Hasher}; | ||
let mut h = std::hash::DefaultHasher::new(); | ||
did.hash(&mut h); | ||
(h.finish() % LOADING as u64) as usize | ||
} | ||
| ||
/// The directory, behind its lock, and what loads the accounts into it. | ||
pub(crate) struct Accounts { | ||
directory: RwLock<Directory>, | ||
/// Held by the one load of an account at a time. | ||
loading: Mutex<()>, | ||
/// Held by a load, the one of its DID's stripe (`stripe`): so that one | ||
/// load of an account runs at a time, and those of others beside it. | ||
loading: Box<[Mutex<()>]>, | ||
layout: Layout, | ||
/// The blocks read of the table, shared with the accounts' tables. | ||
blocks: Arc<BlockCache>, | ||
| @@ -547,7 +565,7 @@ impl Accounts { | ||
pub fn new(layout: Layout, blocks: Arc<BlockCache>, directory: Directory) -> Accounts { | ||
Accounts { | ||
directory: RwLock::new(directory), | ||
loading: Mutex::new(()), | ||
loading: (0..LOADING).map(|_| Mutex::new(())).collect(), | ||
layout, | ||
blocks, | ||
} | ||
| @@ -690,9 +708,7 @@ impl Service { | ||
if !read(&self.directory).may_be(did) { | ||
return Ok(None); | ||
} | ||
let _one = self | ||
.directory | ||
.loading | ||
let _one = self.directory.loading[stripe(did)] | ||
.lock() | ||
.unwrap_or_else(PoisonError::into_inner); | ||
if let Some(a) = read(&self.directory).by_did.get(did) { | ||
crates/pds-server/src/lib.rs+6−0
| @@ -161,6 +161,10 @@ pub(crate) struct Config { | ||
pub backfill: std::time::Duration, | ||
/// The bytes a log may grow to past its checkpoint's, whatever that is (`spec/STORE.md`). | ||
pub log_floor: u64, | ||
/// The most an account's log may grow to past its table, whatever the | ||
/// table's size, but `log_floor` if that is more (`store::ACCOUNT_CAP`, | ||
/// `spec/STORE.md`, "The first request to a cold account"). | ||
pub account_cap: 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 | ||
| @@ -277,6 +281,7 @@ impl Config { | ||
86_400_000, | ||
)?), | ||
log_floor: store::FLOOR, | ||
account_cap: store::ACCOUNT_CAP, | ||
cache_bytes: limits::env_u64("PDS_CACHE_BYTES", 256 << 20)?, | ||
share: pds_store::files::share(pds_store::files::limit()), | ||
load_all: false, | ||
| @@ -1487,6 +1492,7 @@ mod testing { | ||
ssrf_protection: false, | ||
backfill: std::time::Duration::from_millis(86_400_000), | ||
log_floor: crate::store::FLOOR, | ||
account_cap: crate::store::ACCOUNT_CAP, | ||
cache_bytes: 256 << 20, | ||
share: 64, | ||
load_all: true, | ||
crates/pds-server/src/store.rs+38−17
| @@ -72,13 +72,15 @@ | ||
//! after it holds of an account not yet loaded is kept as where in the log | ||
//! it is (`directory`). | ||
//! | ||
//! **Compacting** a log of generation `g`, when after an append its logs | ||
//! pass `max(checkpoint, log_floor)` bytes, the service log's | ||
//! `max(min(checkpoint, SERVICE_CAP), log_floor)`, or its generation began | ||
//! more than twice the backfill window ago (`policy`, `service_policy`); | ||
//! and an account's, whatever its size, when what its store holds in | ||
//! memory of the log after its table passes its share of the cache | ||
//! (`cache::Cache::memtable`): | ||
//! **Compacting** a log of generation `g`, when after an append, or as the | ||
//! compaction before ends, its logs pass `max(min(checkpoint, | ||
//! ACCOUNT_CAP), log_floor)` bytes, the service log's `max(min(checkpoint, | ||
//! SERVICE_CAP), log_floor)`, or its generation began more than twice the | ||
//! backfill window ago (`policy`, `service_policy`); and an account's, | ||
//! whatever its size, when what its store holds in memory of the log after | ||
//! its table passes its share of the cache (`cache::Cache::memtable`). So | ||
//! once no compaction runs, a log holds no more than that, though writes | ||
//! came while the last one ran: | ||
//! | ||
//! 1. under the log's lock, log `g`'s room given back, its seal written, | ||
//! and log `g + 1` made, empty; nothing synced, nothing read, nothing | ||
| @@ -93,10 +95,13 @@ | ||
//! new table from then on; the directory synced; | ||
//! 5. the logs before `g + 1` deleted. | ||
//! | ||
//! The service log is capped because a start replays it, noting where each | ||
//! account's entries are: so what a start reads of it does not grow with | ||
//! the accounts, and its table is written whole once for each `SERVICE_CAP` | ||
//! of log. | ||
//! Both logs are capped because a start, or an account's first use after | ||
//! one, replays them: what a start reads of the service log does not grow | ||
//! with the accounts, and its table is written whole once for each | ||
//! `SERVICE_CAP` of log; what an account's first use reads of its log does | ||
//! not grow with its table, as a day of events makes it, which is written | ||
//! whole once for each `ACCOUNT_CAP` of log (`spec/STORE.md`, "The first | ||
//! request to a cold account"). | ||
//! | ||
//! **Starting**: `<checkpoint>.tmp` deleted, the checkpoint read (generation | ||
//! `c`), logs before `c` deleted, the rest replayed in order and none | ||
| @@ -308,6 +313,20 @@ use std::path::{Path, PathBuf}; | ||
/// The bytes a log may grow to past its checkpoint's, whatever the checkpoint's size. | ||
pub(crate) const FLOOR: u64 = 1 << 20; | ||
| ||
/// The most an account's log grows to past its table before it is | ||
/// compacted, whatever the table's size, but `log_floor` if that is more: | ||
/// its first use after a start replays it. `Config::account_cap`'s | ||
/// default, which tests set smaller. | ||
pub(crate) const ACCOUNT_CAP: u64 = 4 << 20; | ||
| ||
/// How much more than compacts it by size an account's log may hold while | ||
/// a compaction of it runs, before its writers wait for that compaction | ||
/// (`cache::Slot::write_lock`): so that, however fast the writes come | ||
/// while a large table is written again, its first use after a start | ||
/// replays no more than its cap (`Config::account_cap`) and this, and a | ||
/// write. | ||
pub(crate) const BEHIND: u64 = 2 << 20; | ||
| ||
/// The most the service log grows to before it is compacted, whatever its | ||
/// checkpoint's size, but `log_floor` if that is more: a start replays it. | ||
pub(crate) const SERVICE_CAP: u64 = 8 << 20; | ||
| @@ -477,15 +496,17 @@ pub(crate) fn hold(dir: &Path) -> Result<std::fs::File, String> { | ||
} | ||
} | ||
| ||
/// When an account's log is compacted: past its checkpoint's size or | ||
/// `log_floor`, or once its generation began more than twice the window ago, | ||
/// as its files tell (`pds_store::Policy::max_age`): so the first write | ||
/// after `2 W` of quiet compacts it, though the server was started again, or | ||
/// the store let go and loaded again, meanwhile (`spec/STORE.md`, "Settled"). | ||
/// When an account's log is compacted: past its checkpoint's size, or | ||
/// `Config::account_cap` (`ACCOUNT_CAP`) if that is less, or `log_floor` if | ||
/// that is more; or once its generation began more than twice the window | ||
/// ago, as its files tell | ||
/// (`pds_store::Policy::max_age`): so the first write after `2 W` of quiet | ||
/// compacts it, though the server was started again, or the store let go | ||
/// and loaded again, meanwhile (`spec/STORE.md`, "Settled"). | ||
pub(crate) fn policy(c: &Config) -> Policy { | ||
Policy { | ||
floor: c.log_floor, | ||
cap: None, | ||
cap: Some(c.account_cap), | ||
max_age: Some(c.backfill * 2), | ||
} | ||
} | ||
crates/pds-store/src/generations.rs+78−9
| @@ -7,7 +7,9 @@ | ||
//! the last ends with its seal, a frame of `[{"t":"seal"}]` alone, which no | ||
//! caller ever sees. Frames are numbered on across generations, seals too. | ||
//! | ||
//! Compacting from generation `g` (`compact`, or an append that makes it due): | ||
//! Compacting from generation `g` (`compact`, an append that makes it due, | ||
//! or the end of one begun so, if what was appended meanwhile makes the | ||
//! next due): | ||
//! | ||
//! 1. under the log's lock, with a torn tail cut back first, the room after | ||
//! log `g`'s last frame is given back, its seal written there, and log | ||
| @@ -806,9 +808,9 @@ impl Shared { | ||
&& !self.closed(inner) | ||
} | ||
| ||
/// After an append, under the lock: start a compaction if one is due, | ||
/// steps 2 to 5 on a thread of its own. Answers what to say if one could | ||
/// not start. | ||
/// After an append, or a compaction that ended (`again`), under the | ||
/// lock: start a compaction if one is due, steps 2 to 5 on a thread of | ||
/// its own. Answers what to say if one could not start. | ||
pub(crate) fn trigger(self: &Arc<Self>, inner: &mut Inner) -> Option<String> { | ||
if !self.ready(inner) { | ||
return None; | ||
| @@ -837,7 +839,9 @@ impl Shared { | ||
.name("pds-compact".into()) | ||
.spawn(move || { | ||
let done = s.settle(g, &*fold, 5); | ||
let _ = s.end(g, done, true); | ||
if s.end(g, done, true).is_ok() { | ||
s.again(); | ||
} | ||
}); | ||
match spawned { | ||
Ok(_) => None, | ||
| @@ -849,6 +853,19 @@ impl Shared { | ||
} | ||
} | ||
| ||
/// After a compaction begun by a trigger has ended well, start the next | ||
/// if one is due now, as the appends made while it ran would have had | ||
/// it not run (`trigger`): so that, once none runs, a log holds no more | ||
/// than its policy lets it, however much came while one did. | ||
fn again(self: &Arc<Self>) { | ||
let mut inner = lock(&self.inner); | ||
let failed = self.trigger(&mut inner); | ||
drop(inner); | ||
if let Some(why) = failed { | ||
crate::report(&why); | ||
} | ||
} | ||
| ||
/// Step 1, under the lock, if no compaction runs: seal the current log, | ||
/// `g`, and make log `g + 1` for appends to go to. Answers `g`. | ||
fn start(self: &Arc<Self>, inner: &mut Inner) -> Result<u64, String> { | ||
| @@ -1423,6 +1440,51 @@ mod tests { | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
| ||
/// What is appended while a compaction runs, past what makes one due, | ||
/// is compacted as that one ends, with no append after it: once none | ||
/// runs, the log holds no more than its policy lets it. | ||
#[test] | ||
fn compacts_again_as_one_ends_if_due() { | ||
let dir = scratch("again"); | ||
let layout = Layout::new(&dir, "repo"); | ||
let limit = 200; | ||
let policy = Policy { | ||
floor: limit, | ||
cap: Some(limit), | ||
max_age: None, | ||
}; | ||
let (wal, _) = start(&layout, policy).unwrap(); | ||
let (fold, at, go) = held(); | ||
wal.set_fold(fold); | ||
// Past the limit: a compaction begins, and waits in its fold. | ||
let mut n = 0; | ||
while !wal.compacting() { | ||
wal.append(&[json!(n)]).unwrap(); | ||
n += 1; | ||
} | ||
at.recv().unwrap(); | ||
let g = wal.generation(); | ||
// Past it again while that one runs. | ||
let sealed = wal.log_bytes(); | ||
while wal.log_bytes() - sealed <= limit { | ||
wal.append(&[json!(n)]).unwrap(); | ||
n += 1; | ||
} | ||
assert_eq!(wal.generation(), g, "none begins while one runs"); | ||
go.send(()).unwrap(); | ||
// The next begins as it ends. | ||
at.recv_timeout(Duration::from_secs(10)) | ||
.expect("a compaction begun as the one before ended"); | ||
assert_eq!(wal.generation(), g + 1); | ||
go.send(()).unwrap(); | ||
wal.wait_compacted(); | ||
assert!(wal.log_bytes() <= limit, "{}", wal.log_bytes()); | ||
assert_eq!(wal.checkpoint_generation(), g + 1); | ||
drop(wal); | ||
assert_eq!(start(&layout, NEVER).unwrap().1, nums(0..n)); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
| ||
/// By age: once its generation began more than `max_age` ago, when a | ||
/// compaction made its log or the log was first made, whether or not | ||
/// it was started again meanwhile. | ||
| @@ -1517,7 +1579,8 @@ mod tests { | ||
} | ||
| ||
/// Writes go on while a compaction folds, to the next log, each durable; | ||
/// and no other compaction starts meanwhile, though one is due. | ||
/// and no other compaction starts meanwhile, though one is due: the | ||
/// next begins as it ends, and folds them. | ||
#[test] | ||
fn writes_go_on_while_it_compacts() { | ||
let dir = scratch("during"); | ||
| @@ -1550,10 +1613,16 @@ mod tests { | ||
frames_of(nums(i..i + 50)) | ||
); | ||
go.send(()).unwrap(); | ||
reached.recv().unwrap(); | ||
assert_eq!(wal.generation(), 2); | ||
go.send(()).unwrap(); | ||
wal.wait_compacted(); | ||
assert_eq!(checkpoint(&layout), [vec![json!(1)], nums(0..i)].concat()); | ||
assert_eq!(names(&dir), ["repo.1.log", "repo.checkpoint"]); | ||
assert_eq!(wal.log_bytes(), size(&layout.log(1))); | ||
assert_eq!( | ||
checkpoint(&layout), | ||
[vec![json!(2)], nums(0..i + 50)].concat() | ||
); | ||
assert_eq!(names(&dir), ["repo.2.log", "repo.checkpoint"]); | ||
assert_eq!(wal.log_bytes(), size(&layout.log(2))); | ||
drop(wal); | ||
assert_eq!(start(&layout, NEVER).unwrap().1, nums(0..i + 50)); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
crates/pds-store/src/table.rs+14−1
| @@ -717,6 +717,7 @@ impl Table { | ||
Some(f) => f.read_exact_at(buf, offset)?, | ||
None => self.file()?.read_exact_at(buf, offset)?, | ||
} | ||
cache.read.fetch_add(len as u64, Ordering::Relaxed); | ||
let (entries, c) = buf.split_at(len - CHECK); | ||
if self.version.check(entries) != c { | ||
return Err(bad( | ||
| @@ -1046,11 +1047,15 @@ fn held(value: &[u8]) -> u64 { | ||
/// with a lock of its own, so that readers of different items seldom wait | ||
/// for one another; the bytes are counted across all of them, and never | ||
/// pass the budget. Room is made by letting go of the least recently used | ||
/// of the part the new item goes in, then of the other parts in turn. | ||
/// of the part the new item goes in, then of the other parts in turn. It | ||
/// counts the bytes of the tables' blocks read from their files through it | ||
/// (`read_bytes`). | ||
pub struct BlockCache { | ||
budget: u64, | ||
/// The bytes held, and those of items about to be. | ||
bytes: AtomicU64, | ||
/// The bytes of tables' blocks read from their files, since it was made. | ||
read: AtomicU64, | ||
parts: Box<[Part]>, | ||
files: Arc<Files>, | ||
} | ||
| @@ -1156,6 +1161,7 @@ impl BlockCache { | ||
BlockCache { | ||
budget, | ||
bytes: AtomicU64::new(0), | ||
read: AtomicU64::new(0), | ||
parts: (0..PARTS).map(|_| Part::default()).collect(), | ||
files: Arc::new(Files { | ||
max: open.max(1), | ||
| @@ -1171,6 +1177,13 @@ impl BlockCache { | ||
self.bytes.load(Ordering::Relaxed) | ||
} | ||
| ||
/// The bytes of tables' blocks read from their files through it since | ||
/// it was made, checks and all: what reading by key and in order cost, | ||
/// apart from what opening the tables read of their ends. | ||
pub fn read_bytes(&self) -> u64 { | ||
self.read.load(Ordering::Relaxed) | ||
} | ||
| ||
/// How many tables' files it holds open. | ||
pub fn open_files(&self) -> usize { | ||
self.files.open.load(Ordering::Relaxed) | ||
harness/checks/operations.mjs+6−1
| @@ -631,7 +631,12 @@ async function checkSpans(upTo) { | ||
if (any.length) await broke('spans', request, 'none: the traceparent is not sampled', any.slice(0, 2)) | ||
continue | ||
} | ||
if (spans.length !== 1) await broke('spans', request, 'one SERVER span in the request\'s trace', spans.length ? spans : `none, of the ${otlp.spans.size} spans the receiver has from ${otlp.exports.length} exports`) | ||
if (spans.length !== 1) { | ||
// When it ended, among the server's lives, so that a span lost shows where. | ||
const at = (t) => (t === null || t === undefined ? null : new Date(t).toISOString()) | ||
const when = { ended: at(rec.ended), life: rec.life, lives: server.lives.map((l) => ({ started: at(l.started), ended: at(l.ended), how: l.how })) } | ||
await broke('spans', { ...request, ...when }, 'one SERVER span in the request\'s trace', spans.length ? spans : `none, of the ${otlp.spans.size} spans the receiver has from ${otlp.exports.length} exports`) | ||
} | ||
const [sp] = spans | ||
await checkServerSpan(sp, rec, request, lives[rec.life]) | ||
const under = children.get(sp.spanId) ?? [] | ||
harness/checks/store.mjs+83−4
| @@ -6,7 +6,7 @@ | ||
// time. How the server lays its data out is its own: only the directory's | ||
// size, and its files being made, removed or shortened, are seen. | ||
| ||
import { existsSync, readdirSync, statSync } from 'node:fs' | ||
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs' | ||
import { join } from 'node:path' | ||
import { isDeepStrictEqual } from 'node:util' | ||
import { BACKFILL_MS, CHECK_EVERY, CRASH_EVERY, FIREHOSE, ONLY, STEPS } from '../lib/args.mjs' | ||
| @@ -82,8 +82,7 @@ async function rewriteBatch(acct) { | ||
} | ||
| ||
/// deleteRecord of a key of the collection, there or not. | ||
async function deleteKey(acct) { | ||
const key = pick(KEYS) | ||
async function deleteKey(acct, key = pick(KEYS)) { | ||
const [a, b] = await both('deleteRecord, rewritten', 'com.atproto.repo.deleteRecord', { body: { repo: acct.handle, collection: C, rkey: key }, token: acct }) | ||
if (a.status === 200) acct.records.delete(`${C}/${key}`) | ||
noteCommit(ref, acct, a) | ||
| @@ -447,12 +446,13 @@ export async function storeRun() { | ||
// Settled: a quiet 2 W, then a write to each account. | ||
await wait(2 * BACKFILL_MS + 1000) | ||
const report = await settled('') | ||
await coldReads() | ||
// Out of the window now: all but the latest writes' events. | ||
await windowReplay() | ||
const last = await restart(base) | ||
await checkRepos() | ||
await windowReplay() | ||
return { report, base, last } | ||
return { report, base, last, cold } | ||
} | ||
| ||
/// spec/STORE.md, "Bounds", "Settled": a write to each account, after 2 W | ||
| @@ -482,3 +482,82 @@ async function settled(why) { | ||
`${what}: ${size} bytes, bound ${bound}: ${(size / liveBytes).toFixed(2)}x the live state`, | ||
] | ||
} | ||
| ||
/// The bytes the server's process has read, by any read call, from the page | ||
/// cache or the disk: Linux's /proc/<pid>/io `rchar`. Null where the machine | ||
/// does not count them, or the server is no process of this machine. | ||
function readBytes() { | ||
const pid = server.proc?.pid | ||
if (!pid || !existsSync(`/proc/${pid}/io`)) return null | ||
const m = /^rchar:\s*(\d+)$/m.exec(readFileSync(`/proc/${pid}/io`, 'utf8')) | ||
return m ? Number(m[1]) : null | ||
} | ||
| ||
/// What coldReads measured, for the run's summary: null where not counted. | ||
let cold = null | ||
| ||
/// The data directory as it is left: no file changing for a second. | ||
async function settle() { | ||
for (let last = sizeOf(filesOf()), quiet = 0; quiet < 10; ) { | ||
await wait(100) | ||
const now = sizeOf(filesOf()) | ||
quiet = now === last ? quiet + 1 : 0 | ||
last = now | ||
} | ||
} | ||
| ||
/// spec/STORE.md, "Bounds", "The first request to a cold account": a cold | ||
/// account's first use reads at most 6 MiB of its files besides what the | ||
/// request reads, whatever it holds. A new account, with a space of its | ||
/// own and nothing a start takes up again (the run's accounts have | ||
/// writes to a space no directory knows), given 48 records of 250 KB | ||
/// at keys of their own, a table of 12 MB or more; then `2 W` with no write | ||
/// and one write, which folds its log (spec/STORE.md, "Settled"), so that | ||
/// its log begins again; at once 16 rewrites, each of which the log holds | ||
/// twice, as the record and its event: 8 MB, well within `2 W`, which a log | ||
/// folded only once it outgrows its table keeps whole; the data directory | ||
/// let settle, the server shut down and started again; then, nothing else | ||
/// asked of it, that account's first getRecord must read no more than | ||
/// 6 MiB. Its records deleted after, so that the checks after read little. | ||
async function coldReads() { | ||
if (readBytes() === null) { | ||
count('a cold account\'s first use, its reads not counted on this machine', false) | ||
return | ||
} | ||
// An account of its own, with nothing the server takes up again as it starts. | ||
const acct = await createAccount({ withPassword: true }) | ||
await makeSpace(acct) | ||
const record = () => ({ $type: C, batch: nextBatch(), text: 'e'.repeat(250_000) }) | ||
const keys = Array.from({ length: 48 }, (_, i) => `cold${i}`) | ||
for (const k of keys) await rewrite(acct, k, record()) | ||
await wait(2 * BACKFILL_MS + 1000) | ||
await rewrite(acct, keys[0], record()) | ||
for (let n = 0; n < 16; n++) await rewrite(acct, pick(keys), record()) | ||
await settle() | ||
// The spans of the requests before it exported, as a shutdown may not wait for all. | ||
await wait(2000) | ||
await server.stop('SIGTERM', 15_000) | ||
server.start() | ||
await waitReady(server, cand.url) | ||
// Whatever the start reads of its own, done with: no read for half a second. | ||
for (let last = readBytes(), quiet = 0; quiet < 5; ) { | ||
await wait(100) | ||
const now = readBytes() | ||
quiet = now === last ? quiet + 1 : 0 | ||
last = now | ||
} | ||
const key = pick(keys) | ||
const from = readBytes() | ||
const got = await xrpcHttp(cand, 'com.atproto.repo.getRecord', { params: { repo: didOf(cand, acct), collection: C, rkey: key } }) | ||
const read = readBytes() - from | ||
if (got.status !== 200) await fail(cand, 'getRecord, a cold account\'s first request', { did: `<did:${acct.n}>`, key }, 'the record', got.body) | ||
if (FIREHOSE) resubscribe() | ||
const most = 6 * 1048576 | ||
if (read > most) { | ||
const state = await live(acct) | ||
await differ('a cold account\'s first request', { did: `<did:${acct.n}>`, live: state.bytes }, `reading at most ${most} bytes of its files: a log folded before it holds 4 MiB of writes (spec/STORE.md, "The first request to a cold account")`, `${read} bytes read`) | ||
} | ||
cold = { read, most } | ||
count('a cold account\'s first use, reading at most 6 MiB', true) | ||
for (const k of keys) await deleteKey(acct, k) | ||
} | ||
harness/compare.mjs+2−2
| @@ -152,9 +152,9 @@ if (MOVES) { | ||
await shutdown(0) | ||
} | ||
if (STORE) { | ||
const { report, base, last } = await storeRun() | ||
const { report, base, last, cold } = await storeRun() | ||
await checkOperations() | ||
console.error(`\nall ${STEPS} store steps agree (seed ${SEED}), ${accounts.length} accounts, ${recordCount()} records`) | ||
console.error(`\nall ${STEPS} store steps agree (seed ${SEED}), ${accounts.length} accounts, ${recordCount()} records${cold ? `, a cold first use read ${cold.read} bytes of at most ${cold.most}` : ', a cold first use\'s reads not counted here'}`) | ||
for (const line of report) console.error(` ${line}`) | ||
const ms = crashes.restartMs.slice(3).sort((x, y) => x - y) | ||
console.error(` first starts at most ${base} ms, later p50 ${ms[ms.length >> 1]} ms, max ${ms.at(-1)} ms, the last ${last} ms`) | ||