Skip to content

Commit cefe9fd

Browse files
Restore crash safety for database pruning (sigp#4975)
* Add some DB sanity checks * Restore crash safety for database pruning
1 parent 66d30bc commit cefe9fd

File tree

4 files changed

+59
-75
lines changed

4 files changed

+59
-75
lines changed

beacon_node/beacon_chain/src/builder.rs

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ use std::time::Duration;
3434
use store::{Error as StoreError, HotColdDB, ItemStore, KeyValueStoreOp};
3535
use task_executor::{ShutdownReason, TaskExecutor};
3636
use types::{
37-
BeaconBlock, BeaconState, ChainSpec, Checkpoint, Epoch, EthSpec, Graffiti, Hash256, Signature,
37+
BeaconBlock, BeaconState, ChainSpec, Epoch, EthSpec, Graffiti, Hash256, Signature,
3838
SignedBeaconBlock, Slot,
3939
};
4040

@@ -559,16 +559,6 @@ where
559559
.map_err(|e| format!("Failed to initialize blob info: {:?}", e))?,
560560
);
561561

562-
// Store pruning checkpoint to prevent attempting to prune before the anchor state.
563-
self.pending_io_batch.push(
564-
store
565-
.pruning_checkpoint_store_op(Checkpoint {
566-
root: weak_subj_block_root,
567-
epoch: weak_subj_state.slot().epoch(TEthSpec::slots_per_epoch()),
568-
})
569-
.map_err(|e| format!("{:?}", e))?,
570-
);
571-
572562
let snapshot = BeaconSnapshot {
573563
beacon_block_root: weak_subj_block_root,
574564
beacon_block: Arc::new(weak_subj_block),

beacon_node/beacon_chain/src/migrate.rs

Lines changed: 25 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -512,13 +512,7 @@ impl<E: EthSpec, Hot: ItemStore<E>, Cold: ItemStore<E>> BackgroundMigrator<E, Ho
512512
genesis_block_root: Hash256,
513513
log: &Logger,
514514
) -> Result<PruningOutcome, BeaconChainError> {
515-
let old_finalized_checkpoint =
516-
store
517-
.load_pruning_checkpoint()?
518-
.unwrap_or_else(|| Checkpoint {
519-
epoch: Epoch::new(0),
520-
root: Hash256::zero(),
521-
});
515+
let old_finalized_checkpoint = store.get_pruning_checkpoint();
522516

523517
let old_finalized_slot = old_finalized_checkpoint
524518
.epoch
@@ -572,6 +566,21 @@ impl<E: EthSpec, Hot: ItemStore<E>, Cold: ItemStore<E>> BackgroundMigrator<E, Ho
572566
})
573567
.collect::<Result<_, _>>()?;
574568

569+
// Quick sanity check. If the canonical block & state roots are incorrect then we could
570+
// incorrectly delete canonical states, which would corrupt the database.
571+
let expected_canonical_block_roots = new_finalized_slot
572+
.saturating_sub(old_finalized_slot)
573+
.as_usize()
574+
.saturating_add(1);
575+
if newly_finalized_chain.len() != expected_canonical_block_roots {
576+
return Err(BeaconChainError::DBInconsistent(format!(
577+
"canonical chain iterator is corrupt; \
578+
expected {} but got {} block roots",
579+
expected_canonical_block_roots,
580+
newly_finalized_chain.len()
581+
)));
582+
}
583+
575584
// We don't know which blocks are shared among abandoned chains, so we buffer and delete
576585
// everything in one fell swoop.
577586
let mut abandoned_blocks: HashSet<SignedBeaconBlockHash> = HashSet::new();
@@ -735,11 +744,6 @@ impl<E: EthSpec, Hot: ItemStore<E>, Cold: ItemStore<E>> BackgroundMigrator<E, Ho
735744
persisted_head.as_kv_store_op(BEACON_CHAIN_DB_KEY)?,
736745
));
737746

