Skip to content
Draft
Show file tree
Hide file tree
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
8 changes: 4 additions & 4 deletions nomt/src/bitbox/rehash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ pub(crate) fn finish_pending_rehash(path: &Path, page_pool: &PagePool) -> anyhow
.write(true)
.open(&meta_path)
.with_context(|| format!("failed to open {}", meta_path.display()))?;
let mut meta = Meta::read(page_pool, &meta_fd)
let (mut meta, pending_value_log) = Meta::read_with_pending(page_pool, &meta_fd)
.with_context(|| format!("failed to read {}", meta_path.display()))?;
meta.validate()?;

Expand All @@ -93,7 +93,7 @@ pub(crate) fn finish_pending_rehash(path: &Path, page_pool: &PagePool) -> anyhow
}
n if n == marker.old_num_pages && ht_len == new_len => {
meta.bitbox_num_pages = marker.new_num_pages;
Meta::write(page_pool, &meta_fd, &meta)
Meta::write_with_pending(page_pool, &meta_fd, &meta, pending_value_log)
.context("failed to finish pending rehash metadata update")?;
}
n if n == marker.old_num_pages && ht_len == old_len => {
Expand Down Expand Up @@ -135,7 +135,7 @@ pub(crate) fn grow_hashtable(
.write(true)
.open(&meta_path)
.with_context(|| format!("failed to open {}", meta_path.display()))?;
let mut meta = Meta::read(page_pool, &meta_fd)
let (mut meta, pending_value_log) = Meta::read_with_pending(page_pool, &meta_fd)
.with_context(|| format!("failed to read {}", meta_path.display()))?;
meta.validate()?;

Expand Down Expand Up @@ -166,7 +166,7 @@ pub(crate) fn grow_hashtable(
sync_dir(path)?;

meta.bitbox_num_pages = new_num_pages;
Meta::write(page_pool, &meta_fd, &meta).context("failed to update NOMT metadata")?;
Meta::write_with_pending(page_pool, &meta_fd, &meta, pending_value_log).context("failed to update NOMT metadata")?;

remove_file_if_exists(&path.join(MARKER_FILE))?;
sync_dir(path)?;
Expand Down
30 changes: 27 additions & 3 deletions nomt/src/store/meta.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ use std::os::unix::fs::FileExt as _;
use crate::io::{self, PagePool};

pub(crate) const MAGIC: [u8; 4] = *b"NOMT";
pub(crate) const VERSION: u32 = 1;
/// Version 2 adds the pending value log marker after the encoded [`Meta`].
pub(crate) const VERSION: u32 = 2;
pub(crate) const META_SIZE: usize = 64;

/// This data structure describes the state of the btree.
Expand Down Expand Up @@ -138,16 +139,39 @@ impl Meta {
}

pub fn read(page_pool: &PagePool, fd: &File) -> std::io::Result<Self> {
Ok(Self::read_with_pending(page_pool, fd)?.0)
}

/// Reads the meta and the sync seqn of the pending value log, 0 if none.
pub fn read_with_pending(page_pool: &PagePool, fd: &File) -> std::io::Result<(Self, u32)> {
let page = io::read_page(page_pool, fd, 0)?;
let meta = Meta::decode(&page[..META_SIZE]);
Ok(meta)
let pending = if meta.version >= 2 {
u32::from_le_bytes(page[META_SIZE..META_SIZE + 4].try_into().unwrap())
} else {
0
};
Ok((meta, pending))
}

pub fn write(page_pool: &PagePool, fd: &File, meta: &Meta) -> std::io::Result<()> {
Self::write_with_pending(page_pool, fd, meta, 0)
}

/// Writes the meta, marking the value log of sync `pending` as not yet applied to the
/// beatree pages. 0 means none.
pub fn write_with_pending(
page_pool: &PagePool,
fd: &File,
meta: &Meta,
pending: u32,
) -> std::io::Result<()> {
let mut page = page_pool.alloc_fat_page();
page.fill(0);
meta.encode_to(&mut page.as_mut()[..META_SIZE]);
page[META_SIZE..META_SIZE + 4].copy_from_slice(&pending.to_le_bytes());
fd.write_all_at(&page[..], 0)?;
fd.sync_all()?;
fd.sync_data()?;
Ok(())
}
}
Expand Down
49 changes: 48 additions & 1 deletion nomt/src/store/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ mod flock;
pub(crate) mod meta;
mod page_loader;
mod sync;
mod value_log;

/// This is a lightweight handle and can be cloned cheaply.
#[derive(Clone)]
Expand All @@ -43,7 +44,11 @@ struct Shared {
pages: bitbox::DB,
rollback: Option<Rollback>,
io_pool: IoPool,
/// Writes out the hash-table pages after the manifest, so the beatree update that runs
/// meanwhile does not queue behind them.
ht_io_pool: IoPool,
meta_fd: File,
value_log_fd: File,
flock: Option<flock::Flock>,
poisoned: AtomicBool,

Expand Down Expand Up @@ -86,6 +91,7 @@ impl Store {
}

let io_pool = io::start_io_pool(o.io_workers, page_pool.clone());
let ht_io_pool = io::start_io_pool(o.io_workers, page_pool.clone());

let meta_fd = {
let mut options = OpenOptions::new();
Expand Down Expand Up @@ -146,7 +152,15 @@ impl Store {
}
}

let meta = meta::Meta::read(&page_pool, &meta_fd)?;
let value_log_fd = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&o.path.join("value_log"))?;
// A manifest may reference the log, so its directory entry must be durable.
db_dir_fd.sync_all()?;

let (mut meta, pending_value_log) = meta::Meta::read_with_pending(&page_pool, &meta_fd)?;
meta.validate()?;
let values = beatree::Tree::open(
page_pool.clone(),
Expand Down Expand Up @@ -180,20 +194,52 @@ impl Store {
)
})
.transpose()?;

// The last sync wrote its manifest but maybe not its beatree pages: apply its changeset
// to the beatree state the manifest records.
if pending_value_log != 0 {
if pending_value_log != meta.sync_seqn {
anyhow::bail!(
"pending value log {} does not match sync {}",
pending_value_log,
meta.sync_seqn
);
}
let changeset = value_log::read(&value_log_fd, pending_value_log)?;
let mut beatree_sync = values.sync();
beatree_sync.begin_sync(changeset);
let beatree_meta = beatree_sync.wait_pre_meta()?;
meta.version = meta::VERSION;
meta.ln_freelist_pn = beatree_meta.ln_freelist_pn;
meta.ln_bump = beatree_meta.ln_bump;
meta.bbn_freelist_pn = beatree_meta.bbn_freelist_pn;
meta.bbn_bump = beatree_meta.bbn_bump;
Meta::write(&page_pool, &meta_fd, &meta)?;
crate::task::join_task(&beatree_sync.post_meta());
}

Ok(Self {
sync: Arc::new(Mutex::new(sync::Sync::new(
meta.sync_seqn,
meta.bitbox_num_pages,
meta.bitbox_seed,
o.panic_on_sync,
beatree::SyncData {
ln_freelist_pn: meta.ln_freelist_pn,
ln_bump: meta.ln_bump,
bbn_freelist_pn: meta.bbn_freelist_pn,
bbn_bump: meta.bbn_bump,
},
))),
shared: Arc::new(Shared {
rollback,
values,
pages,
io_pool,
ht_io_pool,
_db_dir_fd: db_dir_fd,
meta_fd,
value_log_fd,
flock: Some(flock),
poisoned: false.into(),
}),
Expand Down Expand Up @@ -317,6 +363,7 @@ impl Drop for Shared {
// Otherwise, these IO workers might still be writing to the files while another process
// acquired the flock.
self.io_pool.shutdown();
self.ht_io_pool.shutdown();
drop(self.flock.take());
}
}
Expand Down
138 changes: 83 additions & 55 deletions nomt/src/store/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use nomt_core::page_id::PageId;

use super::{
meta::{self, Meta},
DirtyPage, Shared,
value_log, DirtyPage, Shared,
};
use crate::{
beatree, bitbox, options::PanicOnSyncMode, page_cache::PageCache, rollback, task::join_task,
Expand All @@ -13,6 +13,8 @@ pub struct Sync {
pub(crate) bitbox_num_pages: u32,
pub(crate) bitbox_seed: [u8; 16],
pub(crate) panic_on_sync: Option<PanicOnSyncMode>,
/// The beatree state recorded in the last manifest.
pub(crate) beatree: beatree::SyncData,
}

impl Sync {
Expand All @@ -21,15 +23,23 @@ impl Sync {
bitbox_num_pages: u32,
bitbox_seed: [u8; 16],
panic_on_sync: Option<PanicOnSyncMode>,
beatree: beatree::SyncData,
) -> Self {
Self {
sync_seqn,
bitbox_num_pages,
bitbox_seed,
panic_on_sync,
beatree,
}
}

/// Commits the changes.
///
/// The manifest is written as soon as the hash-table WAL, the rollback delta and the value log
/// are durable, without waiting for the beatree pages. It records the previous beatree state
/// and marks the value log as pending. The hash-table pages are then written while the beatree
/// update finishes, and a second manifest write records the new beatree state.
pub fn sync(
&mut self,
shared: &Shared,
Expand All @@ -48,63 +58,81 @@ impl Sync {
let mut rollback_sync = rollback.as_ref().map(|rollback| rollback.sync());

bitbox_sync.begin_sync(sync_seqn, page_cache, updated_pages);
beatree_sync.begin_sync(value_tx);

// Persist the rollback delta while the trees are being prepared. All of them must
// succeed before the manifest references their new state.
let rollback_result = match rollback_delta {
// UNWRAP: a rollback delta is only produced when rollback is enabled.
Some(delta) => rollback.as_ref().unwrap().commit(delta),
None => Ok(()),
};
let bitbox_result = bitbox_sync.wait_pre_meta();
let beatree_result = beatree_sync.wait_pre_meta();
rollback_result?;
bitbox_result?;
let beatree_meta_wd = beatree_result?;

let (rollback_start_live, rollback_end_live) = match rollback_sync {
Some(ref mut rollback) => rollback.begin_sync(),
None => (0, 0),
};

if let Some(PanicOnSyncMode::PostWal) = self.panic_on_sync {
panic!("panic_on_sync is true (post-wal)")
}

let new_meta = Meta {
magic: meta::MAGIC,
version: meta::VERSION,
ln_freelist_pn: beatree_meta_wd.ln_freelist_pn,
ln_bump: beatree_meta_wd.ln_bump,
bbn_freelist_pn: beatree_meta_wd.bbn_freelist_pn,
bbn_bump: beatree_meta_wd.bbn_bump,
sync_seqn,
bitbox_num_pages: self.bitbox_num_pages,
bitbox_seed: self.bitbox_seed,
rollback_start_live,
rollback_end_live,
};
Meta::write(&shared.io_pool.page_pool(), &shared.meta_fd, &new_meta)?;
self.sync_seqn += 1;

if let Some(PanicOnSyncMode::PostMeta) = self.panic_on_sync {
panic!("panic_on_sync is true (post-meta)");
}
let changeset: Vec<_> = value_tx.into_iter().collect();
let value_log = value_log::encode(sync_seqn, &changeset);
beatree_sync.begin_sync(changeset);

if let Some(ref mut rollback) = rollback_sync {
rollback.post_meta();
}
std::thread::scope(|s| -> anyhow::Result<()> {
let value_log_write = s.spawn(|| value_log::write(&shared.value_log_fd, &value_log));

// Finish the beatree sync while the hash-table pages are written out.
let beatree_post_meta = beatree_sync.post_meta();
let bitbox_result = bitbox_sync.post_meta(shared.io_pool.make_handle());
join_task(&beatree_post_meta);
bitbox_result?;
// Persist the rollback delta while the trees are being prepared. All of them must
// succeed before the manifest references their new state.
let rollback_result = match rollback_delta {
// UNWRAP: a rollback delta is only produced when rollback is enabled.
Some(delta) => rollback.as_ref().unwrap().commit(delta),
None => Ok(()),
};
let bitbox_result = bitbox_sync.wait_pre_meta();
// UNWRAP: the writer does not panic.
let value_log_result = value_log_write.join().unwrap();
rollback_result?;
bitbox_result?;
value_log_result?;

if let Some(ref rollback) = rollback_sync {
rollback.wait_post_meta()?;
}
Ok(())
let (rollback_start_live, rollback_end_live) = match rollback_sync {
Some(ref mut rollback) => rollback.begin_sync(),
None => (0, 0),
};

if let Some(PanicOnSyncMode::PostWal) = self.panic_on_sync {
panic!("panic_on_sync is true (post-wal)")
}

let mut new_meta = Meta {
magic: meta::MAGIC,
version: meta::VERSION,
ln_freelist_pn: self.beatree.ln_freelist_pn,
ln_bump: self.beatree.ln_bump,
bbn_freelist_pn: self.beatree.bbn_freelist_pn,
bbn_bump: self.beatree.bbn_bump,
sync_seqn,
bitbox_num_pages: self.bitbox_num_pages,
bitbox_seed: self.bitbox_seed,
rollback_start_live,
rollback_end_live,
};
let page_pool = shared.io_pool.page_pool();
Meta::write_with_pending(&page_pool, &shared.meta_fd, &new_meta, sync_seqn)?;
self.sync_seqn += 1;

if let Some(ref mut rollback) = rollback_sync {
rollback.post_meta();
}

// Write out the hash-table pages while the beatree update completes.
let ht_writeout = s.spawn(|| bitbox_sync.post_meta(shared.ht_io_pool.make_handle()));

let beatree_result = beatree_sync.wait_pre_meta();
if let Some(PanicOnSyncMode::PostMeta) = self.panic_on_sync {
panic!("panic_on_sync is true (post-meta)");
}
let beatree_meta = beatree_result?;
new_meta.ln_freelist_pn = beatree_meta.ln_freelist_pn;
new_meta.ln_bump = beatree_meta.ln_bump;
new_meta.bbn_freelist_pn = beatree_meta.bbn_freelist_pn;
new_meta.bbn_bump = beatree_meta.bbn_bump;
Meta::write(&page_pool, &shared.meta_fd, &new_meta)?;
self.beatree = beatree_meta;

join_task(&beatree_sync.post_meta());
// UNWRAP: the writeout does not panic.
ht_writeout.join().unwrap()?;

if let Some(ref rollback) = rollback_sync {
rollback.wait_post_meta()?;
}
Ok(())
})
}
}
Loading
Loading