chadtmiller.com/monolith
An atproto PDS
0
0
pds-server: a fold indexes each frame once, however large
.changeset/import-compacts-at-once.mdnew+7−0
| @@ -0,0 +1,7 @@ | ||
--- | ||
default: patch | ||
--- | ||
| ||
# A large import's log is compacted at once | ||
| ||
The log of an account that moved in a large repository with `com.atproto.repo.importRepo` is compacted in seconds, not in about an hour: the import is one commit of every record, whose index was larger than compaction's cache keeps, so it read the whole commit again for each record it wrote out, and the account's next write, such as `activateAccount`, waited for it all that time. Compaction now indexes each commit once, holding its index until it ends, counted in `PDS_CACHE_BYTES` as what it holds besides. | ||
crates/pds-server/src/checkpoint.rs+268−43
| @@ -93,7 +93,7 @@ use pds_store::{Fold, Layout, Pos}; | ||
use serde_json::Value as Json; | ||
use serde_json::value::RawValue; | ||
use spaces::{Old, SpaceMem, View}; | ||
use std::collections::{BTreeMap, HashMap}; | ||
use std::collections::{BTreeMap, HashMap, HashSet}; | ||
use std::fs::File; | ||
use std::io::{self, Write}; | ||
use std::os::unix::fs::FileExt; | ||
| @@ -1016,12 +1016,15 @@ impl Memtable { | ||
for cid in c.gone { | ||
self.block(cid, gone(&rev)); | ||
} | ||
// An import puts every record in one commit: each looked up, not | ||
// searched for among the others. | ||
let put: HashSet<&[u8]> = c.puts.iter().map(|(_, p)| p.as_slice()).collect(); | ||
for (cid, n, added) in c.refs { | ||
if n == 0 { | ||
self.block(cid, gone(&rev)); | ||
continue; | ||
} | ||
let here = c.puts.iter().any(|(_, p)| *p == cid); | ||
let here = put.contains(cid.as_slice()); | ||
let at = match self.blocks.get(&cid) { | ||
_ if here => At::Log(pos), | ||
Some(MemBlock { at: Some(at), .. }) => *at, | ||
| @@ -1577,37 +1580,65 @@ fn frame_item( | ||
) -> Result<Option<Vec<u8>>, String> { | ||
let key = index_key(number, pos); | ||
let found = match cache.get(&key) { | ||
Some(ix) => match find(&ix, want) { | ||
None => None, | ||
Some((how, start, len)) => Some(decode_item( | ||
how, | ||
&read(pos.offset + (pds_store::HEADER + start) as u64, len) | ||
.map_err(|e| e.to_string())?, | ||
)?), | ||
}, | ||
Some(ix) => indexed_item(&ix, pos, read, want)?, | ||
None => { | ||
let payload = | ||
pds_store::payload(read(pos.offset, pos.len as usize).map_err(|e| e.to_string())?) | ||
.ok_or_else(|| format!("no whole frame at {}", pos.offset))?; | ||
match index(&payload)? { | ||
Some(ix) => { | ||
let hit = find(&ix, want); | ||
cache.put(key, ix.into()); | ||
match hit { | ||
None => None, | ||
Some((how, start, len)) => Some(decode_item( | ||
how, | ||
payload | ||
.get(start..start + len) | ||
.ok_or("an index past its frame")?, | ||
)?), | ||
} | ||
} | ||
None => item(&payload, want)?, | ||
let (ix, found) = whole_frame_item(pos, read, want)?; | ||
if let Some(ix) = ix { | ||
cache.put(key, ix.into()); | ||
} | ||
found | ||
} | ||
}; | ||
// A block, and a space record, is what its CID says it is. | ||
checked(want, found) | ||
} | ||
| ||
/// An item of the frame at `pos`, by the frame's index `ix`: its bytes | ||
/// alone, which `read` reads. | ||
fn indexed_item( | ||
ix: &[u8], | ||
pos: Pos, | ||
read: &dyn Fn(u64, usize) -> io::Result<Vec<u8>>, | ||
want: Want, | ||
) -> Result<Option<Vec<u8>>, String> { | ||
let Some((how, start, len)) = find(ix, want) else { | ||
return Ok(None); | ||
}; | ||
let text = | ||
read(pos.offset + (pds_store::HEADER + start) as u64, len).map_err(|e| e.to_string())?; | ||
decode_item(how, &text).map(Some) | ||
} | ||
| ||
/// A frame's index, if a name fits one (`index`), and an item found in it. | ||
type Indexed = (Option<Vec<u8>>, Option<Vec<u8>>); | ||
| ||
/// An item of the frame at `pos`, read whole by `read`, and the frame's | ||
/// index, made of it. | ||
fn whole_frame_item( | ||
pos: Pos, | ||
read: &dyn Fn(u64, usize) -> io::Result<Vec<u8>>, | ||
want: Want, | ||
) -> Result<Indexed, String> { | ||
let payload = | ||
pds_store::payload(read(pos.offset, pos.len as usize).map_err(|e| e.to_string())?) | ||
.ok_or_else(|| format!("no whole frame at {}", pos.offset))?; | ||
let Some(ix) = index(&payload)? else { | ||
return Ok((None, item(&payload, want)?)); | ||
}; | ||
let found = match find(&ix, want) { | ||
None => None, | ||
Some((how, start, len)) => Some(decode_item( | ||
how, | ||
payload | ||
.get(start..start + len) | ||
.ok_or("an index past its frame")?, | ||
)?), | ||
}; | ||
Ok((Some(ix), found)) | ||
} | ||
| ||
/// An item found, checked: a block, and a space record, is what its CID | ||
/// says it is. | ||
fn checked(want: Want, found: Option<Vec<u8>>) -> Result<Option<Vec<u8>>, String> { | ||
if let (Want::Block(c) | Want::SpaceRecord(_, c), Some(b)) = (want, &found) | ||
&& cid_of(0x71, b) != c | ||
{ | ||
| @@ -1619,6 +1650,43 @@ fn frame_item( | ||
Ok(found) | ||
} | ||
| ||
/// The indexes of the frames a fold reads the items of, by each frame's | ||
/// generation and offset, and their bytes. Each is made once, when an item | ||
/// of its frame is first read, and kept until the fold ends, whatever its | ||
/// size: the block cache keeps no entry larger than an eighth of it, and | ||
/// one commit of a whole repository, as an import is, has an index larger | ||
/// than the fold's cache would keep, which would otherwise be made again, | ||
/// the whole frame read, for each of its items. | ||
#[derive(Default)] | ||
struct Indexes { | ||
of: HashMap<(u64, u64), Vec<u8>>, | ||
bytes: u64, | ||
} | ||
| ||
impl Indexes { | ||
/// An item of the frame at `pos`, whose bytes `read` reads, as | ||
/// `frame_item` reads one. | ||
fn item( | ||
&mut self, | ||
pos: Pos, | ||
read: &dyn Fn(u64, usize) -> io::Result<Vec<u8>>, | ||
want: Want, | ||
) -> Result<Option<Vec<u8>>, String> { | ||
let found = match self.of.get(&(pos.generation, pos.offset)) { | ||
Some(ix) => indexed_item(ix, pos, read, want)?, | ||
None => { | ||
let (ix, found) = whole_frame_item(pos, read, want)?; | ||
if let Some(ix) = ix { | ||
self.bytes += ix.len() as u64; | ||
self.of.insert((pos.generation, pos.offset), ix); | ||
} | ||
found | ||
} | ||
}; | ||
checked(want, found) | ||
} | ||
} | ||
| ||
/// Read `len` bytes of `file` at `offset`. | ||
fn read_at(file: &File, offset: u64, len: usize) -> io::Result<Vec<u8>> { | ||
let mut buf = vec![0u8; len]; | ||
| @@ -2301,8 +2369,12 @@ pub(crate) struct AccountFold { | ||
} | ||
| ||
/// What a fold holds in memory while it merges, counted with its account's | ||
/// store until it ends (`cache::Slot::folding`). | ||
struct Holding(Option<Arc<Account>>); | ||
/// store until it ends (`cache::Slot::folding`): what it holds from the | ||
/// start, and the frames' indexes it makes as it goes (`Indexes`). | ||
struct Holding { | ||
account: Option<Arc<Account>>, | ||
bytes: std::cell::Cell<u64>, | ||
} | ||
| ||
impl Holding { | ||
fn new(account: &Weak<Account>, bytes: u64) -> Holding { | ||
| @@ -2310,24 +2382,38 @@ impl Holding { | ||
if let Some(a) = &account { | ||
a.store.folding(bytes); | ||
} | ||
Holding(account) | ||
Holding { | ||
account, | ||
bytes: bytes.into(), | ||
} | ||
} | ||
| ||
/// Count `bytes` more. | ||
fn more(&self, bytes: u64) { | ||
let n = self.bytes.get() + bytes; | ||
self.bytes.set(n); | ||
if let Some(a) = &self.account { | ||
a.store.folding(n); | ||
} | ||
} | ||
} | ||
| ||
impl Drop for Holding { | ||
fn drop(&mut self) { | ||
if let Some(a) = &self.0 { | ||
if let Some(a) = &self.account { | ||
a.store.folding(0); | ||
} | ||
} | ||
} | ||
| ||
/// Reads the items of the sealed logs' frames as the merge reaches them, | ||
/// each alone, through its frame's index kept in the fold's cache. | ||
/// each alone, through its frame's index (`Indexes`), whose bytes count | ||
/// with what the fold holds, if anything counts it. | ||
struct Frames<'a> { | ||
layout: &'a Layout, | ||
cache: &'a BlockCache, | ||
files: HashMap<u64, File>, | ||
indexes: Indexes, | ||
holding: Option<&'a Holding>, | ||
} | ||
| ||
impl Frames<'_> { | ||
| @@ -2339,7 +2425,14 @@ impl Frames<'_> { | ||
} | ||
}; | ||
let read = |offset: u64, len: usize| read_at(file, offset, len); | ||
frame_item(self.cache, pos.generation, pos, &read, want) | ||
let before = self.indexes.bytes; | ||
let found = self.indexes.item(pos, &read, want); | ||
if let Some(h) = self.holding | ||
&& self.indexes.bytes > before | ||
{ | ||
h.more(self.indexes.bytes - before); | ||
} | ||
found | ||
} | ||
} | ||
| ||
| @@ -2351,9 +2444,9 @@ impl Fold for AccountFold { | ||
generation: u64, | ||
out: &mut dyn Write, | ||
) -> Result<(), String> { | ||
// What is read again is kept: the places of the frames' items, and | ||
// the table's blocks records are looked up in as the logs are | ||
// replayed. What the merge reads once, in order, is not. | ||
// What is read again is kept: the table's blocks records are looked | ||
// up in as the logs are replayed, and the places of the frames' | ||
// items (`Frames`). What the merge reads once, in order, is not. | ||
let cache = BlockCache::new(self.blocks); | ||
let passing = BlockCache::new(0); | ||
let table = match checkpoint { | ||
| @@ -2437,14 +2530,15 @@ impl Fold for AccountFold { | ||
+ 2, | ||
); | ||
// What it holds from here on: the state, where each entry of the | ||
// sealed logs is, and the blocks it keeps. | ||
// sealed logs is, and the blocks it keeps; and the frames' indexes, | ||
// as it makes them. | ||
let held = small.blobs.cost() | ||
+ small.spaces.cost() | ||
+ small.authority.cost() | ||
+ small.notify.cost() | ||
+ mem.cost() | ||
+ self.blocks; | ||
let _holding = Holding::new(&self.account, held); | ||
let holding = Holding::new(&self.account, held); | ||
let view = View { | ||
mem: &mem.spaces, | ||
old: spaces_old, | ||
| @@ -2452,8 +2546,9 @@ impl Fold for AccountFold { | ||
}; | ||
let mut frames = Frames { | ||
layout: &layout, | ||
cache: &cache, | ||
files: HashMap::new(), | ||
indexes: Indexes::default(), | ||
holding: Some(&holding), | ||
}; | ||
let werr = |e: io::Error| e.to_string(); | ||
let old = |prefix: u8| -> Rows<'_, String> { | ||
| @@ -2808,8 +2903,9 @@ fn legacy_fold( | ||
entries.insert(b"S".to_vec(), small.encode(did, now)); | ||
let mut frames = Frames { | ||
layout: &layout, | ||
cache: &cache, | ||
files: HashMap::new(), | ||
indexes: Indexes::default(), | ||
holding: None, | ||
}; | ||
let view = View { | ||
mem: &space_mem, | ||
| @@ -3282,6 +3378,135 @@ mod tests { | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
| ||
/// A fold reads each frame of its logs whole once, to index it, and | ||
/// then each item alone, however large the frame's index. An import's | ||
/// frame, one commit of a whole repository, has an index larger than the | ||
/// fold's block cache keeps any entry (an eighth of it, 4 MiB at most), | ||
/// which was made again, the whole frame read, for each of its items: | ||
/// so the import's log is compacted at once, as a write's is. | ||
#[tokio::test] | ||
async fn a_fold_indexes_each_frame_once() { | ||
use super::{ENTRY, Indexes, Want, read_at}; | ||
use axum::http::{HeaderMap, HeaderValue, Method, header}; | ||
const RECORDS: usize = 12_000; | ||
let plc = plc().await; | ||
let dir = scratch("ckpt-fold-index"); | ||
// Compacted only when the test says. | ||
let s = open_with(&dir, &plc, |c| c.log_floor = 1 << 30); | ||
let (did, token) = create(&s, "alice").await; | ||
// A repository of its records, imported whole: one frame. | ||
let key = k256::ecdsa::SigningKey::from_slice(&[5u8; 32]).unwrap(); | ||
let mut repo = pds_repo::full::Repo::new(did.clone(), key); | ||
repo.init(); | ||
for batch in (0..RECORDS).collect::<Vec<_>>().chunks(200) { | ||
let ops = batch | ||
.iter() | ||
.map(|i| pds_repo::Op::Create { | ||
collection: "a.b.c".into(), | ||
rkey: Some(format!("k{i:05}")), | ||
value: pds_repo::data::from_json(&record(*i as i64)).unwrap(), | ||
}) | ||
.collect(); | ||
repo.apply(ops, None).unwrap(); | ||
} | ||
let car = repo.car(); | ||
let mut headers = HeaderMap::new(); | ||
headers.insert( | ||
header::CONTENT_TYPE, | ||
HeaderValue::from_static("application/vnd.ipld.car"), | ||
); | ||
headers.insert( | ||
header::AUTHORIZATION, | ||
HeaderValue::from_str(&format!("Bearer {token}")).unwrap(), | ||
); | ||
let authorization = crate::authorization(&headers); | ||
let call = crate::Call { | ||
nsid: "com.atproto.repo.importRepo", | ||
method: &Method::POST, | ||
params: &[], | ||
body: &car, | ||
bearer: crate::sessions::Bearer::of(authorization.as_deref()), | ||
headers: &headers, | ||
client: "127.0.0.1".into(), | ||
charged: std::sync::OnceLock::new(), | ||
http: None, | ||
}; | ||
assert!(matches!( | ||
crate::answer(&s, &call).await, | ||
Ok(crate::Resp::Nothing) | ||
)); | ||
// The import's frame, and its items: its records and tree nodes. | ||
let layout = crate::store::account_layout(&dir, &did); | ||
let generation = store_of(&s, &did, |st| st.wal.generation()); | ||
let path = layout.log(generation); | ||
let mut found = None; | ||
pds_store::scan_file(&path, |offset, len, entries| { | ||
if let Some(c) = entries | ||
.iter() | ||
.find(|e| e["t"] == "commit" && e["puts"].as_array().unwrap().len() == RECORDS) | ||
{ | ||
found = Some((offset, len, c.clone())); | ||
} | ||
Ok(()) | ||
}) | ||
.unwrap() | ||
.unwrap(); | ||
let (offset, len, commit) = found.unwrap(); | ||
let unhex = |v: &Json| hex::decode(v.as_str().unwrap()).unwrap(); | ||
let mut cids: Vec<Vec<u8>> = commit["puts"] | ||
.as_array() | ||
.unwrap() | ||
.iter() | ||
.map(|p| unhex(&p[2])) | ||
.collect(); | ||
cids.extend( | ||
commit["tree"] | ||
.as_array() | ||
.unwrap() | ||
.iter() | ||
.map(|n| unhex(&n[0])), | ||
); | ||
assert!( | ||
cids.len() * ENTRY > (4 << 20) / 8, | ||
"an index the fold's cache would keep" | ||
); | ||
// Read as the fold reads them: the frame whole once, then each item alone. | ||
let pos = pds_store::Pos { | ||
generation, | ||
offset, | ||
len, | ||
}; | ||
let file = std::fs::File::open(&path).unwrap(); | ||
let whole = std::cell::Cell::new(0); | ||
let read = |at: u64, n: usize| { | ||
if (at, n) == (offset, len as usize) { | ||
whole.set(whole.get() + 1); | ||
} | ||
read_at(&file, at, n) | ||
}; | ||
let mut indexes = Indexes::default(); | ||
for cid in &cids { | ||
let block = indexes.item(pos, &read, Want::Block(cid)).unwrap(); | ||
assert!(block.is_some(), "{} missing", cid_string(cid)); | ||
} | ||
assert_eq!(whole.get(), 1, "the frame read whole for each of its items"); | ||
// And so the log is compacted in a moment, not in the time it takes | ||
// to read the frame once for each item. | ||
let wal = store_of(&s, &did, |st| st.wal.clone()); | ||
let started = std::time::Instant::now(); | ||
wal.compact().unwrap(); | ||
let took = started.elapsed(); | ||
assert!( | ||
took < std::time::Duration::from_secs(30), | ||
"compacted in {took:?}" | ||
); | ||
store_of(&s, &did, |st| { | ||
st.ctx.blocks.forget(st.disk.table.as_ref().unwrap().id()) | ||
}); | ||
assert_eq!(records_of(&s, &did).len(), RECORDS); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
| ||
/// The notifications' part of a table: written and read back whole, | ||
/// lapsed registrations and kept notices too. | ||
#[test] | ||