738-
// Persist the new finalized checkpoint as the pruning checkpoint.
739-
batch.push(StoreOp::KeyValueOp(
740-
store.pruning_checkpoint_store_op(new_finalized_checkpoint)?,
741-
));
742-
743747
store.do_atomically_with_block_and_blobs_cache(batch)?;
744748
debug!(
745749
log,
@@ -753,19 +757,26 @@ impl<E: EthSpec, Hot: ItemStore<E>, Cold: ItemStore<E>> BackgroundMigrator<E, Ho
753757
let (state_root, summary) = res?;
754758

755759
if summary.slot <= new_finalized_slot {
756-
// If state root doesn't match state root from canonical chain, or this slot
757-
// is not part of the recently finalized chain, then delete.
760+
// If state root doesn't match state root from canonical chain, then delete.
761+
// We may also find older states here that should have been deleted by `migrate_db`
762+
// but weren't due to wonky I/O atomicity.
758763
if newly_finalized_chain
759764
.get(&summary.slot)
760765
.map_or(true, |(_, canonical_state_root)| {
761766
state_root != Hash256::from(*canonical_state_root)
762767
})
763768
{
769+
let reason = if summary.slot < old_finalized_slot {
770+
"old dangling state"
771+
} else {
772+
"non-canonical"
773+
};
764774
debug!(
765775
log,
766776
"Deleting state";
767777
"state_root" => ?state_root,
768778
"slot" => summary.slot,
779+
"reason" => reason,
769780
);
770781
state_delete_batch.push(StoreOp::DeleteState(state_root, Some(summary.slot)));
771782
}

beacon_node/store/src/hot_cold_store.rs

Lines changed: 30 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@ use crate::iter::{BlockRootsIterator, ParentRootBlockIterator, RootsIterator};
1010
use crate::leveldb_store::{BytesKey, LevelDB};
1111
use crate::memory_store::MemoryStore;
1212
use crate::metadata::{
13-
AnchorInfo, BlobInfo, CompactionTimestamp, PruningCheckpoint, SchemaVersion, ANCHOR_INFO_KEY,
14-
BLOB_INFO_KEY, COMPACTION_TIMESTAMP_KEY, CONFIG_KEY, CURRENT_SCHEMA_VERSION,
15-
PRUNING_CHECKPOINT_KEY, SCHEMA_VERSION_KEY, SPLIT_KEY, STATE_UPPER_LIMIT_NO_RETAIN,
13+
AnchorInfo, BlobInfo, CompactionTimestamp, SchemaVersion, ANCHOR_INFO_KEY, BLOB_INFO_KEY,
14+
COMPACTION_TIMESTAMP_KEY, CONFIG_KEY, CURRENT_SCHEMA_VERSION, SCHEMA_VERSION_KEY, SPLIT_KEY,
15+
STATE_UPPER_LIMIT_NO_RETAIN,
1616
};
1717
use crate::metrics;
1818
use crate::state_cache::{PutStateOutcome, StateCache};
@@ -77,6 +77,8 @@ pub struct HotColdDB<E: EthSpec, Hot: ItemStore<E>, Cold: ItemStore<E>> {
7777
/// LRU cache of deserialized blocks and blobs. Updated whenever a block or blob is loaded.
7878
block_cache: Mutex<BlockCache<E>>,
7979
/// Cache of beacon states.
80+
///
81+
/// LOCK ORDERING: this lock must always be locked *after* the `split` if both are required.
8082
state_cache: Mutex<StateCache<E>>,
8183
/// Immutable validator cache.
8284
pub immutable_validators: Arc<RwLock<ValidatorPubkeyCache<E, Hot, Cold>>>,
@@ -2385,26 +2387,17 @@ impl<E: EthSpec, Hot: ItemStore<E>, Cold: ItemStore<E>> HotColdDB<E, Hot, Cold>
23852387
self.config.compact_on_prune
23862388
}
23872389

2388-
/// Load the checkpoint to begin pruning from (the "old finalized checkpoint").
2389-
pub fn load_pruning_checkpoint(&self) -> Result<Option<Checkpoint>, Error> {
2390-
Ok(self
2391-
.hot_db
2392-
.get(&PRUNING_CHECKPOINT_KEY)?
2393-
.map(|pc: PruningCheckpoint| pc.checkpoint))
2394-
}
2395-
2396-
/// Store the checkpoint to begin pruning from (the "old finalized checkpoint").
2397-
pub fn store_pruning_checkpoint(&self, checkpoint: Checkpoint) -> Result<(), Error> {
2398-
self.hot_db
2399-
.do_atomically(vec![self.pruning_checkpoint_store_op(checkpoint)?])
2400-
}
2401-
2402-
/// Create a staged store for the pruning checkpoint.
2403-
pub fn pruning_checkpoint_store_op(
2404-
&self,
2405-
checkpoint: Checkpoint,
2406-
) -> Result<KeyValueStoreOp, Error> {
2407-
PruningCheckpoint { checkpoint }.as_kv_store_op(PRUNING_CHECKPOINT_KEY)
2390+
/// Get the checkpoint to begin pruning from (the "old finalized checkpoint").
2391+
pub fn get_pruning_checkpoint(&self) -> Checkpoint {
2392+
// Since tree-states we infer the pruning checkpoint from the split, as this is simpler &
2393+
// safer in the presence of crashes that occur after pruning but before the split is
2394+
// updated.
2395+
// FIXME(sproul): ensure delete PRUNING_CHECKPOINT_KEY is deleted in DB migration
2396+
let split = self.get_split_info();
2397+
Checkpoint {
2398+
epoch: split.slot.epoch(E::slots_per_epoch()),
2399+
root: split.block_root,
2400+
}
24082401
}
24092402

24102403
/// Load the timestamp of the last compaction as a `Duration` since the UNIX epoch.
@@ -2917,8 +2910,8 @@ pub fn migrate_database<E: EthSpec, Hot: ItemStore<E>, Cold: ItemStore<E>>(
29172910
store.store_cold_state(&state_root, &state, &mut cold_db_ops)?;
29182911
}
29192912

2920-
// There are data dependencies between calls to `store_cold_state()` that prevent us from
2921-
// doing one big call to `store.cold_db.do_atomically()` at end of the loop.
2913+
// Cold states are diffed with respect to each other, so we need to finish writing previous
2914+
// states before storing new ones.
29222915
store.cold_db.do_atomically(cold_db_ops)?;
29232916
}
29242917

@@ -2927,15 +2920,20 @@ pub fn migrate_database<E: EthSpec, Hot: ItemStore<E>, Cold: ItemStore<E>>(
29272920
// procedure.
29282921
//
29292922
// Since it is pretty much impossible to be atomic across more than one database, we trade
2930-
// losing track of states to delete, for consistency. In other words: We should be safe to die
2931-
// at any point below but it may happen that some states won't be deleted from the hot database
2932-
// and will remain there forever. Since dying in these particular few lines should be an
2933-
// exceedingly rare event, this should be an acceptable tradeoff.
2923+
// temporarily losing track of blocks to delete, for consistency. In other words: We should be
2924+
// safe to die at any point below but it may happen that some blocks won't be deleted from the
2925+
// hot database and will remain there forever. We may also temporarily abandon states, but
2926+
// they will get picked up by the state pruning that iterates over the whole column.
29342927

29352928
// Flush to disk all the states that have just been migrated to the cold store.
29362929
store.cold_db.do_atomically(cold_db_block_ops)?;
29372930
store.cold_db.sync()?;
29382931

2932+
// Update the split.
2933+
//
2934+
// NOTE(sproul): We do this in its own fsync'd transaction mostly for historical reasons, but
2935+
// I'm scared to change it, because doing an fsync with *more data* while holding the split
2936+
// write lock might have terrible performance implications (jamming the split for 100-500ms+).
29392937
{
29402938
let mut split_guard = store.split.write();
29412939
let latest_split_slot = split_guard.slot;
@@ -2966,13 +2964,13 @@ pub fn migrate_database<E: EthSpec, Hot: ItemStore<E>, Cold: ItemStore<E>>(
29662964
};
29672965
store.hot_db.put_sync(&SPLIT_KEY, &split)?;
29682966

2969-
// Split point is now persisted in the hot database on disk. The in-memory split point
2970-
// hasn't been modified elsewhere since we keep a write lock on it. It's safe to update
2967+
// Split point is now persisted in the hot database on disk. The in-memory split point
2968+
// hasn't been modified elsewhere since we keep a write lock on it. It's safe to update
29712969
// the in-memory split point now.
29722970
*split_guard = split;
29732971
}
29742972

2975-
// Delete the states from the hot database if we got this far.
2973+
// Delete the blocks and states from the hot database if we got this far.
29762974
store.do_atomically_with_block_and_blobs_cache(hot_db_ops)?;
29772975

29782976
// Update the cache's view of the finalized state.

database_manager/src/lib.rs

Lines changed: 3 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -294,32 +294,17 @@ fn parse_inspect_config(cli_args: &ArgMatches) -> Result<InspectConfig, String>
294294
pub fn inspect_db<E: EthSpec>(
295295
inspect_config: InspectConfig,
296296
client_config: ClientConfig,
297-
runtime_context: &RuntimeContext<E>,
298-
log: Logger,
299297
) -> Result<(), String> {
300-
let spec = runtime_context.eth2_config.spec.clone();
301298
let hot_path = client_config.get_db_path();
302299
let cold_path = client_config.get_freezer_db_path();
303-
let blobs_path = client_config.get_blobs_db_path();
304-
305-
let db = HotColdDB::<E, LevelDB<E>, LevelDB<E>>::open(
306-
&hot_path,
307-
&cold_path,
308-
&blobs_path,
309-
|_, _, _| Ok(()),
310-
client_config.store,
311-
spec,
312-
log,
313-
)
314-
.map_err(|e| format!("{:?}", e))?;
315300

316301
let mut total = 0;
317302
let mut num_keys = 0;
318303

319304
let sub_db = if inspect_config.freezer {
320-
&db.cold_db
305+
LevelDB::<E>::open(&cold_path).map_err(|e| format!("Unable to open freezer DB: {e:?}"))?
321306
} else {
322-
&db.hot_db
307+
LevelDB::<E>::open(&hot_path).map_err(|e| format!("Unable to open hot DB: {e:?}"))?
323308
};
324309

325310
let skip = inspect_config.skip.unwrap_or(0);
@@ -653,7 +638,7 @@ pub fn run<T: EthSpec>(cli_args: &ArgMatches<'_>, env: Environment<T>) -> Result
653638
}
654639
("inspect", Some(cli_args)) => {
655640
let inspect_config = parse_inspect_config(cli_args)?;
656-
inspect_db(inspect_config, client_config, &context, log)
641+
inspect_db::<T>(inspect_config, client_config)
657642
}
658643
("prune-payloads", Some(_)) => {
659644
prune_payloads(client_config, &context, log).map_err(format_err)

0 commit comments

Comments
 (0)