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
13 changes: 8 additions & 5 deletions nomt/src/beatree/branch/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::{
ops::bit_ops::{bitwise_memcpy, reconstruct_key},
Key,
},
io::{page_pool::Page, FatPage, PagePool},
io::{FatPage, PagePool, PAGE_SIZE},
};

// Here is the layout of a branch node:
Expand Down Expand Up @@ -44,6 +44,13 @@ pub struct BranchNode {
pub(super) page: FatPage,
}

impl AsRef<[u8; PAGE_SIZE]> for BranchNode {
fn as_ref(&self) -> &[u8; PAGE_SIZE] {
// UNWRAP: a `FatPage` always derefs to a slice of exactly `PAGE_SIZE` bytes.
self.as_slice().try_into().unwrap()
}
}

impl BranchNode {
pub fn new_in(page_pool: &PagePool) -> Self {
BranchNode {
Expand All @@ -55,10 +62,6 @@ impl BranchNode {
&*self.page
}

pub fn page(&self) -> Page {
self.page.page()
}

pub fn view(&self) -> BranchNodeView<'_> {
BranchNodeView {
inner: self.as_slice(),
Expand Down
7 changes: 7 additions & 0 deletions nomt/src/beatree/leaf/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,13 @@ pub struct LeafNode {
pub inner: FatPage,
}

impl AsRef<[u8; PAGE_SIZE]> for LeafNode {
fn as_ref(&self) -> &[u8; PAGE_SIZE] {
// UNWRAP: a `FatPage` always derefs to a slice of exactly `PAGE_SIZE` bytes.
(&*self.inner).try_into().unwrap()
}
}

impl LeafNode {
#[inline]
pub fn n(&self) -> usize {
Expand Down
7 changes: 5 additions & 2 deletions nomt/src/beatree/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -486,8 +486,11 @@ impl SyncController {
/// This must be called after [`Self::begin_sync`].
pub fn wait_pre_meta(&mut self) -> std::io::Result<SyncData> {
join_task(&self.begin_sync_result_rx)?;
self.inner.sync.bbn_fsync.wait()?;
self.inner.sync.ln_fsync.wait()?;
// Both fsyncs have started; wait for both even when one fails.
let bbn_result = self.inner.sync.bbn_fsync.wait();
let ln_result = self.inner.sync.ln_fsync.wait();
bbn_result?;
ln_result?;

// UNWRAP: fsync of bbn and ln above ensures that sync_data is Some.
let sync_data = self.inner.sync_data.lock().take().unwrap();
Expand Down
20 changes: 4 additions & 16 deletions nomt/src/beatree/ops/update/branch_stage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::{
index::Index,
Key,
},
task::{join_task, spawn_task},
task::{join_task_result, spawn_task},
};

use super::branch_updater::{BaseBranch, BranchUpdater, DigestResult as BranchDigestResult};
Expand All @@ -22,21 +22,13 @@ use super::extend_range_protocol::{
/// Tracker of all changes that happen to branch nodes during an update
pub type BranchesTracker = super::NodesTracker<BranchNode>;

/// Data, including buffers, which may be dropped only once I/O has certainly concluded.
#[derive(Default)]
pub struct PostIoDrop {
deferred_drop_pages: Vec<Vec<Arc<BranchNode>>>,
}

/// Outputs of the branch stage.
#[derive(Default)]
pub struct BranchStageOutput {
/// The page numbers of all freed pages.
pub freed_pages: Vec<PageNumber>,
/// The number of submitted I/Os.
pub submitted_io: usize,
/// Data which should be dropped after all submitted I/Os have concluded.
pub post_io_drop: PostIoDrop,
}

/// Change the btree's branch nodes in the specified way.
Expand Down Expand Up @@ -96,8 +88,8 @@ pub fn run(
let mut output = BranchStageOutput::default();
let mut branch_changeset: Vec<(Key, Option<Arc<BranchNode>>)> = vec![];

for _ in 0..num_workers {
let worker_output = join_task(&worker_result_rx)?;
for completed in 0..num_workers {
let worker_output = join_task_result(&worker_result_rx, num_workers - completed - 1)?;
apply_bbn_changes(&mut output, &mut branch_changeset, worker_output);
}

Expand Down Expand Up @@ -135,9 +127,6 @@ fn apply_bbn_changes(
output
.freed_pages
.extend(worker_output.branches_tracker.extra_freed.drain(..));
output.post_io_drop.deferred_drop_pages.push(std::mem::take(
&mut worker_output.branches_tracker.deferred_drop_pages,
));
}

// Branch changeset is created by aggregating the outcomes of multiple workers,
Expand Down Expand Up @@ -485,10 +474,9 @@ impl super::branch_updater::HandleNewBranch for NewBranchHandler {
bbn.set_bbn_pn(page_number.0);
let bbn = Arc::new(bbn);

let page = bbn.page();
self.io_handle
.send(IoCommand {
kind: IoKind::WriteRaw(fd, page_number.0 as u64, page),
kind: IoKind::WriteShared(fd, page_number.0 as u64, bbn.clone()),
user_data: 0,
})
.expect("I/O Pool Down");
Expand Down
9 changes: 4 additions & 5 deletions nomt/src/beatree/ops/update/leaf_stage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use crate::beatree::{
Key, ValueChange,
};
use crate::io::{IoCommand, IoHandle, IoKind};
use crate::task::{join_task, spawn_task};
use crate::task::{join_task_result, spawn_task};

/// Tracker of all changes that happen to leaves during an update
pub type LeavesTracker = super::NodesTracker<LeafNode>;
Expand Down Expand Up @@ -174,8 +174,8 @@ pub fn run(
let mut output = LeafStageOutput::default();
output.submitted_io += overflow_io;

for _ in 0..num_workers {
let worker_output = join_task(&worker_result_rx)?;
for completed in 0..num_workers {
let worker_output = join_task_result(&worker_result_rx, num_workers - completed - 1)?;
apply_worker_changes(&leaf_reader, &mut output, worker_output);
}

Expand Down Expand Up @@ -717,10 +717,9 @@ impl super::leaf_updater::HandleNewLeaf for NewLeafHandler {

let page_number = self.leaf_writer.allocate()?;

let page = leaf.inner.page();
self.io_handle
.send(IoCommand {
kind: IoKind::WriteRaw(fd, page_number.0 as u64, page),
kind: IoKind::WriteShared(fd, page_number.0 as u64, leaf.clone()),
user_data: 0,
})
.expect("I/O Pool Down");
Expand Down
13 changes: 6 additions & 7 deletions nomt/src/beatree/ops/update/leaf_updater.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,15 +227,14 @@ impl LeafUpdater {
},
};

if from == to {
// nothing to keep
return;
if from != to {
let values_size = base.node.values_size(from, to);
self.ops.push(LeafOp::KeepChunk(from, to, values_size));
self.gauge.ingest(to - from, values_size);
}

let values_size = base.node.values_size(from, to);
self.ops.push(LeafOp::KeepChunk(from, to, values_size));
self.gauge.ingest(to - from, values_size);

// Replacing a cell must reclaim its overflow pages even when no preceding
// cells were kept (the first key, or consecutive updated keys).
if found {
let (val, overflow) = base.cell(to);
if overflow {
Expand Down
13 changes: 5 additions & 8 deletions nomt/src/beatree/ops/update/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,16 +93,18 @@ pub fn update(
crate::beatree::writeout::submit_freelist_write(&io_handle, &leaf_store, ln_freelist_pages);
crate::beatree::writeout::submit_freelist_write(&io_handle, &bbn_store, bbn_freelist_pages);

// make sure that all write requests succeeded.
// Drain every submitted request, including when an earlier write failed, and keep the first
// error.
let mut write_result = Ok(());
for _ in 0..total_io {
// UNWRAP: we receive only what we sent. No `RecvErr` expected.
io_handle.recv().unwrap().result?;
write_result = write_result.and(io_handle.recv().unwrap().result);
}
write_result?;

let (tx, rx) = crossbeam_channel::bounded(1);
let post_io_task = move || {
leaf_stage_outputs.post_io_work.run(&leaf_cache);
drop(branch_stage_outputs.post_io_drop);
leaf_cache.evict();
};
spawn_task(&thread_pool, post_io_task, tx);
Expand Down Expand Up @@ -138,9 +140,6 @@ pub struct NodesTracker<Node> {
pub pending_base: Option<(Key, Arc<Node>, Option<Key>)>,
/// Page numbers which were allocated and discarded entirely during this update.
pub extra_freed: Vec<PageNumber>,
/// Pages which are potentially being written and which must be kept alive until I/O
/// is guaranteed complete.
pub deferred_drop_pages: Vec<Arc<Node>>,
pub new_inserted: usize,
}

Expand All @@ -152,7 +151,6 @@ impl<Node> NodesTracker<Node> {
pending_base: None,
extra_freed: Vec::new(),
new_inserted: 0,
deferred_drop_pages: Vec::new(),
}
}

Expand Down Expand Up @@ -201,7 +199,6 @@ impl<Node> NodesTracker<Node> {
pn: PageNumber,
) {
self.extra_freed.push(pn);
self.deferred_drop_pages.push(node.clone());
self.pending_base = Some((separator, node, cutoff));
}
}
19 changes: 13 additions & 6 deletions nomt/src/bitbox/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use crate::{
io::{self, page_pool::FatPage, IoCommand, IoHandle, IoKind, PagePool, PAGE_SIZE},
page_cache::{Page, PageCache},
store::{BucketInfo, DirtyPage},
task::{join_task, spawn_task, TaskResult},
task::{spawn_task, unwrap_task_result, TaskResult},
};

use self::{ht_file::HTOffsets, meta_map::MetaMap};
Expand Down Expand Up @@ -391,8 +391,12 @@ impl SyncController {
///
/// Must be invoked by the sync thread. Blocking.
pub fn wait_pre_meta(&self) -> anyhow::Result<()> {
join_task(&self.begin_sync_result_rx)?;
join_task(&self.pre_meta_result_rx)?;
let preparation = self.begin_sync_result_rx.recv().unwrap();
// If preparation stopped before spawning the WAL writeout, its sender was dropped and
// this returns immediately.
let wal = self.pre_meta_result_rx.recv();
unwrap_task_result(preparation)?;
unwrap_task_result(wal.expect("successful preparation must report WAL readiness"))?;
Ok(())
}

Expand Down Expand Up @@ -438,17 +442,20 @@ fn recover(

wal_fd.seek(SeekFrom::Start(0))?;

let mut wal_reader = WalBlobReader::new(page_pool, wal_fd)?;

// This condition triggers either if:
// 1. the WAL holds data for a sync that never concluded. Safe to discard.
// 2. the WAL holds data for a sync that fully concluded. (somehow). Safe to discard.
if wal_reader.sync_seqn() != sync_seqn {
//
// Only the header is read here: the WAL of a sync that never concluded may be incomplete.
if WalBlobReader::read_sync_seqn(page_pool, wal_fd)? != sync_seqn {
// fsync generously here since it's a one-time operation.
writeout::truncate_wal(wal_fd, true)?;
return Ok(());
}

let mut wal_reader = WalBlobReader::new(page_pool, wal_fd)?;
debug_assert_eq!(wal_reader.sync_seqn(), sync_seqn);

// The indices of pages (in the metabits page space) that were changed and require updates.
// Note those are not ht page numbers yet and still require additional conversion.
let mut changed_meta_page_ixs = HashSet::new();
Expand Down
11 changes: 11 additions & 0 deletions nomt/src/bitbox/wal/read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,17 @@ pub struct WalBlobReader {
}

impl WalBlobReader {
/// Read the sequence even when an uncommitted WAL has an incomplete body.
pub(crate) fn read_sync_seqn(page_pool: &PagePool, wal_fd: &File) -> anyhow::Result<u32> {
// The caller only recovers from a non-empty WAL, and the WAL is written in whole pages.
debug_assert!(wal_fd.metadata()?.len() > 0, "WAL must not be empty");
let page = io::read_page(page_pool, wal_fd, 0)?;
if page[0] != WAL_ENTRY_TAG_START {
bail!("unexpected WAL entry tag at start: {}", page[0]);
}
Ok(u32::from_le_bytes(page[1..5].try_into().unwrap()))
}

/// Creates a new WAL blob reader.
///
/// The `wal_fd` is expected to be positioned at the start of the WAL file. The file must be
Expand Down
71 changes: 70 additions & 1 deletion nomt/src/bitbox/wal/tests.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
use super::{WalBlobBuilder, WalBlobReader, WalEntry};
use crate::{io::page_pool::PagePool, merkle::ElidedChildren, page_diff::PageDiff};
use crate::{
io::{page_pool::PagePool, PAGE_SIZE},
merkle::ElidedChildren,
page_diff::PageDiff,
};
use std::{fs::OpenOptions, io::Write as _};

#[test]
Expand Down Expand Up @@ -108,3 +112,68 @@ fn test_write_read() {
);
assert_eq!(reader.read_entry().unwrap(), None);
}

fn wal_file_with(contents: &[u8]) -> (tempfile::TempDir, std::fs::File) {
let tempdir = tempfile::tempdir().unwrap();
let mut wal_fd = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(tempdir.path().join("wal"))
.unwrap();
wal_fd.write_all(contents).unwrap();
(tempdir, wal_fd)
}

#[test]
fn read_sync_seqn_rejects_wal_shorter_than_a_page() {
let (_tempdir, wal_fd) = wal_file_with(&[super::WAL_ENTRY_TAG_START; 100]);
assert!(WalBlobReader::read_sync_seqn(&PagePool::new(), &wal_fd).is_err());
}

#[test]
fn read_sync_seqn_rejects_bad_start_tag() {
let (_tempdir, wal_fd) = wal_file_with(&[0; PAGE_SIZE]);
assert!(WalBlobReader::read_sync_seqn(&PagePool::new(), &wal_fd).is_err());
}

// A sync that never concluded may leave only a prefix of its WAL. The header must still be
// readable, so that recovery can tell the WAL belongs to another sync and discard it.
#[test]
fn read_sync_seqn_reads_torn_wal() {
let mut builder = WalBlobBuilder::new().unwrap();
builder.reset(69);
let mut diff = PageDiff::default();
for i in 0..126 {
diff.set_changed(i);
}
for bucket in 0..3 {
builder.write_update(
[bucket as u8; 32],
&diff,
(0..126).map(|x| [x; 32]),
ElidedChildren::new(),
bucket,
);
}
builder.finalize();
assert!(builder.as_slice().len() > PAGE_SIZE);
let (_tempdir, wal_fd) = wal_file_with(&builder.as_slice()[..PAGE_SIZE]);

let page_pool = PagePool::new();
assert_eq!(
WalBlobReader::read_sync_seqn(&page_pool, &wal_fd).unwrap(),
69
);

// The body is incomplete: parsing it fails.
let mut reader = WalBlobReader::new(&page_pool, &wal_fd).unwrap();
let torn = loop {
match reader.read_entry() {
Ok(Some(_)) => continue,
Ok(None) => break false,
Err(_) => break true,
}
};
assert!(torn);
}
6 changes: 5 additions & 1 deletion nomt/src/bitbox/writeout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,14 @@ pub(super) fn write_ht(
sent += 1;
}

// Drain every submitted write and keep the first error. The WAL must not be truncated if any
// page failed to reach the hash table.
let mut write_result = Ok(());
while sent > 0 {
io_handle.recv().unwrap();
write_result = write_result.and(io_handle.recv().unwrap().result);
sent -= 1;
}
write_result?;

ht_fd.sync_all()?;

Expand Down
3 changes: 2 additions & 1 deletion nomt/src/io/linux.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,8 @@ fn submission_entry(command: &mut IoCommand) -> squeue::Entry {
.offset(page_index * PAGE_SIZE as u64)
.build()
}
IoKind::WriteRaw(fd, page_index, ref page) => {
IoKind::WriteShared(fd, page_index, ref page) => {
let page: &[u8; PAGE_SIZE] = page.as_ref().as_ref();
opcode::Write::new(types::Fd(fd), page.as_ptr(), PAGE_SIZE as u32)
.offset(page_index * PAGE_SIZE as u64)
.build()
Expand Down
Loading