Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: always acquire numbers lock first #10842

Merged
merged 2 commits into from
Sep 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions crates/chain-state/src/in_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,16 @@ pub(crate) struct InMemoryStateMetrics {
///
/// This tracks blocks and their state that haven't been persisted to disk yet but are part of the
/// canonical chain that can be traced back to a canonical block on disk.
///
/// # Locking behavior on state updates
///
/// All update calls must be atomic, meaning that they must acquire all locks at once, before
/// modifying the state. This is to ensure that the internal state is always consistent.
/// Update functions ensure that the numbers write lock is always acquired first, because lookup by
/// numbers first read the numbers map and then the blocks map.
/// By acquiring the numbers lock first, we ensure that read-only lookups don't deadlock updates.
/// This holds, because only lookup by number functions need to acquire the numbers lock first to
/// get the block hash.
#[derive(Debug, Default)]
pub(crate) struct InMemoryState {
/// All canonical blocks that are not on disk yet.
Expand Down Expand Up @@ -138,10 +148,11 @@ impl CanonicalInMemoryStateInner {
/// Clears all entries in the in memory state.
fn clear(&self) {
{
let mut blocks = self.in_memory_state.blocks.write();
// acquire locks, starting with the numbers lock
let mut numbers = self.in_memory_state.numbers.write();
blocks.clear();
let mut blocks = self.in_memory_state.blocks.write();
numbers.clear();
blocks.clear();
self.in_memory_state.pending.send_modify(|p| {
p.take();
});
Expand Down Expand Up @@ -239,7 +250,7 @@ impl CanonicalInMemoryState {
I: IntoIterator<Item = ExecutedBlock>,
{
{
// acquire all locks
// acquire locks, starting with the numbers lock
let mut numbers = self.inner.in_memory_state.numbers.write();
let mut blocks = self.inner.in_memory_state.blocks.write();

Expand Down Expand Up @@ -301,8 +312,9 @@ impl CanonicalInMemoryState {
}

{
let mut blocks = self.inner.in_memory_state.blocks.write();
// acquire locks, starting with the numbers lock
let mut numbers = self.inner.in_memory_state.numbers.write();
let mut blocks = self.inner.in_memory_state.blocks.write();

let BlockNumHash { number: persisted_height, hash: _ } = persisted_num_hash;

Expand Down
Loading