Something went wrong. Try again.
contributor fork of @ptr.pet hydrant forked from ptr.pet/hydrant
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590use std::ops::Bound;
use fjall::{Keyspace, OwnedWriteBatch, Readable};use miette::{Context, IntoDiagnostic, Result};
use crate::db::Db;use crate::db::keys::{SEP, VERSIONING_KEY};
mod v1;mod v2;mod v3;mod v4;mod v5;mod v6;mod v7;mod v8;mod v9;
/// a migration whose entire write set is buffered into one batch.type AtomicFn = fn(&Db, &mut OwnedWriteBatch) -> Result<()>;
/// transform one scanned entry. staged writes may target any keyspace.type VisitFn = fn(&Db, &mut OwnedWriteBatch, &[u8], &[u8]) -> Result<()>;
/// how a migration is applied.enum Migration { /// the whole write set is buffered into one batch, committed atomically with /// the version bump. /// /// a batch is held entirely in memory, so this is only for migrations whose /// write set is small and bounded. it is *not* bounded by how much the /// migration reads: streaming a large keyspace to accumulate a handful of /// counters is fine, staging one write per entry of a large keyspace is not. Atomic(AtomicFn), /// ordered resumable passes, each committed in chunks with bounded memory. /// /// the only way to rewrite a keyspace larger than memory. passes run in /// order, and each runs to completion before the next starts. // no shipped migration needs chunking yet; the collection-interning rewrite // is the first consumer. exercised by this module's tests. #[allow(dead_code)] Chunked(&'static [Pass]),}
/// per-chunk limits. both bound peak batch memory; whichever is hit first ends/// the chunk. they also bound how much work a crash re-does.#[derive(Clone, Copy)]struct ChunkBudget { /// entries scanned per chunk. entries: usize, /// scanned key+value bytes per chunk. /// /// a proxy for staged bytes, which a `WriteBatch` does not expose. it keeps /// value-heavy keyspaces (`blocks` averages ~5 KiB/entry) from staging a /// multi-hundred-megabyte batch just because the entry count is low. bytes: usize,}
impl ChunkBudget { /// what a pass should use unless it has a measured reason not to. #[allow(dead_code)] const DEFAULT: Self = Self { entries: 100_000, bytes: 64 * 1024 * 1024, };}
/// one resumable key-ordered scan over a single keyspace.////// the framework owns iteration, chunk commits, and the resume cursor; a pass/// supplies only [`Pass::visit`].////// # visit must be idempotent////// the resume cursor advances only on a committed chunk, so a crash re-visits/// every entry of the in-flight chunk.////// more subtly, a pass that writes into the keyspace it scans can observe its/// own output. each chunk reads a fresh snapshot, so output that sorts *after*/// the resume cursor is scanned again in a later chunk. `visit` must therefore/// be safe to apply twice, and re-visiting its own output must reach a fixpoint/// — normally by making the migrated form recognizable and doing nothing when it/// is seen. a transform whose output sorts before its input (as key-shortening/// rewrites usually do) is never rescanned, but that is a property of the/// encoding, not a guarantee of the framework.struct Pass { /// stable cursor identity. THIS SHOULD ALWAYS BE STABLE. DO NOT CHANGE. name: &'static str, /// on-disk name of the keyspace to scan. /// /// a pass whose keyspace is not compiled into this build is skipped, so a /// migration can name mode-specific keyspaces unconditionally. /// /// a pass scanning `counts` also sees its own resume cursor, which sorts /// between the `k|` and `r|` prefixes; `visit` must ignore keys under /// [`MIGRATION_CURSOR_PREFIX`]. scan: &'static str, visit: VisitFn, budget: ChunkBudget,}
/// ordered list of schema migrations.////// invariants:/// - migration `vN` upgrades on-disk data from schema version `N-1` to `N`/// - once a migration ships, its input/output wire types are frozen/// - never "fix up" an older migration to match a newer live type; add a new/// schema version and a new migration instead/// - if a stored type changes shape, define a new versioned type in/// `src/types.rs`, export the newest one for live code, and have the new/// migration explicitly deserialize the previous version and write the new one/// - a migration that stages one write per entry of a high-cardinality keyspace/// must be [`Migration::Chunked`]; [`Migration::Atomic`] would buffer the/// whole rewrite in memory////// example: if `RepoState` changes again after `types::v7::RepoState`, add a new/// `types::v8::RepoState`, keep `v7` frozen, and add a migration that rewrites/// `v7 -> v8`./// ordered list of migrations. migration at index `i` upgrades the schema from version `i` to `i+1`.const MIGRATIONS: &[(&str, Migration)] = &[ ( "stable_firehose_cursors", Migration::Atomic(v1::stable_firehose_cursors), ), ( "repo_state_root_commit", Migration::Atomic(v2::repo_state_root_commit), ), ( "firehose_source_is_pds", Migration::Atomic(v3::firehose_source_is_pds), ), ( "repo_state_active", Migration::Atomic(v4::repo_state_active), ), ("pds_meta_layout", Migration::Atomic(v5::pds_meta_layout)), ( "rebuild_pds_account_counts", Migration::Atomic(v6::rebuild_pds_account_counts), ), ( "repo_state_event_clocks", Migration::Atomic(v7::repo_state_event_clocks), ), ( "rebuild_lifecycle_counts", Migration::Atomic(v8::rebuild_lifecycle_counts), ), ( "migrate_excludes_and_pds_keys", Migration::Atomic(v9::migrate_v9), ),];
#[cfg(test)]pub(crate) const LATEST_VERSION: u64 = MIGRATIONS.len() as u64;
/// resume cursors for chunked passes, in the `counts` keyspace:/// `mig|{version}|{pass}` -> last committed key.////// the `counts` compaction filter only drops `r|` and old `d|` entries, so these/// survive compaction.const MIGRATION_CURSOR_PREFIX: &[u8] = b"mig|";
fn pass_cursor_key(version: usize, pass: &str) -> Vec<u8> { let mut key = Vec::with_capacity(MIGRATION_CURSOR_PREFIX.len() + 8 + 1 + pass.len()); key.extend_from_slice(MIGRATION_CURSOR_PREFIX); key.extend_from_slice(&(version as u64).to_be_bytes()); key.push(SEP); key.extend_from_slice(pass.as_bytes()); key}
fn read_version(db: &Db) -> Result<u64> { db.counts .get(VERSIONING_KEY) .into_diagnostic()? .map(|r| { r.as_ref() .try_into() .into_diagnostic() .wrap_err("db version key expected to be 8 bytes") .map(u64::from_be_bytes) }) .transpose() .map(|v| v.unwrap_or(0))}
struct ChunkOutcome { /// entries visited and committed. seen: usize, /// the scan reached the end of the keyspace. exhausted: bool,}
/// visit one chunk of `pass`, committing the transformed entries and the/// advanced resume cursor as one atomic batch.fn run_chunk(db: &Db, cursor_key: &[u8], ks: &Keyspace, pass: &Pass) -> Result<ChunkOutcome> { let resume = db.counts.get(cursor_key).into_diagnostic()?; let start = resume .as_ref() .map_or(Bound::Unbounded, |k| Bound::Excluded(k.to_vec()));
let mut batch = db.inner.batch(); let mut seen = 0usize; let mut bytes = 0usize; let mut last = None; let mut exhausted = true;
{ // a fresh snapshot per chunk keeps the scan consistent while the batch is // staged, without pinning superseded versions for the whole pass. let snapshot = db.inner.snapshot(); for guard in snapshot.range(ks, (start, Bound::<Vec<u8>>::Unbounded)) { // checked before visiting, so breaking here proves an entry remains. // a chunk always visits at least one entry, so neither a degenerate // budget nor an entry larger than the byte budget can stall the pass // or make an unfinished scan look exhausted. if seen > 0 && (seen >= pass.budget.entries || bytes >= pass.budget.bytes) { exhausted = false; break; } let (key, value) = guard.into_inner().into_diagnostic()?; (pass.visit)(db, &mut batch, &key, &value) .wrap_err_with(|| format!("migration pass {} failed on an entry", pass.name))?; bytes += key.len() + value.len(); last = Some(key); seen += 1; } }
let Some(last) = last else { // nothing left to do; leave the cursor for `run` to clear with the // version bump return Ok(ChunkOutcome { seen: 0, exhausted: true, }); };
batch.insert(&db.counts, cursor_key, last); batch.commit().into_diagnostic()?;
Ok(ChunkOutcome { seen, exhausted })}
/// run one pass to completion, resuming from its stored cursor if present.fn run_pass(db: &Db, version: usize, pass: &Pass) -> Result<()> { let Some(ks) = db.keyspace_by_name(pass.scan) else { // keyspace is not compiled into this build, so there is nothing to migrate tracing::debug!( "db: migration pass {} skipped, keyspace {} not in this build", pass.name, pass.scan ); return Ok(()); }; let cursor_key = pass_cursor_key(version, pass.name);
if db.counts.contains_key(&cursor_key).into_diagnostic()? { tracing::info!("db: resuming migration pass {} from its cursor", pass.name); }
let mut total: u64 = 0; loop { let outcome = run_chunk(db, &cursor_key, &ks, pass)?; total += outcome.seen as u64; if outcome.seen > 0 { tracing::info!( "db: migration pass {} committed {total} entries so far", pass.name ); } if outcome.exhausted { break; } }
tracing::info!( "db: migration pass {} complete ({total} entries)", pass.name ); Ok(())}
/// run all pending database migrations in order.////// each migration's version bump is committed atomically with its final write:/// for [`Migration::Atomic`] that is the whole write set, for/// [`Migration::Chunked`] it is the removal of the pass cursors. a crash part/// way through a chunked migration therefore leaves the old version on disk, and/// the next open resumes each pass from its cursor.////// safe to run on a fresh database (all migrations are no-ops when no relevant/// data exists). called during [`Db::open`].pub(super) fn run(db: &Db) -> Result<()> { let version = read_version(db)? as usize; for (i, (name, migration)) in MIGRATIONS.iter().enumerate().skip(version) { tracing::info!("db: running migration {name} (v{i} -> v{})", i + 1); let mut batch = db.inner.batch(); match migration { Migration::Atomic(f) => f(db, &mut batch)?, Migration::Chunked(passes) => { for pass in *passes { run_pass(db, i, pass)?; // cleared with the version bump, so a crash after the last // chunk resumes at the end of the keyspace and finishes // immediately instead of rescanning it batch.remove(&db.counts, pass_cursor_key(i, pass.name)); } } } let new_version = (i + 1) as u64; batch.insert(&db.counts, VERSIONING_KEY, new_version.to_be_bytes()); batch.commit().into_diagnostic()?; tracing::info!("db: migration {name} complete"); } Ok(())}
#[cfg(test)]mod tests { use super::*;
const TEST_PREFIX: &[u8] = b"chunktest|"; const MIGRATED_PREFIX: &[u8] = b"chunkdone|";
/// rewrites `chunktest|{n}` to `chunkdone|{n}`, keeping the value. /// /// idempotent: already-migrated keys carry the new prefix and are ignored. /// note the output sorts *before* the input (`chunkd` < `chunkt`), which is /// the usual shape for a key rewrite and means output is never rescanned. fn rewrite_prefix( db: &Db, batch: &mut OwnedWriteBatch, key: &[u8], value: &[u8], ) -> Result<()> { let Some(suffix) = key.strip_prefix(TEST_PREFIX) else { return Ok(()); }; let mut new_key = MIGRATED_PREFIX.to_vec(); new_key.extend_from_slice(suffix); batch.insert(&db.cursors, new_key, value); batch.remove(&db.cursors, key); Ok(()) }
fn test_pass(entries: usize) -> Pass { Pass { name: "rewrite_prefix", scan: "cursors", visit: rewrite_prefix, budget: ChunkBudget { entries, bytes: usize::MAX, }, } }
fn open_db() -> Result<(tempfile::TempDir, Db)> { let tmp = tempfile::tempdir().into_diagnostic()?; let cfg = crate::config::Config { database_path: tmp.path().to_path_buf(), ..Default::default() }; let db = Db::open(&cfg)?; Ok((tmp, db)) }
fn seed(db: &Db, count: usize) -> Result<()> { let mut batch = db.inner.batch(); for i in 0..count { let mut key = TEST_PREFIX.to_vec(); key.extend_from_slice(&(i as u64).to_be_bytes()); batch.insert(&db.cursors, key, (i as u64).to_be_bytes()); } batch.commit().into_diagnostic()?; Ok(()) }
fn migrated(db: &Db) -> Result<Vec<(u64, u64)>> { db.cursors .prefix(MIGRATED_PREFIX) .map(|guard| { let (k, v) = guard.into_inner().into_diagnostic()?; let n = u64::from_be_bytes(k[MIGRATED_PREFIX.len()..].try_into().into_diagnostic()?); let v = u64::from_be_bytes(v.as_ref().try_into().into_diagnostic()?); Ok((n, v)) }) .collect() }
fn expected(count: usize) -> Vec<(u64, u64)> { (0..count as u64).map(|i| (i, i)).collect() }
#[test] fn chunked_pass_rewrites_every_entry_across_many_chunks() -> Result<()> { let (_tmp, db) = open_db()?; seed(&db, 50)?;
let pass = test_pass(7); run_pass(&db, 99, &pass)?;
assert_eq!(migrated(&db)?, expected(50)); assert_eq!(db.cursors.prefix(TEST_PREFIX).count(), 0); Ok(()) }
#[test] fn interrupted_pass_resumes_and_matches_an_uninterrupted_run() -> Result<()> { let (_tmp, db) = open_db()?; seed(&db, 50)?;
let pass = test_pass(7); let cursor_key = pass_cursor_key(99, pass.name); let ks = db.keyspace_by_name("cursors").expect("cursors keyspace");
// one chunk only, standing in for a crash mid-pass let first = run_chunk(&db, &cursor_key, &ks, &pass)?; assert_eq!(first.seen, 7); assert!(!first.exhausted); assert_eq!(migrated(&db)?, expected(7)); assert!(db.counts.contains_key(&cursor_key).into_diagnostic()?);
// reopening resumes from the cursor rather than restarting run_pass(&db, 99, &pass)?;
assert_eq!(migrated(&db)?, expected(50)); assert_eq!(db.cursors.prefix(TEST_PREFIX).count(), 0); Ok(()) }
#[test] fn completed_pass_is_a_cheap_no_op_when_rerun() -> Result<()> { let (_tmp, db) = open_db()?; seed(&db, 20)?;
let pass = test_pass(7); run_pass(&db, 99, &pass)?; let after_first = migrated(&db)?;
// the cursor survives until the version bump, so a rerun scans nothing let cursor_key = pass_cursor_key(99, pass.name); let ks = db.keyspace_by_name("cursors").expect("cursors keyspace"); let outcome = run_chunk(&db, &cursor_key, &ks, &pass)?; assert_eq!(outcome.seen, 0); assert!(outcome.exhausted);
assert_eq!(migrated(&db)?, after_first); Ok(()) }
#[test] fn visiting_migrated_entries_again_is_a_fixpoint() -> Result<()> { let (_tmp, db) = open_db()?; seed(&db, 20)?;
let pass = test_pass(7); run_pass(&db, 99, &pass)?; let after_first = migrated(&db)?;
// drop the cursor to force a full rescan over already-migrated entries, // the worst case the idempotency contract has to survive db.counts .remove(pass_cursor_key(99, pass.name)) .into_diagnostic()?; run_pass(&db, 99, &pass)?;
assert_eq!(migrated(&db)?, after_first); Ok(()) }
/// fails partway through a chunk, standing in for a crash mid-chunk. fn fail_partway(db: &Db, batch: &mut OwnedWriteBatch, key: &[u8], value: &[u8]) -> Result<()> { let Some(suffix) = key.strip_prefix(TEST_PREFIX) else { return Ok(()); }; let n = u64::from_be_bytes(suffix.try_into().into_diagnostic()?); if n == 4 { miette::bail!("simulated failure at entry 4"); } rewrite_prefix(db, batch, key, value) }
#[test] fn a_chunk_that_fails_partway_commits_nothing() -> Result<()> { let (_tmp, db) = open_db()?; seed(&db, 50)?;
let pass = Pass { visit: fail_partway, ..test_pass(7) }; let cursor_key = pass_cursor_key(99, pass.name); let ks = db.keyspace_by_name("cursors").expect("cursors keyspace");
assert!(run_chunk(&db, &cursor_key, &ks, &pass).is_err());
// entries 0..=3 were staged before the failure, but the batch is dropped // uncommitted, so neither they nor the cursor survive assert_eq!(migrated(&db)?, vec![]); assert!(!db.counts.contains_key(&cursor_key).into_diagnostic()?); assert_eq!(db.cursors.prefix(TEST_PREFIX).count(), 50);
// retrying with a working visit starts over from the beginning run_pass(&db, 99, &test_pass(7))?; assert_eq!(migrated(&db)?, expected(50)); Ok(()) }
#[test] fn byte_budget_ends_a_chunk_before_the_entry_budget() -> Result<()> { let (_tmp, db) = open_db()?; seed(&db, 50)?;
// each entry is 26 scanned bytes (10-byte prefix + 8-byte key + 8-byte // value), and the budget is checked before visiting, so a 60-byte budget // admits 3 entries (26, 52, 78) before it trips let pass = Pass { budget: ChunkBudget { entries: usize::MAX, bytes: 60, }, ..test_pass(0) }; let cursor_key = pass_cursor_key(99, pass.name); let ks = db.keyspace_by_name("cursors").expect("cursors keyspace");
let outcome = run_chunk(&db, &cursor_key, &ks, &pass)?; assert_eq!(outcome.seen, 3); assert!(!outcome.exhausted);
run_pass(&db, 99, &pass)?; assert_eq!(migrated(&db)?, expected(50)); Ok(()) }
#[test] fn a_degenerate_budget_still_makes_progress() -> Result<()> { let (_tmp, db) = open_db()?; seed(&db, 5)?;
// a zero budget would otherwise trip before visiting anything, leaving // the chunk with no cursor to advance and reporting itself exhausted let pass = Pass { budget: ChunkBudget { entries: 0, bytes: 0, }, ..test_pass(0) }; let cursor_key = pass_cursor_key(99, pass.name); let ks = db.keyspace_by_name("cursors").expect("cursors keyspace");
let outcome = run_chunk(&db, &cursor_key, &ks, &pass)?; assert_eq!(outcome.seen, 1); assert!(!outcome.exhausted);
run_pass(&db, 99, &pass)?; assert_eq!(migrated(&db)?, expected(5)); Ok(()) }
#[test] fn pass_on_a_keyspace_missing_from_this_build_is_skipped() -> Result<()> { let (_tmp, db) = open_db()?;
let pass = Pass { scan: "not_a_keyspace", ..test_pass(7) }; run_pass(&db, 99, &pass)?;
let cursor_key = pass_cursor_key(99, pass.name); assert!(!db.counts.contains_key(&cursor_key).into_diagnostic()?); Ok(()) }
#[test] fn cursor_keys_are_distinct_per_version_and_pass() { assert_ne!(pass_cursor_key(1, "a"), pass_cursor_key(2, "a")); assert_ne!(pass_cursor_key(1, "a"), pass_cursor_key(1, "b")); assert!(pass_cursor_key(1, "a").starts_with(MIGRATION_CURSOR_PREFIX)); }}