From 1f98f04c854b56874a864afec62f5e51585e5674 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 23 Nov 2026 14:13:50 +0100 Subject: [PATCH 1/4] beatree: write new leaves to consecutive pages with vectored writes Each leaf worker takes 32 allocations at a time and merges leaves on consecutive pages into one vectored write (new IoKind::WriteRawV, up to 128 KiB). The free-list is rewritten each sync in address order, rotated to start after the last page used, so allocations sweep through the store. Free pages are reused only once they number twice the live pages; until then new pages are appended. The store grows with fallocate instead of set_len so direct writes don't allocate blocks one at a time. Writes no longer map one-to-one to leaves, so each leaf worker counts the writes it sends and the update waits for that many completions. Co-Authored-By: Claude Opus 5.5 --- nomt/src/beatree/allocator/free_list.rs | 103 +++++++++++++++++----- nomt/src/beatree/allocator/mod.rs | 46 ++++++++-- nomt/src/beatree/ops/update/leaf_stage.rs | 74 +++++++++++++--- nomt/src/io/linux.rs | 6 ++ nomt/src/io/mod.rs | 38 +++++++- nomt/src/io/unix.rs | 9 ++ 6 files changed, 235 insertions(+), 41 deletions(-) diff --git a/nomt/src/beatree/allocator/free_list.rs b/nomt/src/beatree/allocator/free_list.rs index 0e2b87df33..2798f94fac 100644 --- a/nomt/src/beatree/allocator/free_list.rs +++ b/nomt/src/beatree/allocator/free_list.rs @@ -87,6 +87,8 @@ impl FreeList { self.portions.last().map(|(head_pn, _)| head_pn).copied() } + // Superseded by `rewrite`; kept for the incremental free-list tests. + #[cfg_attr(not(test), allow(dead_code))] fn pop(&mut self) -> Option { let pn; let head_empty = { @@ -110,31 +112,82 @@ impl FreeList { Some(pn) } - /// Discards the first `n` items from the free-list. + /// Rewrites the whole free-list in address order, starting after the last page used by this + /// sync, so that the next sync's consecutive allocations land on nearby pages. /// - /// This returns the number of items discarded. Runtime is O(n) in the number of free-list - /// segments modified. - pub fn discard(&mut self, n: usize) -> usize { - let mut discarded = 0; - while discarded < n { - let Some((head_pn, mut head)) = self.portions.pop() else { - return discarded; - }; - self.pop = true; - - let to_discard = std::cmp::min(head.len(), n - discarded); - head.truncate(head.len() - to_discard); + /// `used` is the number of entries the sync allocated (its first `used` pops). The pages that + /// held the previous free-list and the `freed` pages join the list; they stay untouched until + /// the next sync. The new free-list pages are the next free entries in address order, or + /// are bumped when there are not enough. Returns the pages to write. + pub fn rewrite( + &mut self, + page_pool: &PagePool, + used: usize, + freed: Vec, + bump: &mut PageNumber, + ) -> Vec<(PageNumber, FatPage)> { + assert!(!self.pop); + if used == 0 && freed.is_empty() { + return vec![]; + } - if !head.is_empty() { - self.portions.push((head_pn, head)); - } else { - self.released_portions.push(head_pn); - } + // Entries in pop order. + let mut order: Vec = Vec::with_capacity(self.len); + for (_, pns) in self.portions.iter().rev() { + order.extend(pns.iter().rev()); + } + let remaining = &order[used..]; + + let mut entries: Vec = Vec::with_capacity(order.len() + freed.len()); + entries.extend(freed); + entries.extend(self.portions.iter().map(|(pn, _)| *pn)); + + // Take `taken` list pages from the remaining entries and bump the rest, such that the + // list pages exactly hold the entries left over. + let total = remaining.len() + entries.len(); + let pages_for = |taken: usize| (total - taken).div_ceil(MAX_PNS_PER_PAGE); + let mut taken = 0; + while taken < remaining.len() && pages_for(taken + 1) >= taken + 1 { + taken += 1; + } + let mut list_pages: Vec = remaining[..taken].to_vec(); + for _ in taken..pages_for(taken) { + list_pages.push(*bump); + bump.0 += 1; + } + let cursor = remaining[..taken] + .last() + .or(order[..used].last()) + .copied(); + entries.extend_from_slice(&remaining[taken..]); - discarded += to_discard; + entries.sort_unstable(); + if let Some(cursor) = cursor { + let split = entries.partition_point(|pn| *pn <= cursor); + entries.rotate_left(split); } - n + // The last portion is the head and pops from its end, so lay the entries out reversed. + entries.reverse(); + list_pages.sort_unstable(); + self.portions = list_pages + .into_iter() + .zip(entries.chunks(MAX_PNS_PER_PAGE)) + .map(|(pn, pns)| (pn, pns.to_vec())) + .collect(); + self.len = entries.len(); + self.fragmented = false; + self.released_portions.clear(); + + let mut prev = FREELIST_EMPTY; + self.portions + .iter() + .map(|(pn, pns)| { + let page = encode_free_list_page(page_pool, prev, pns); + prev = *pn; + (*pn, page) + }) + .collect() } /// Get a reference to this free list asserted to be clean. This panics if the free list isn't @@ -172,6 +225,8 @@ impl FreeList { /// fragmentation itself. /// /// O(n) in the number of pops / pushes. + // Superseded by `rewrite`; kept for the incremental free-list tests. + #[cfg_attr(not(test), allow(dead_code))] pub fn commit( &mut self, page_pool: &PagePool, @@ -202,6 +257,8 @@ impl FreeList { // determines the exact number of pops and bumps which are needed in order to fulfill the // request. also schedules pushing of all touched pages' previous page numbers. + // Superseded by `rewrite`; kept for the incremental free-list tests. + #[cfg_attr(not(test), allow(dead_code))] fn preallocate( &mut self, to_push: &mut Vec, @@ -312,6 +369,8 @@ impl FreeList { new_pages } + // Superseded by `rewrite`; kept for the incremental free-list tests. + #[cfg_attr(not(test), allow(dead_code))] fn push_and_encode( &mut self, page_pool: &PagePool, @@ -352,6 +411,8 @@ impl FreeList { encoded } + // Superseded by `rewrite`; kept for the incremental free-list tests. + #[cfg_attr(not(test), allow(dead_code))] fn push(&mut self, pn: PageNumber) { // UNWRAP: `push` is only called when head is not full. let head = self.portions.last_mut().unwrap(); @@ -359,6 +420,8 @@ impl FreeList { head.1.push(pn); } + // Superseded by `rewrite`; kept for the incremental free-list tests. + #[cfg_attr(not(test), allow(dead_code))] fn encode_head(&self, page_pool: &PagePool) -> Option<(PageNumber, FatPage)> { if let Some((head_pn, head_pns)) = self.portions.last() { let prev_pn = self diff --git a/nomt/src/beatree/allocator/mod.rs b/nomt/src/beatree/allocator/mod.rs index 967f22730e..206b71c7b1 100644 --- a/nomt/src/beatree/allocator/mod.rs +++ b/nomt/src/beatree/allocator/mod.rs @@ -99,6 +99,11 @@ impl Store { /// This will block if another sync is in progress. pub fn start_sync(&self) -> (SyncAllocator, SyncFinisher) { let sync = Mutex::lock_arc(&self.sync); + // Reuse free pages only once there are enough of them that the free pages at the cursor + // form long runs. Until then, append. + let free = sync.free_list.as_clean().len(); + let live = (sync.bump.0 as usize).saturating_sub(free); + let free_len = if free >= FREE_SLACK * live { free } else { 0 }; let (sync_tx, sync_rx) = crossbeam_channel::bounded(1); let finisher = SyncFinisher { @@ -114,6 +119,7 @@ impl Store { sync: Some(sync), send_to_finish: sync_tx, allocations: AtomicUsize::new(0), + free_len, }), }; @@ -168,6 +174,9 @@ struct StoreSync { type StoreSyncGuard = ArcMutexGuard; +/// Free pages are reused once they number this many times the live pages. +const FREE_SLACK: usize = 2; + // Grow the store by 32MB at a time. const GROW_STORE_BY_PAGES: u32 = 8192; @@ -193,11 +202,26 @@ impl SyncAllocator { /// This returns an error when setting the length of the file fails. pub fn allocate(&self) -> std::io::Result { let allocation_index = self.inner.allocations.fetch_add(1, Ordering::Relaxed); + self.page_at(allocation_index) + } + + /// Get the next `n` page numbers, in allocation order. + /// + /// Consecutive allocations come from consecutive free-list entries or from the bump, so a + /// caller writing them in order issues writes that are as close together as the store allows. + /// Page numbers that end up unused must be returned as freed pages. + pub fn allocate_many(&self, n: usize) -> std::io::Result> { + let first = self.inner.allocations.fetch_add(n, Ordering::Relaxed); + (first..first + n).map(|i| self.page_at(i)).collect() + } + + fn page_at(&self, allocation_index: usize) -> std::io::Result { let sync = self.inner.sync(); let free_list = sync.free_list.as_clean(); - if allocation_index >= free_list.len() { - let pn = PageNumber(sync.bump.0 + (allocation_index - free_list.len()) as u32); + let free_len = self.inner.free_len; + if allocation_index >= free_len { + let pn = PageNumber(sync.bump.0 + (allocation_index - free_len) as u32); // fast path: no contention if pn.0 < self.inner.max_bump.load(Ordering::Relaxed) { @@ -232,6 +256,8 @@ impl SyncAllocator { struct SyncAllocatorInner { sync: Option, + // The number of free-list entries this sync allocates from before bumping. + free_len: usize, send_to_finish: Sender, allocations: AtomicUsize, max_bump: AtomicU32, @@ -251,6 +277,7 @@ impl Drop for SyncAllocatorInner { let _ = self.send_to_finish.send(Finish { sync: self.sync.take().unwrap(), allocations: *self.allocations.get_mut(), + free_len: self.free_len, max_bump: *self.set_len_lock.get_mut(), }); } @@ -266,13 +293,19 @@ impl Drop for SyncAllocatorInner { /// Returns the new boundary (the last accessible page) or an I/O error. fn grow(file: &File, page: PageNumber) -> std::io::Result { let next_bump = (page.0 + GROW_STORE_BY_PAGES - 1).next_multiple_of(GROW_STORE_BY_PAGES); - file.set_len(next_bump as u64 * PAGE_SIZE as u64)?; + let len = next_bump as u64 * PAGE_SIZE as u64; + // Allocate the blocks up front: direct writes into holes allocate them one write at a time. + // SAFETY: plain syscall on a valid fd. + if unsafe { libc::fallocate(file.as_raw_fd(), 0, 0, len as libc::off_t) } != 0 { + file.set_len(len)?; + } Ok(PageNumber(next_bump)) } struct Finish { sync: StoreSyncGuard, allocations: usize, + free_len: usize, max_bump: PageNumber, } @@ -301,14 +334,15 @@ impl SyncFinisher { let Finish { mut sync, allocations, + free_len, mut max_bump, } = self.sync_finish.recv().unwrap(); - let bumps = allocations - sync.free_list.discard(allocations); + let used = allocations.min(free_len); // remaining allocations all logically incremented bump. - let mut next_bump = PageNumber(sync.bump.0 + bumps as u32); - let freelist_pages = sync.free_list.commit(page_pool, freed, &mut next_bump); + let mut next_bump = PageNumber(sync.bump.0 + (allocations - used) as u32); + let freelist_pages = sync.free_list.rewrite(page_pool, used, freed, &mut next_bump); // writing the free-list pages might require more bumps, which may require growing the file // further. diff --git a/nomt/src/beatree/ops/update/leaf_stage.rs b/nomt/src/beatree/ops/update/leaf_stage.rs index c47ad4bfc7..2e1403f246 100644 --- a/nomt/src/beatree/ops/update/leaf_stage.rs +++ b/nomt/src/beatree/ops/update/leaf_stage.rs @@ -22,7 +22,7 @@ use crate::beatree::{ }, Key, ValueChange, }; -use crate::io::{IoCommand, IoHandle, IoKind}; +use crate::io::{page_pool::Page, IoCommand, IoHandle, IoKind, IoVecs}; use crate::task::{join_task, spawn_task}; /// Tracker of all changes that happen to leaves during an update @@ -202,9 +202,6 @@ fn apply_worker_changes( } let new_pn = leaf_entry.inserted.as_ref().map(|(_, pn)| *pn); - if new_pn.is_some() { - output.submitted_io += 1; - } if let Some(prev_pn) = leaf_entry.deleted { output.freed_pages.push(prev_pn); @@ -213,7 +210,9 @@ fn apply_worker_changes( output.leaf_changeset.push((*key, new_pn)); } - output.submitted_io += worker_output.leaves_tracker.extra_freed.len(); + // Leaves on consecutive pages share writes, and unused allocations are freed without a + // write, so count the writes the worker sent. + output.submitted_io += worker_output.submitted_io; output .freed_pages .extend(worker_output.leaves_tracker.extra_freed.drain(..)); @@ -549,6 +548,8 @@ fn reset_leaf_base_fresh( } struct LeafWorkerOutput { + // The number of leaf writes sent. + submitted_io: usize, leaves_tracker: LeavesTracker, overflow_deleted: Vec>, } @@ -573,6 +574,10 @@ fn run_worker( leaf_writer, leaves_tracker: LeavesTracker::new(), io_handle, + reserved: Vec::new(), + run_start: 0, + run: Vec::new(), + submitted: 0, }; // point leaf updater at first leaf. @@ -693,16 +698,52 @@ fn run_worker( } } + new_leaf_state.flush_run(); + new_leaf_state + .leaves_tracker + .extra_freed + .extend(new_leaf_state.reserved); Ok(LeafWorkerOutput { + submitted_io: new_leaf_state.submitted, leaves_tracker: new_leaf_state.leaves_tracker, overflow_deleted, }) } +/// Each worker takes this many consecutive allocations at a time so its leaves land on nearby +/// pages and its writes can be merged. +const LEAF_ALLOCATION_CHUNK: usize = 32; + struct NewLeafHandler { leaf_writer: SyncAllocator, leaves_tracker: LeavesTracker, io_handle: IoHandle, + // Allocated but not yet used page numbers, in reverse allocation order. + reserved: Vec, + // Leaves on consecutive pages starting at `run_start`, not yet submitted. + run_start: u64, + run: Vec, + // The number of writes sent. + submitted: usize, +} + +/// The most pages merged into one write: 128 KiB. +const MAX_WRITE_RUN: usize = 32; + +impl NewLeafHandler { + fn flush_run(&mut self) { + let fd = self.leaf_writer.store_fd(); + let kind = match self.run.len() { + 0 => return, + 1 => IoKind::WriteRaw(fd, self.run_start, self.run[0].clone()), + _ => IoKind::WriteRawV(fd, self.run_start, IoVecs::new(&self.run)), + }; + self.run.clear(); + self.submitted += 1; + self.io_handle + .send(IoCommand { kind, user_data: 0 }) + .expect("I/O Pool Down"); + } } impl super::leaf_updater::HandleNewLeaf for NewLeafHandler { @@ -713,17 +754,22 @@ impl super::leaf_updater::HandleNewLeaf for NewLeafHandler { cutoff: Option, ) -> std::io::Result<()> { let leaf = Arc::new(leaf); - let fd = self.leaf_writer.store_fd(); - let page_number = self.leaf_writer.allocate()?; + if self.reserved.is_empty() { + self.reserved = self.leaf_writer.allocate_many(LEAF_ALLOCATION_CHUNK)?; + self.reserved.reverse(); + } + // UNWRAP: refilled above. + let page_number = self.reserved.pop().unwrap(); - let page = leaf.inner.page(); - self.io_handle - .send(IoCommand { - kind: IoKind::WriteRaw(fd, page_number.0 as u64, page), - user_data: 0, - }) - .expect("I/O Pool Down"); + let pn = page_number.0 as u64; + if self.run.len() == MAX_WRITE_RUN || pn != self.run_start + self.run.len() as u64 { + self.flush_run(); + } + if self.run.is_empty() { + self.run_start = pn; + } + self.run.push(leaf.inner.page()); self.leaves_tracker.insert(key, leaf, cutoff, page_number); Ok(()) diff --git a/nomt/src/io/linux.rs b/nomt/src/io/linux.rs index a9796bacf1..aa49224e23 100644 --- a/nomt/src/io/linux.rs +++ b/nomt/src/io/linux.rs @@ -208,6 +208,12 @@ fn submission_entry(command: &mut IoCommand) -> squeue::Entry { .offset(page_index * PAGE_SIZE as u64) .build() } + IoKind::WriteRawV(fd, page_index, ref iovs) => { + let iovs = iovs.as_slice(); + opcode::Writev::new(types::Fd(fd), iovs.as_ptr(), iovs.len() as u32) + .offset(page_index * PAGE_SIZE as u64) + .build() + } IoKind::WriteRaw(fd, page_index, ref page) => { opcode::Write::new(types::Fd(fd), page.as_ptr(), PAGE_SIZE as u32) .offset(page_index * PAGE_SIZE as u64) diff --git a/nomt/src/io/mod.rs b/nomt/src/io/mod.rs index 3448d43982..d9fdd83aa2 100644 --- a/nomt/src/io/mod.rs +++ b/nomt/src/io/mod.rs @@ -53,6 +53,33 @@ pub enum IoKind { Write(RawFd, u64, FatPage), WriteArc(RawFd, u64, Arc), WriteRaw(RawFd, u64, Page), + /// Writes consecutive pages starting at the given page number with one vectored write. + WriteRawV(RawFd, u64, IoVecs), +} + +/// The buffers of a vectored write, one page each. +pub struct IoVecs(Vec); + +// SAFETY: the iovecs point at pages whose owners keep them alive until the write completes, as +// with `Page`. +unsafe impl Send for IoVecs {} + +impl IoVecs { + pub fn new(pages: &[Page]) -> Self { + IoVecs( + pages + .iter() + .map(|page| libc::iovec { + iov_base: page.as_ptr() as *mut libc::c_void, + iov_len: PAGE_SIZE, + }) + .collect(), + ) + } + + fn as_slice(&self) -> &[libc::iovec] { + &self.0 + } } impl fmt::Debug for IoKind { @@ -62,6 +89,9 @@ impl fmt::Debug for IoKind { IoKind::Write(fd, pn, _) => write!(f, "Write(fd={}, pn={})", fd, pn), IoKind::WriteArc(fd, pn, _) => write!(f, "WriteArc(fd={}, pn={})", fd, pn), IoKind::WriteRaw(fd, pn, _) => write!(f, "WriteRaw(fd={}, pn={})", fd, pn), + IoKind::WriteRawV(fd, pn, iovs) => { + write!(f, "WriteRawV(fd={}, pn={}, n={})", fd, pn, iovs.0.len()) + } } } } @@ -77,7 +107,9 @@ impl IoKind { match self { IoKind::Read(_, _, buf) | IoKind::Write(_, _, buf) => buf, IoKind::WriteArc(_, _, _) => panic!("attempted to extract owned buf from write_arc"), - IoKind::WriteRaw(_, _, _) => panic!("attempted to extract buf from write_raw"), + IoKind::WriteRaw(_, _, _) | IoKind::WriteRawV(_, _, _) => { + panic!("attempted to extract buf from write_raw") + } } } @@ -91,6 +123,10 @@ impl IoKind { // there should be no unexpected end-of-file that is not aligned with PAGE_SIZE // when all previous writes have succeeded. IoKind::Read(_, _, _) if res == 0 => IoKindResult::Ok, + IoKind::WriteRawV(_, _, iovs) if res == (iovs.0.len() * PAGE_SIZE) as isize => { + IoKindResult::Ok + } + IoKind::WriteRawV(_, _, _) if res >= 0 => IoKindResult::Retry, // pread and pwrite return the number of bytes read or written _ if res == PAGE_SIZE as isize => IoKindResult::Ok, _ if res == -1 => { diff --git a/nomt/src/io/unix.rs b/nomt/src/io/unix.rs index d4b0a24e85..62ba457697 100644 --- a/nomt/src/io/unix.rs +++ b/nomt/src/io/unix.rs @@ -73,6 +73,15 @@ fn execute(mut command: IoCommand) -> CompleteIo { (page_index * PAGE_SIZE as u64) as libc::off_t, ) }, + IoKind::WriteRawV(fd, page_index, ref iovs) => unsafe { + let iovs = iovs.as_slice(); + libc::pwritev( + fd, + iovs.as_ptr(), + iovs.len() as libc::c_int, + (page_index * PAGE_SIZE as u64) as libc::off_t, + ) + }, IoKind::WriteRaw(fd, page_index, ref mut page) => unsafe { libc::pwrite( fd, From bf13f0594906ba2e6170a61f442a648dd3cd5878 Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Wed, 25 Nov 2026 09:30:35 +0100 Subject: [PATCH 2/4] beatree: fix darwin build and rustfmt fallocate is Linux-only; fall back to set_len elsewhere. Co-Authored-By: Claude Opus 5.5 --- nomt/src/beatree/allocator/free_list.rs | 5 +---- nomt/src/beatree/allocator/mod.rs | 10 ++++++++-- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/nomt/src/beatree/allocator/free_list.rs b/nomt/src/beatree/allocator/free_list.rs index 2798f94fac..bc1be37ff6 100644 --- a/nomt/src/beatree/allocator/free_list.rs +++ b/nomt/src/beatree/allocator/free_list.rs @@ -155,10 +155,7 @@ impl FreeList { list_pages.push(*bump); bump.0 += 1; } - let cursor = remaining[..taken] - .last() - .or(order[..used].last()) - .copied(); + let cursor = remaining[..taken].last().or(order[..used].last()).copied(); entries.extend_from_slice(&remaining[taken..]); entries.sort_unstable(); diff --git a/nomt/src/beatree/allocator/mod.rs b/nomt/src/beatree/allocator/mod.rs index 206b71c7b1..51d0900cd7 100644 --- a/nomt/src/beatree/allocator/mod.rs +++ b/nomt/src/beatree/allocator/mod.rs @@ -296,7 +296,11 @@ fn grow(file: &File, page: PageNumber) -> std::io::Result { let len = next_bump as u64 * PAGE_SIZE as u64; // Allocate the blocks up front: direct writes into holes allocate them one write at a time. // SAFETY: plain syscall on a valid fd. - if unsafe { libc::fallocate(file.as_raw_fd(), 0, 0, len as libc::off_t) } != 0 { + #[cfg(target_os = "linux")] + let allocated = unsafe { libc::fallocate(file.as_raw_fd(), 0, 0, len as libc::off_t) } == 0; + #[cfg(not(target_os = "linux"))] + let allocated = false; + if !allocated { file.set_len(len)?; } Ok(PageNumber(next_bump)) @@ -342,7 +346,9 @@ impl SyncFinisher { // remaining allocations all logically incremented bump. let mut next_bump = PageNumber(sync.bump.0 + (allocations - used) as u32); - let freelist_pages = sync.free_list.rewrite(page_pool, used, freed, &mut next_bump); + let freelist_pages = sync + .free_list + .rewrite(page_pool, used, freed, &mut next_bump); // writing the free-list pages might require more bumps, which may require growing the file // further. From 57ae52c37bcfc5dcd56507ea93d183dc7a784ecd Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Wed, 25 Nov 2026 10:14:06 +0100 Subject: [PATCH 3/4] beatree: drop the incremental free-list code and test rewrite FreeList::commit and its helpers were only kept alive for their own tests. Remove them with the pop/released_portions state, fold CleanFreeList into FreeList, and add tests for rewrite (layout, page conservation, crash safety, sweep order, fragmented input) and for the allocator's allocate_many/reuse path including a reload from disk. Co-Authored-By: Claude Opus 5.5 --- nomt/src/beatree/allocator/free_list.rs | 813 ++++++------------------ nomt/src/beatree/allocator/mod.rs | 91 ++- 2 files changed, 275 insertions(+), 629 deletions(-) diff --git a/nomt/src/beatree/allocator/free_list.rs b/nomt/src/beatree/allocator/free_list.rs index bc1be37ff6..198b7fbcb9 100644 --- a/nomt/src/beatree/allocator/free_list.rs +++ b/nomt/src/beatree/allocator/free_list.rs @@ -8,38 +8,34 @@ use super::PageNumber; const MAX_PNS_PER_PAGE: usize = (PAGE_SIZE - 6) / 4; -/// In-memory version of FreeList which provides a way to decode from and encode into pages -/// and provide two primitives, one for extracting free pages from the list and one to append -/// freed pages. -/// -/// Pages that are freed due to the fetch of free pages are automatically added back during the encode phase, -/// which also covers the addition of new free pages. +/// In-memory version of the free-list, which is stored on disk as a linked list of pages. #[derive(Clone)] pub struct FreeList { // head is last portion. portions: Vec<(PageNumber, Vec)>, - // Becomes true if something is being popped, false otherwise - pop: bool, len: usize, - // The comment on `fn commit` explains what fragmentation is in detail. + // Databases written before `rewrite` may hold a fragmented list: the head page has exactly one + // item and the second-to-last page one fewer than the maximum. fragmented: bool, - released_portions: Vec, } impl FreeList { + fn new(portions: Vec<(PageNumber, Vec)>) -> Self { + let (len, fragmented) = len_and_fragmented(&portions); + FreeList { + portions, + len, + fragmented, + } + } + pub fn read( page_pool: &PagePool, store_file: &File, free_list_head: Option, ) -> anyhow::Result { let Some(mut free_list_pn) = free_list_head else { - return Ok(FreeList { - portions: vec![], - pop: false, - released_portions: vec![], - fragmented: false, - len: 0, - }); + return Ok(FreeList::new(vec![])); }; // restore free list from file @@ -59,15 +55,7 @@ impl FreeList { free_list_portions.reverse(); - let (len, fragmented) = len_and_fragmented(&free_list_portions); - - Ok(FreeList { - pop: false, - portions: free_list_portions, - released_portions: vec![], - fragmented, - len, - }) + Ok(FreeList::new(free_list_portions)) } /// Get a set of all pages tracked in the free-list. This is all free pages plus all the @@ -87,29 +75,18 @@ impl FreeList { self.portions.last().map(|(head_pn, _)| head_pn).copied() } - // Superseded by `rewrite`; kept for the incremental free-list tests. - #[cfg_attr(not(test), allow(dead_code))] - fn pop(&mut self) -> Option { - let pn; - let head_empty = { - let head = self.portions.last_mut()?; - // UNWRAP: free-list portions are always non-empty. - pn = head.1.pop().unwrap(); - self.pop = true; - - if head.1.is_empty() { - Some(head.0) - } else { - None - } - }; + /// Get the length of the free-list. + pub fn len(&self) -> usize { + self.len + } - if let Some(prev_head_pn) = head_empty { - let _ = self.portions.pop(); - self.released_portions.push(prev_head_pn); + // All entries in the order `get_nth_pop` hands them out. + fn pop_order(&self) -> Vec { + let mut order = Vec::with_capacity(self.len); + for (_, pns) in self.portions.iter().rev() { + order.extend(pns.iter().rev()); } - - Some(pn) + order } /// Rewrites the whole free-list in address order, starting after the last page used by this @@ -126,16 +103,11 @@ impl FreeList { freed: Vec, bump: &mut PageNumber, ) -> Vec<(PageNumber, FatPage)> { - assert!(!self.pop); if used == 0 && freed.is_empty() { return vec![]; } - // Entries in pop order. - let mut order: Vec = Vec::with_capacity(self.len); - for (_, pns) in self.portions.iter().rev() { - order.extend(pns.iter().rev()); - } + let order = self.pop_order(); let remaining = &order[used..]; let mut entries: Vec = Vec::with_capacity(order.len() + freed.len()); @@ -147,7 +119,7 @@ impl FreeList { let total = remaining.len() + entries.len(); let pages_for = |taken: usize| (total - taken).div_ceil(MAX_PNS_PER_PAGE); let mut taken = 0; - while taken < remaining.len() && pages_for(taken + 1) >= taken + 1 { + while taken < remaining.len() && pages_for(taken + 1) > taken { taken += 1; } let mut list_pages: Vec = remaining[..taken].to_vec(); @@ -174,7 +146,6 @@ impl FreeList { .collect(); self.len = entries.len(); self.fragmented = false; - self.released_portions.clear(); let mut prev = FREELIST_EMPTY; self.portions @@ -187,252 +158,32 @@ impl FreeList { .collect() } - /// Get a reference to this free list asserted to be clean. This panics if the free list isn't - /// clean: if any `pop`s have occurred since the last call to `commit`. - pub fn as_clean(&self) -> CleanFreeList<'_> { - assert!(!self.pop); - CleanFreeList(self) - } - - /// Apply the changes resulting from calls to `pop()` and pushing all the `to_push` page numbers - /// to the free list. This returns a vector of pages to write, each tagged with the page number - /// it should be written at. - /// - /// FreeList Pages are stored in the file using a Copy-On-Write (COW) approach. - /// - /// This function only applies `pop` invocations since the last call to this function, - /// creating an encoded version of the updated free list state. - /// - /// The FreeList is conceptually a paginated stack. There are some additional constraints due - /// to the copy-on-write mechanics: all touched pages must have their previous page - /// number pushed at the end, and new page numbers are determined by popping from the list. - /// Additionally, to maintain crash-consistency, we do not reuse any page which is being - /// added afresh to the list within this function. Pops and pushes are therefore heavily - /// intertwined. Pushes can cause pops. Pops reduce the length of the list, making pops - /// possibly unnecessary. Pops can also cause further pops when they touch new pages. - /// - /// These restrictions add some code complexity, as well as the possibility of "fragmentation". - /// This fragmentation is minor and takes a very specific form: the second page will have one - /// fewer items than the maximum and the head page will have exactly one item. This occurs only - /// when the last item pushed would be the first in a new page and the pop to allocate that - /// new page dirties a previously untouched page. Needless to say, it is rare, something like - /// 1-in-a-million (1022^2) and of near-zero consequence if forced somehow by an adversary. - /// - /// The next call to `commit` will eliminate any previous fragmentation, but may result in - /// fragmentation itself. - /// - /// O(n) in the number of pops / pushes. - // Superseded by `rewrite`; kept for the incremental free-list tests. - #[cfg_attr(not(test), allow(dead_code))] - pub fn commit( - &mut self, - page_pool: &PagePool, - mut to_push: Vec, - bump: &mut PageNumber, - ) -> Vec<(PageNumber, FatPage)> { - // No changes were made - let had_pops = std::mem::replace(&mut self.pop, false); - if !had_pops && to_push.is_empty() { - return vec![]; - } - - // append the released free list pages - to_push.extend(self.released_portions.drain(..)); - - let new_pages = self.preallocate(&mut to_push, bump); - let pages = self.push_and_encode(page_pool, &to_push, new_pages); - - // preallocate pops, therefore, we must set it back. - self.pop = false; - - let (len, fragmented) = len_and_fragmented(&self.portions); - self.len = len; - self.fragmented = fragmented; - - pages - } + /// Get the result of the nth pop on this free-list. Panics if n >= len. Runtime: O(1). + pub fn get_nth_pop(&self, mut n: usize) -> PageNumber { + let portions = &self.portions; + let n_portions = portions.len(); + if self.fragmented { + if n == 0 { + portions[n_portions - 1].1[0] + } else if n < MAX_PNS_PER_PAGE { + portions[n_portions - 2].1[MAX_PNS_PER_PAGE - n - 1] + } else { + let portion_offset = 2 + (n / MAX_PNS_PER_PAGE); + n = n % MAX_PNS_PER_PAGE; - // determines the exact number of pops and bumps which are needed in order to fulfill the - // request. also schedules pushing of all touched pages' previous page numbers. - // Superseded by `rewrite`; kept for the incremental free-list tests. - #[cfg_attr(not(test), allow(dead_code))] - fn preallocate( - &mut self, - to_push: &mut Vec, - bump: &mut PageNumber, - ) -> Vec { - let mut new_pages = Vec::new(); - - // allocate a new page for rewriting the head (if any). - let mut new_full_portion = true; - let mut i; - if let Some(pn) = self.pop() { - // check if this freed a page and handle that - match self.released_portions.pop() { - Some(x) => { - if let Some((new_head_pn, new_head_pns)) = self - .portions - .last_mut() - .filter(|p| p.1.len() == MAX_PNS_PER_PAGE - 1) - { - // fix up fragmentation. only the second-to-last page can be fragmented, - // and it is. use this page to rewrite the second-to-last and position - // the cursor at the end of this page instead. - to_push.push(*new_head_pn); - to_push.push(x); - *new_head_pn = pn; - new_full_portion = false; - i = MAX_PNS_PER_PAGE - new_head_pns.len(); - } else { - // previous page was full or doesn't exist. - to_push.push(x); - new_pages.push(pn); - - // new page has already been allocated for this batch. - i = MAX_PNS_PER_PAGE; - } - } - None => { - new_full_portion = false; - - // UNWRAP: protected since pop succeeded but head was not released. - let (head_pn, head_pns) = self.portions.last_mut().unwrap(); - to_push.push(*head_pn); - *head_pn = pn; - - // head is partially full. position cursor at the number of items needed to - // fill it. - i = MAX_PNS_PER_PAGE - head_pns.len(); - } + portions[n_portions - portion_offset].1[MAX_PNS_PER_PAGE - n - 1] } } else { - // nothing popped, free list was totally empty. - // defer to loop to create the page for the next section. - i = 0; - }; - - // loop invariant: free list len + i is always divisible by MAX_PNS_PER_PAGE. - // therefore, the loop condition asks "do we still have items beyond the last page?" - // while accounting for pops and pushes within the loop. - while i < to_push.len() { - if let Some((ref mut head_pn, ref mut head_pns)) = - self.portions.last_mut().filter(|_| new_full_portion) - { - // just popped into a new portion (which we will edit). prepare it for rewrite, - // because we are about to pop from it and alter it. - to_push.push(*head_pn); - - // UNWRAP: new_full_portion guarantees that the new portion is full. - *head_pn = head_pns.pop().unwrap(); - - new_full_portion = false; - - // pop reduces free list length, we adjust i to compensate. - // however, we must unconditionally rewrite this page even if i equals the previous - // value of to_push.len(). That is because if we didn't pop we wouldn't have enough - // pages. - // this is inescapable and is what causes fragmentation. - i += 1; - - continue; - } + let head_len = portions[n_portions - 1].1.len(); + if n < head_len { + portions[n_portions - 1].1[head_len - n - 1] + } else { + n -= head_len; + let portion_offset = 2 + (n / MAX_PNS_PER_PAGE); + n = n % MAX_PNS_PER_PAGE; - // loop invariant: from this point on, the head page (if any) always has a head_pn which - // was itself drawn from the free-list. - match self.pop() { - Some(pn) => { - new_pages.push(pn); - // pop reduces free list length, we adjust i to compensate - i += 1; - - if let Some(released) = self.released_portions.pop() { - new_full_portion = true; - // note: this is the PN we took out of the new portion; it's fresh. - // - // if i now equals to_push.len(), we have a forced fragmentation. - new_pages.push(released); - } - } - None => { - new_pages.push(*bump); - bump.0 += 1; - } + portions[n_portions - portion_offset].1[MAX_PNS_PER_PAGE - n - 1] } - - // jump 'i' to the end of the next page. - i += MAX_PNS_PER_PAGE; - } - - new_pages - } - - // Superseded by `rewrite`; kept for the incremental free-list tests. - #[cfg_attr(not(test), allow(dead_code))] - fn push_and_encode( - &mut self, - page_pool: &PagePool, - to_push: &[PageNumber], - new_pages: Vec, - ) -> Vec<(PageNumber, FatPage)> { - let mut encoded = Vec::new(); - let mut new_pages = new_pages.into_iter().peekable(); - for (i, pn) in to_push.iter().cloned().enumerate() { - // the second condition is checking for the fragmentation described in the commit - // doc comment. fragmentation can only occur in the second page and the head page - // has a single item. - let head_full = self - .portions - .last() - .map_or(true, |h| h.1.len() == MAX_PNS_PER_PAGE); - - let fragmentation = self - .portions - .last() - .map_or(false, |h| h.1.len() == MAX_PNS_PER_PAGE - 1) - && new_pages.peek().is_some() - && i + 1 == to_push.len(); - - if head_full || fragmentation { - encoded.extend(self.encode_head(page_pool)); - // UNWRAP: we've always allocated enough PNs for all appended PNs. - let new_head_pn = new_pages.next().unwrap(); - self.portions.push((new_head_pn, Vec::new())); - } - - self.push(pn); - } - - assert!(new_pages.next().is_none()); - - encoded.extend(self.encode_head(page_pool)); - encoded - } - - // Superseded by `rewrite`; kept for the incremental free-list tests. - #[cfg_attr(not(test), allow(dead_code))] - fn push(&mut self, pn: PageNumber) { - // UNWRAP: `push` is only called when head is not full. - let head = self.portions.last_mut().unwrap(); - assert!(head.1.len() < MAX_PNS_PER_PAGE); - head.1.push(pn); - } - - // Superseded by `rewrite`; kept for the incremental free-list tests. - #[cfg_attr(not(test), allow(dead_code))] - fn encode_head(&self, page_pool: &PagePool) -> Option<(PageNumber, FatPage)> { - if let Some((head_pn, head_pns)) = self.portions.last() { - let prev_pn = self - .portions - .len() - .checked_sub(2) - .map_or(FREELIST_EMPTY, |i| self.portions[i].0); - - Some(( - *head_pn, - encode_free_list_page(page_pool, prev_pn, &head_pns), - )) - } else { - None } } } @@ -483,45 +234,6 @@ fn encode_free_list_page(page_pool: &PagePool, prev: PageNumber, pns: &[PageNumb page } -/// A wrapper type which denotes a clean free-list. -pub struct CleanFreeList<'a>(&'a FreeList); - -impl<'a> CleanFreeList<'a> { - /// Get the length of the free-list. - pub fn len(&self) -> usize { - self.0.len - } - - /// Get the result of the nth pop on this free-list. Panics if n >= len. Runtime: O(1). - pub fn get_nth_pop(&self, mut n: usize) -> PageNumber { - let portions = &self.0.portions; - let n_portions = portions.len(); - if self.0.fragmented { - if n == 0 { - portions[n_portions - 1].1[0] - } else if n < MAX_PNS_PER_PAGE { - portions[n_portions - 2].1[MAX_PNS_PER_PAGE - n - 1] - } else { - let portion_offset = 2 + (n / MAX_PNS_PER_PAGE); - n = n % MAX_PNS_PER_PAGE; - - portions[n_portions - portion_offset].1[MAX_PNS_PER_PAGE - n - 1] - } - } else { - let head_len = portions[n_portions - 1].1.len(); - if n < head_len { - portions[n_portions - 1].1[head_len - n - 1] - } else { - n -= head_len; - let portion_offset = 2 + (n / MAX_PNS_PER_PAGE); - n = n % MAX_PNS_PER_PAGE; - - portions[n_portions - portion_offset].1[MAX_PNS_PER_PAGE - n - 1] - } - } - } -} - // A free page is laid out in the following form: // + prev free page : u32 // + item_count : u16 @@ -563,328 +275,175 @@ impl<'a> FreeListPageMut<'a> { #[cfg(test)] mod tests { - use super::{FreeList, PageNumber, PagePool, MAX_PNS_PER_PAGE}; - - #[test] - fn pop_into_next_portion_one_page_needed() { - let mut free_list = FreeList { - portions: vec![(PageNumber(1), vec![PageNumber(2)])], - pop: false, - released_portions: Vec::new(), - len: 1, - fragmented: false, - }; + use super::{decode_free_list_page, FreeList, PageNumber, PagePool, MAX_PNS_PER_PAGE}; + use crate::beatree::FREELIST_EMPTY; + use std::collections::BTreeSet; - // expected order of events: - // 1. first (2) is popped for the new head. - // 2. This exhausts the head. We use (2) for a new head and push (1) to the end. - let page_pool = PagePool::new(); - let result = free_list.commit( - &page_pool, - (3..).take(1).map(PageNumber).collect::>(), - &mut PageNumber(10000), - ); - - assert_eq!(result.len(), 1); - assert_eq!(result[0].0, PageNumber(2)); - - assert_eq!(free_list.portions.len(), 1); - assert_eq!(free_list.portions[0].0, PageNumber(2)); - assert_eq!(free_list.portions[0].1, vec![PageNumber(3), PageNumber(1)]); - assert_eq!(free_list.len, 2); + fn pns(range: std::ops::Range) -> Vec { + range.map(PageNumber).collect() } - #[test] - fn pop_into_next_portion_fragmentation() { - let mut free_list = FreeList { - portions: vec![(PageNumber(1), vec![PageNumber(2), PageNumber(3)])], - pop: false, - released_portions: Vec::new(), - len: 2, - fragmented: false, - }; - - // expected order of events: - // 1. first (3) is popped for the new head and (1) is pushed. - // 2. We now need a new page to store all the items. (2) is popped. - // 3. This empties the head portion, leaving (3) dangling. to_push == MAX - // 4. We use (3) as a new page for writing the last item, fragmentation was forced. - // If we had pushed (3) to the end of the free-list instead, to_push would be MAX+1 - // and we'd need to take a new page from bump or the previous head, dirtying it and - // allocating unnecessarily. - let page_pool = PagePool::new(); - let result = free_list.commit( - &page_pool, - (4..) - .take(MAX_PNS_PER_PAGE - 1) - .map(PageNumber) - .collect::>(), - &mut PageNumber(10000), - ); - - assert_eq!(result.len(), 2); - assert_eq!(result[0].0, PageNumber(2)); - assert_eq!(result[1].0, PageNumber(3)); - - assert_eq!(free_list.portions.len(), 2); - assert_eq!(free_list.portions[0].0, PageNumber(2)); - assert_eq!(free_list.portions[1].0, PageNumber(3)); - assert_eq!(free_list.portions[0].1.len(), MAX_PNS_PER_PAGE - 1); - assert_eq!(free_list.portions[1].1.len(), 1); - assert_eq!(free_list.len, MAX_PNS_PER_PAGE); - assert!(free_list.fragmented); + fn assert_nth_pop_matches_layout(free_list: &FreeList) { + let predicted = (0..free_list.len()) + .map(|i| free_list.get_nth_pop(i)) + .collect::>(); + assert_eq!(predicted, free_list.pop_order()); } #[test] - fn pop_into_next_portion_without_fragmentation() { - let mut free_list = FreeList { - portions: vec![(PageNumber(1), vec![PageNumber(2), PageNumber(3)])], - pop: false, - released_portions: Vec::new(), - len: 2, - fragmented: false, - }; - - // expected order of events: - // 1. first (3) is popped for the new head and (1) is pushed. - // 2. We now need a new page to store all the items. (2) is popped. - // 3. This empties the head portion, leaving (3) dangling. to_push = MAX + 1 - // 4. We push (2) for the first new page and (3) for the next. (2) is completely full, - // and (3) has the last item. - let page_pool = PagePool::new(); - let result = free_list.commit( - &page_pool, - (4..) - .take(MAX_PNS_PER_PAGE) - .map(PageNumber) - .collect::>(), - &mut PageNumber(10000), - ); - - assert_eq!(result.len(), 2); - assert_eq!(result[0].0, PageNumber(2)); - assert_eq!(result[1].0, PageNumber(3)); - - assert_eq!(free_list.portions.len(), 2); - assert_eq!(free_list.portions[0].0, PageNumber(2)); - assert_eq!(free_list.portions[1].0, PageNumber(3)); - assert_eq!(free_list.portions[0].1.len(), MAX_PNS_PER_PAGE); - assert_eq!(free_list.portions[1].1.len(), 1); - assert_eq!(free_list.len, MAX_PNS_PER_PAGE + 1); + fn clean_nth_pop() { + let free_list = FreeList::new(vec![ + (PageNumber(1), pns(1000..1000 + MAX_PNS_PER_PAGE as u32)), + (PageNumber(2), pns(5000..5000 + MAX_PNS_PER_PAGE as u32)), + ( + PageNumber(3), + pns(10000..10000 + MAX_PNS_PER_PAGE as u32 / 2), + ), + ]); + assert!(!free_list.fragmented); + assert_nth_pop_matches_layout(&free_list); } #[test] - fn fragmentation_handled() { - let full_portion = (10000..) - .take(MAX_PNS_PER_PAGE - 2) - .chain(Some(2)) - .chain(Some(3)) - .map(PageNumber) - .collect::>(); - let mut free_list = FreeList { - portions: vec![ - (PageNumber(1), full_portion), - (PageNumber(4), vec![PageNumber(5)]), - ], - pop: false, - released_portions: Vec::new(), - len: MAX_PNS_PER_PAGE + 1, - fragmented: false, - }; - - // expected order of events: - // 1. first (5) is popped for the new head and (4) is pushed. to_push == MAX+1. - // 2. This vacates the head page. (5) is used as a fresh page. - // 2. We need a new page to store all the items. We need to pop into the previously - // full page. - // 3. Its previous head (1) is pushed and (3) is taken to overwrite it. to_push == MAX+2 - // 4. (2) is popped to handle the new page. - // 5. One of the to_push items is written into the full page. to_push == MAX+1 - // 6. We can't write MAX items into the next page and 1 into another, because we'd need - // to pop a new page for that but wouldn't be able to use it. - // 7. The only solution is to pop the next page (69) and have the second-to-last page - // fragmented. - let page_pool = PagePool::new(); - let result = free_list.commit( - &page_pool, - (20000..) - .take(MAX_PNS_PER_PAGE) - .map(PageNumber) - .collect::>(), - &mut PageNumber(100000), - ); - - assert_eq!(result.len(), 3); - assert_eq!(result[0].0, PageNumber(3)); - assert_eq!(result[1].0, PageNumber(5)); - assert_eq!(result[2].0, PageNumber(2)); - - assert_eq!(free_list.portions.len(), 3); - - assert_eq!(free_list.portions[0].0, PageNumber(3)); - assert_eq!(free_list.portions[1].0, PageNumber(5)); - assert_eq!(free_list.portions[2].0, PageNumber(2)); - - assert_eq!(free_list.portions[0].1.len(), MAX_PNS_PER_PAGE); - assert_eq!(free_list.portions[1].1.len(), MAX_PNS_PER_PAGE - 1); - assert_eq!(free_list.portions[2].1.len(), 1); - - assert_eq!(free_list.len, MAX_PNS_PER_PAGE * 2); + fn fragmented_nth_pop() { + let free_list = FreeList::new(vec![ + (PageNumber(1), pns(1000..1000 + MAX_PNS_PER_PAGE as u32)), + (PageNumber(4), pns(5000..5000 + MAX_PNS_PER_PAGE as u32)), + ( + PageNumber(5), + pns(10000..10000 + MAX_PNS_PER_PAGE as u32 - 1), + ), + (PageNumber(6), vec![PageNumber(7)]), + ]); assert!(free_list.fragmented); + assert_eq!(free_list.len(), MAX_PNS_PER_PAGE * 3); + assert_nth_pop_matches_layout(&free_list); } - #[test] - fn clean_up_fragmentation() { - let fragmented_portion = (10000..) - .take(MAX_PNS_PER_PAGE - 3) - .chain(Some(2)) - .chain(Some(3)) - .map(PageNumber) - .collect::>(); + // Runs `rewrite` and checks the result against the free list it started from. + fn check_rewrite(mut free_list: FreeList, used: usize, freed: Vec) -> FreeList { + let before = free_list.pop_order(); + let old_list_pages: Vec = free_list.portions.iter().map(|p| p.0).collect(); + let bump_before = PageNumber(1_000_000); + let mut bump = bump_before; - let mut free_list = FreeList { - portions: vec![ - (PageNumber(1), fragmented_portion), - (PageNumber(4), vec![PageNumber(5)]), - ], - pop: false, - released_portions: Vec::new(), - len: MAX_PNS_PER_PAGE, - fragmented: true, - }; - - // expected order of operations: - // 1. 5 is popped to rewrite the head. This vacates the head. - // 2. Because the previous portion is fragmented, 5 is taken as its new head and its old - // head and the outdated (1) and (4) are pushed. - // 3. A new page (3) is popped for the new items. - // 4. The fragmented (5) is filled out and the rest of the items are pushed into (3) let page_pool = PagePool::new(); - let result = free_list.commit(&page_pool, vec![PageNumber(6)], &mut PageNumber(10000)); + let written = free_list.rewrite(&page_pool, used, freed.clone(), &mut bump); - assert_eq!(result.len(), 2); - assert_eq!(result[0].0, PageNumber(5)); - assert_eq!(result[1].0, PageNumber(3)); + // The written pages encode exactly the new portions, chained in order. + assert_eq!(written.len(), free_list.portions.len()); + let mut prev = FREELIST_EMPTY; + for ((pn, page), (portion_pn, portion)) in written.iter().zip(&free_list.portions) { + assert_eq!(pn, portion_pn); + let (decoded_prev, decoded) = decode_free_list_page(page.clone(), u32::MAX); + assert_eq!(decoded_prev, prev); + assert_eq!(&decoded, portion); + prev = *pn; + } - assert_eq!(free_list.portions.len(), 2); + // Every portion but the head is full, so the list is not fragmented. + let (head, rest) = free_list.portions.split_last().unwrap(); + assert!(!head.1.is_empty()); + assert!(rest.iter().all(|p| p.1.len() == MAX_PNS_PER_PAGE)); + assert!(!free_list.fragmented); + assert_nth_pop_matches_layout(&free_list); + + // No page is lost or duplicated. + let list_pages: BTreeSet = free_list.portions.iter().map(|p| p.0).collect(); + let entries: BTreeSet = free_list.pop_order().into_iter().collect(); + assert_eq!(entries.len(), free_list.len()); + assert!(list_pages.is_disjoint(&entries)); + let bumped: BTreeSet = (bump_before.0..bump.0).map(PageNumber).collect(); + let expected: BTreeSet = before[used..] + .iter() + .chain(&freed) + .chain(&old_list_pages) + .copied() + .chain(bumped.iter().copied()) + .collect(); + assert_eq!(&list_pages | &entries, expected); - assert_eq!(free_list.portions[0].0, PageNumber(5)); - assert_eq!(free_list.portions[1].0, PageNumber(3)); + // The new list pages are written this sync, so they must not be anything the committed + // state still references (old list pages, freed pages) or this sync's allocations. + let fresh: BTreeSet = before[used..].iter().copied().chain(bumped).collect(); + assert!(list_pages.is_subset(&fresh)); - assert_eq!(free_list.portions[0].1.len(), MAX_PNS_PER_PAGE); - assert_eq!(free_list.portions[1].1.len(), 1); + // Pops sweep upwards through the file, wrapping around at most once. + let order = free_list.pop_order(); + assert!(order.windows(2).filter(|w| w[0] > w[1]).count() <= 1); - assert_eq!(free_list.len, MAX_PNS_PER_PAGE + 1); - assert!(!free_list.fragmented); + free_list } #[test] - fn rewrite_head_after_pop_only() { - let mut free_list = FreeList { - portions: vec![(PageNumber(1), vec![PageNumber(2)])], - pop: true, - released_portions: Vec::new(), - len: 1, - fragmented: false, - }; - - // The head must follow CoW. - let page_pool = PagePool::new(); - let result = free_list.commit(&page_pool, Vec::new(), &mut PageNumber(10000)); - - assert_eq!(result.len(), 1); - assert_eq!(result[0].0, PageNumber(2)); - - let (prev_pn, free_list) = super::decode_free_list_page(result[0].1.clone(), 3); - - assert_eq!(prev_pn, super::FREELIST_EMPTY); - assert_eq!(free_list, vec![PageNumber(1)]); + fn rewrite_nothing_to_do() { + let mut free_list = FreeList::new(vec![(PageNumber(1), pns(2..10))]); + let written = free_list.rewrite(&PagePool::new(), 0, vec![], &mut PageNumber(100)); + assert!(written.is_empty()); + assert_eq!(free_list.portions, vec![(PageNumber(1), pns(2..10))]); } #[test] - fn clean_nth_pop() { - let full_portion_1 = (1000..) - .take(MAX_PNS_PER_PAGE) - .map(PageNumber) - .collect::>(); - - let full_portion_2 = (5000..) - .take(MAX_PNS_PER_PAGE) - .map(PageNumber) - .collect::>(); - - let last_portion = (10000..) - .take(MAX_PNS_PER_PAGE / 2) - .map(PageNumber) - .collect::>(); - - let mut free_list = FreeList { - portions: vec![ - (PageNumber(1), full_portion_1), - (PageNumber(2), full_portion_2), - (PageNumber(3), last_portion), - ], - pop: false, - released_portions: Vec::new(), - len: MAX_PNS_PER_PAGE * 2 + MAX_PNS_PER_PAGE / 2, - fragmented: false, - }; - - let predicted_pops = { - let clean = free_list.as_clean(); - (0..clean.len()) - .map(|i| clean.get_nth_pop(i)) - .collect::>() - }; - let actual_pops = (0..free_list.len) - .map(|_| free_list.pop().unwrap()) - .collect::>(); - - assert_eq!(predicted_pops, actual_pops); + fn rewrite_empty_list_bumps_list_page() { + let free_list = check_rewrite(FreeList::new(vec![]), 0, pns(5..8)); + assert_eq!( + free_list.portions, + vec![(PageNumber(1_000_000), pns(5..8).into_iter().rev().collect())] + ); } #[test] - fn clean_nth_pop_fragmented() { - let full_portion_1 = (1000..) - .take(MAX_PNS_PER_PAGE) - .map(PageNumber) - .collect::>(); - - let full_portion_2 = (5000..) - .take(MAX_PNS_PER_PAGE) - .map(PageNumber) - .collect::>(); - - let fragmented_portion = (10000..) - .take(MAX_PNS_PER_PAGE - 3) - .chain(Some(2)) - .chain(Some(3)) - .map(PageNumber) - .collect::>(); + fn rewrite_takes_list_pages_from_free_entries() { + let free_list = FreeList::new(vec![(PageNumber(1), pns(2..10))]); + let free_list = check_rewrite(free_list, 3, pns(20..22)); + // used: 9, 8, 7. The next entry in pop order, 6, holds the new list. + assert_eq!(free_list.portions.len(), 1); + assert_eq!(free_list.portions[0].0, PageNumber(6)); + // Pops resume after the cursor at 6 and wrap around. + assert_eq!( + free_list.pop_order(), + [20, 21, 1, 2, 3, 4, 5].map(PageNumber).to_vec() + ); + } - let mut free_list = FreeList { - portions: vec![ - (PageNumber(1), full_portion_1), - (PageNumber(4), full_portion_2), - (PageNumber(5), fragmented_portion), - (PageNumber(6), vec![PageNumber(7)]), - ], - pop: false, - released_portions: Vec::new(), - len: MAX_PNS_PER_PAGE * 3, - fragmented: true, - }; + #[test] + fn rewrite_all_used() { + let free_list = FreeList::new(vec![ + (PageNumber(1), pns(100..100 + MAX_PNS_PER_PAGE as u32)), + (PageNumber(2), pns(5000..5010)), + ]); + let len = free_list.len(); + let free_list = check_rewrite(free_list, len, vec![]); + // Only the two old list pages remain free; the new list page is bumped. + assert_eq!(free_list.pop_order(), pns(1..3)); + } - let predicted_pops = { - let clean = free_list.as_clean(); - (0..clean.len()) - .map(|i| clean.get_nth_pop(i)) - .collect::>() - }; - let actual_pops = (0..free_list.len) - .map(|_| free_list.pop().unwrap()) - .collect::>(); + #[test] + fn rewrite_multi_page_shuffled() { + // A deterministic shuffle of three and a half pages of entries. + let n = (MAX_PNS_PER_PAGE * 7 / 2) as u32; + let mut all: Vec = (0..n).map(|i| PageNumber(10 + (i * 7919) % n)).collect(); + let freed = all.split_off(all.len() - 500); + let portions = all + .chunks(MAX_PNS_PER_PAGE) + .enumerate() + .map(|(i, c)| (PageNumber(n + 100 + i as u32), c.to_vec())) + .collect(); + let free_list = FreeList::new(portions); + let len = free_list.len(); + let free_list = check_rewrite(free_list, len / 3, freed); + let free_list = check_rewrite(free_list, 10, pns(n + 200..n + 300)); + check_rewrite(free_list, 0, pns(n + 300..n + 301)); + } - assert_eq!(predicted_pops, actual_pops); + #[test] + fn rewrite_fragmented() { + let free_list = FreeList::new(vec![ + (PageNumber(1), pns(100..100 + MAX_PNS_PER_PAGE as u32)), + (PageNumber(4), pns(5000..5000 + MAX_PNS_PER_PAGE as u32 - 1)), + (PageNumber(6), vec![PageNumber(7)]), + ]); + assert!(free_list.fragmented); + check_rewrite(free_list, 5, pns(9000..9003)); } } diff --git a/nomt/src/beatree/allocator/mod.rs b/nomt/src/beatree/allocator/mod.rs index 51d0900cd7..2244b18fab 100644 --- a/nomt/src/beatree/allocator/mod.rs +++ b/nomt/src/beatree/allocator/mod.rs @@ -101,7 +101,7 @@ impl Store { let sync = Mutex::lock_arc(&self.sync); // Reuse free pages only once there are enough of them that the free pages at the cursor // form long runs. Until then, append. - let free = sync.free_list.as_clean().len(); + let free = sync.free_list.len(); let live = (sync.bump.0 as usize).saturating_sub(free); let free_len = if free >= FREE_SLACK * live { free } else { 0 }; let (sync_tx, sync_rx) = crossbeam_channel::bounded(1); @@ -218,7 +218,7 @@ impl SyncAllocator { fn page_at(&self, allocation_index: usize) -> std::io::Result { let sync = self.inner.sync(); - let free_list = sync.free_list.as_clean(); + let free_list = &sync.free_list; let free_len = self.inner.free_len; if allocation_index >= free_len { let pn = PageNumber(sync.bump.0 + (allocation_index - free_len) as u32); @@ -374,3 +374,90 @@ pub struct StoreMeta { /// The next free page number. pub bump: u32, } + +#[cfg(test)] +mod tests { + use super::{PageNumber, Store, FREELIST_EMPTY}; + use crate::io::{PagePool, PAGE_SIZE}; + use std::{collections::BTreeSet, os::unix::fs::FileExt, sync::Arc}; + + // Drives many syncs with page churn and checks that no page referenced by the committed state + // is handed out or overwritten, that free pages get reused, and that the free list reloads. + #[test] + fn allocate_many_and_reuse() { + let page_pool = PagePool::new(); + let file = Arc::new(tempfile::tempfile().unwrap()); + let store = Store::open(&page_pool, file.clone(), PageNumber(1), None).unwrap(); + + let mut live: Vec = Vec::new(); + let mut committed_list: BTreeSet = BTreeSet::new(); + let mut reused = false; + let mut last = None; + + for sync_i in 0..40 { + let bump_before = store.sync.lock().bump; + let (allocator, finisher) = store.start_sync(); + let referenced: BTreeSet = live + .iter() + .copied() + .chain(committed_list.iter().copied()) + .collect(); + + let mut allocated = allocator.allocate_many(48).unwrap(); + allocated.push(allocator.allocate().unwrap()); + allocated.extend(allocator.allocate_many(16).unwrap()); + assert_eq!( + allocated.iter().collect::>().len(), + allocated.len() + ); + for pn in &allocated { + assert!(!pn.is_nil()); + assert!( + !referenced.contains(pn), + "sync {sync_i}: {pn:?} is still referenced" + ); + reused |= *pn < bump_before; + } + if allocated.iter().all(|pn| *pn >= bump_before) { + // appending: consecutive allocations are consecutive pages. + assert!(allocated.windows(2).all(|w| w[1].0 == w[0].0 + 1)); + } + drop(allocator); + + // Return the last few allocations unused and free the oldest live pages. + let unused = allocated.split_off(allocated.len() - 5); + let n_free = if live.len() > 300 { 60 } else { 0 }; + let mut freed: Vec = live.drain(..n_free).collect(); + freed.extend(&unused); + live.extend(&allocated); + + let (list_pages, meta) = finisher.finish(&page_pool, freed).unwrap(); + let new_list: BTreeSet = list_pages.iter().map(|(pn, _)| *pn).collect(); + for pn in &new_list { + assert!( + !referenced.contains(pn), + "sync {sync_i}: list page {pn:?} overwrites" + ); + assert!(!allocated.contains(pn) && !unused.contains(pn)); + } + committed_list = new_list; + last = Some((list_pages, meta)); + } + assert!(reused, "free pages were never reused"); + + // Write out the last free list and reopen the store from it. + let (list_pages, meta) = last.unwrap(); + for (pn, page) in &list_pages { + file.write_all_at(&page[..], pn.0 as u64 * PAGE_SIZE as u64) + .unwrap(); + } + let head = (meta.freelist_pn != FREELIST_EMPTY.0).then_some(PageNumber(meta.freelist_pn)); + let reopened = Store::open(&page_pool, file, PageNumber(meta.bump), head).unwrap(); + assert_eq!( + reopened.all_tracked_freelist_pages(), + store.all_tracked_freelist_pages() + ); + let live: BTreeSet = live.into_iter().collect(); + assert!(live.is_disjoint(&store.all_tracked_freelist_pages())); + } +} From 98bc045494c184b401eb1c41f0867ab3ac4fdad2 Mon Sep 17 00:00:00 2001 From: Nikolai Golub Date: Wed, 25 Nov 2026 10:14:07 +0100 Subject: [PATCH 4/4] beatree: own pending leaves in the write run and flush it earlier The run now holds the leaves' Arcs rather than raw pages, so a pending page cannot be freed before its write is sent, and the last run is sent as soon as the worker stops producing leaves instead of after it waits on its left neighbor. Drop IoVecs::as_slice. Co-Authored-By: Claude Opus 5.5 --- nomt/src/beatree/ops/update/leaf_stage.rs | 52 +++++++++++++++-------- nomt/src/io/linux.rs | 3 +- nomt/src/io/mod.rs | 7 +-- nomt/src/io/unix.rs | 5 +-- 4 files changed, 39 insertions(+), 28 deletions(-) diff --git a/nomt/src/beatree/ops/update/leaf_stage.rs b/nomt/src/beatree/ops/update/leaf_stage.rs index 2e1403f246..b076add3d9 100644 --- a/nomt/src/beatree/ops/update/leaf_stage.rs +++ b/nomt/src/beatree/ops/update/leaf_stage.rs @@ -22,7 +22,7 @@ use crate::beatree::{ }, Key, ValueChange, }; -use crate::io::{page_pool::Page, IoCommand, IoHandle, IoKind, IoVecs}; +use crate::io::{IoCommand, IoHandle, IoKind, IoVecs}; use crate::task::{join_task, spawn_task}; /// Tracker of all changes that happen to leaves during an update @@ -575,8 +575,7 @@ fn run_worker( leaves_tracker: LeavesTracker::new(), io_handle, reserved: Vec::new(), - run_start: 0, - run: Vec::new(), + run: WriteRun::default(), submitted: 0, }; @@ -670,6 +669,9 @@ fn run_worker( ); } + // No more leaves are produced, so don't hold the last write while waiting on the left worker. + new_leaf_state.flush_run(); + // Now we are safe to send over our right neighbor to the left one // because we're sure to have finished interacting with it has_finished_workload = true; @@ -698,7 +700,6 @@ fn run_worker( } } - new_leaf_state.flush_run(); new_leaf_state .leaves_tracker .extra_freed @@ -720,9 +721,7 @@ struct NewLeafHandler { io_handle: IoHandle, // Allocated but not yet used page numbers, in reverse allocation order. reserved: Vec, - // Leaves on consecutive pages starting at `run_start`, not yet submitted. - run_start: u64, - run: Vec, + run: WriteRun, // The number of writes sent. submitted: usize, } @@ -730,15 +729,36 @@ struct NewLeafHandler { /// The most pages merged into one write: 128 KiB. const MAX_WRITE_RUN: usize = 32; +/// Leaves on consecutive pages starting at `start`, not yet submitted. +#[derive(Default)] +struct WriteRun { + start: u64, + // Owned so the pages stay alive until the write is sent, whatever happens to the tracker. + leaves: Vec>, +} + +impl WriteRun { + fn continues_at(&self, pn: u64) -> bool { + !self.leaves.is_empty() + && self.leaves.len() < MAX_WRITE_RUN + && pn == self.start + self.leaves.len() as u64 + } +} + impl NewLeafHandler { fn flush_run(&mut self) { let fd = self.leaf_writer.store_fd(); - let kind = match self.run.len() { - 0 => return, - 1 => IoKind::WriteRaw(fd, self.run_start, self.run[0].clone()), - _ => IoKind::WriteRawV(fd, self.run_start, IoVecs::new(&self.run)), + let start = self.run.start; + let leaves = std::mem::take(&mut self.run.leaves); + let kind = match &leaves[..] { + [] => return, + [leaf] => IoKind::WriteRaw(fd, start, leaf.inner.page()), + _ => IoKind::WriteRawV( + fd, + start, + IoVecs::new(leaves.iter().map(|l| l.inner.page())), + ), }; - self.run.clear(); self.submitted += 1; self.io_handle .send(IoCommand { kind, user_data: 0 }) @@ -763,13 +783,11 @@ impl super::leaf_updater::HandleNewLeaf for NewLeafHandler { let page_number = self.reserved.pop().unwrap(); let pn = page_number.0 as u64; - if self.run.len() == MAX_WRITE_RUN || pn != self.run_start + self.run.len() as u64 { + if !self.run.continues_at(pn) { self.flush_run(); + self.run.start = pn; } - if self.run.is_empty() { - self.run_start = pn; - } - self.run.push(leaf.inner.page()); + self.run.leaves.push(leaf.clone()); self.leaves_tracker.insert(key, leaf, cutoff, page_number); Ok(()) diff --git a/nomt/src/io/linux.rs b/nomt/src/io/linux.rs index aa49224e23..5766a5cca7 100644 --- a/nomt/src/io/linux.rs +++ b/nomt/src/io/linux.rs @@ -209,8 +209,7 @@ fn submission_entry(command: &mut IoCommand) -> squeue::Entry { .build() } IoKind::WriteRawV(fd, page_index, ref iovs) => { - let iovs = iovs.as_slice(); - opcode::Writev::new(types::Fd(fd), iovs.as_ptr(), iovs.len() as u32) + opcode::Writev::new(types::Fd(fd), iovs.0.as_ptr(), iovs.0.len() as u32) .offset(page_index * PAGE_SIZE as u64) .build() } diff --git a/nomt/src/io/mod.rs b/nomt/src/io/mod.rs index d9fdd83aa2..6773495225 100644 --- a/nomt/src/io/mod.rs +++ b/nomt/src/io/mod.rs @@ -65,10 +65,9 @@ pub struct IoVecs(Vec); unsafe impl Send for IoVecs {} impl IoVecs { - pub fn new(pages: &[Page]) -> Self { + pub fn new(pages: impl Iterator) -> Self { IoVecs( pages - .iter() .map(|page| libc::iovec { iov_base: page.as_ptr() as *mut libc::c_void, iov_len: PAGE_SIZE, @@ -76,10 +75,6 @@ impl IoVecs { .collect(), ) } - - fn as_slice(&self) -> &[libc::iovec] { - &self.0 - } } impl fmt::Debug for IoKind { diff --git a/nomt/src/io/unix.rs b/nomt/src/io/unix.rs index 62ba457697..7e34fe2302 100644 --- a/nomt/src/io/unix.rs +++ b/nomt/src/io/unix.rs @@ -74,11 +74,10 @@ fn execute(mut command: IoCommand) -> CompleteIo { ) }, IoKind::WriteRawV(fd, page_index, ref iovs) => unsafe { - let iovs = iovs.as_slice(); libc::pwritev( fd, - iovs.as_ptr(), - iovs.len() as libc::c_int, + iovs.0.as_ptr(), + iovs.0.len() as libc::c_int, (page_index * PAGE_SIZE as u64) as libc::off_t, ) },