From 61521b4cb3d8f4f6ae7fcf6c60e63be75a8ac7e1 Mon Sep 17 00:00:00 2001 From: Kim Altintop Date: Tue, 17 Nov 2026 13:03:46 +0100 Subject: [PATCH 1/5] Revert "Database-wide eviction for (some) reads (#6607)" This reverts commit c660db7967ebcdceaeccb60ab001ff81ebddb2d1. --- .../locking_tx_datastore/committed_state.rs | 26 ++-------- .../src/locking_tx_datastore/mut_tx.rs | 26 +++------- .../src/locking_tx_datastore/state_view.rs | 16 ++---- .../datastore/src/locking_tx_datastore/tx.rs | 1 - crates/table/src/table.rs | 50 ++----------------- 5 files changed, 20 insertions(+), 99 deletions(-) diff --git a/crates/datastore/src/locking_tx_datastore/committed_state.rs b/crates/datastore/src/locking_tx_datastore/committed_state.rs index e721accadb7..84003f6e49f 100644 --- a/crates/datastore/src/locking_tx_datastore/committed_state.rs +++ b/crates/datastore/src/locking_tx_datastore/committed_state.rs @@ -57,7 +57,7 @@ use spacetimedb_schema::{ use spacetimedb_table::{ blob_store::BlobHash, indexes::{RowPointer, SquashedOffset}, - table::{self, PreparedBlobRelease, PreparedEvictionPolicy, ReadEviction, RowRef, Table, TableAndIndex}, + table::{PreparedBlobRelease, PreparedEvictionPolicy, RowRef, Table, TableAndIndex}, tiered::{BlobHandle, BlobSet, EvictionPolicy, PreparedCommit, TieredDatabaseStorage}, }; use std::{collections::BTreeMap, iter}; @@ -157,12 +157,6 @@ impl MemoryUsage for CommittedState { } } -impl ReadEviction for CommittedState { - fn evict_for_read(&self) -> std::result::Result<(), table::TableError> { - self.trim_resident() - } -} - impl StateView for CommittedState { type Iter<'a> = TableScanIter<'a>; type IterByColRange<'a, R: RangeBounds> = IterByColRangeTx<'a, R>; @@ -477,7 +471,6 @@ impl CommittedState { self.tables .get(&table_id)? .get_index_by_cols_with_table(self.storage.blobs(), cols) - .map(|index| index.with_read_eviction(self)) } /// Returns the table associated with the given `index_id`, if any. @@ -490,7 +483,6 @@ impl CommittedState { self.tables .get(&table_id)? .get_index_by_id_with_table(self.storage.blobs(), index_id) - .map(|index| index.with_read_eviction(self)) } // TODO(perf, deep-integration): Make this method `unsafe`. Add the following to the docs: @@ -515,21 +507,11 @@ impl CommittedState { .get_table(table_id) .expect("Attempt to get COMMITTED_STATE row from table not present in tables."); // TODO(perf, deep-integration): Use `get_row_ref_unchecked`. - Ok(self - .retry_read(|| Ok(table.get_row_ref(self.storage.blobs(), row_ptr)?))? + Ok(table + .get_row_ref(self.storage.blobs(), row_ptr)? .expect("row pointer to be present")) } - pub(super) fn retry_read(&self, mut read: impl FnMut() -> Result) -> Result { - match read() { - Err(error) if error.is_resident_memory_limit() => { - self.trim_resident()?; - read() - } - result => result, - } - } - /// True if the transaction `(tx_data, ctx)` will be written to the commitlog, /// and therefore consumes a value from `self.next_tx_offset`. /// @@ -1230,7 +1212,7 @@ impl CommittedState { /// or no more objects can be evicted. /// /// TODO: Use a database-scoped LRU eviction policy instead of evicting table by table. - pub(super) fn trim_resident(&self) -> std::result::Result<(), table::TableError> { + pub(super) fn trim_resident(&self) -> Result<()> { let pages = self.storage.pages(); let target = pages.resident_budget().low_water_bytes; for table in self.tables.values() { diff --git a/crates/datastore/src/locking_tx_datastore/mut_tx.rs b/crates/datastore/src/locking_tx_datastore/mut_tx.rs index eee753aec66..7948eadbf67 100644 --- a/crates/datastore/src/locking_tx_datastore/mut_tx.rs +++ b/crates/datastore/src/locking_tx_datastore/mut_tx.rs @@ -742,10 +742,7 @@ impl MutTxId { } for ptr in deleted_table.iter() { - if let Some(row_ref) = self - .committed_state_write_lock - .retry_read(|| Ok(table.get_row_ref(blob_store, ptr)?))? - { + if let Some(row_ref) = table.get_row_ref(blob_store, ptr)? { process_views(table_id, row_ref); } } @@ -762,10 +759,7 @@ impl MutTxId { } let blob_store = &self.tx_state.blob_store; - for row_ref in inserted_table - .scan_rows(blob_store) - .with_read_eviction(&*self.committed_state_write_lock) - { + for row_ref in inserted_table.scan_rows(blob_store) { process_views(table_id, row_ref?); } } @@ -2318,10 +2312,7 @@ impl MutTxId { .get_index_by_id_with_table(table_id, index_id)?; // Find the index for the tx state, if any. - let tx_index = self - .tx_state - .get_index_by_id_with_table(table_id, index_id) - .map(|index| index.with_read_eviction(&*self.committed_state_write_lock)); + let tx_index = self.tx_state.get_index_by_id_with_table(table_id, index_id); Some((table_id, commit_index, tx_index)) } @@ -2978,8 +2969,7 @@ impl MutTxId { // See above. Once `TxState::get` is unsafe, justify with: // // Our invariants satisfy `TxState::get`. - self.committed_state_write_lock - .retry_read(|| Ok(self.tx_state.get(table_id, row_ptr)?))?, + self.tx_state.get(table_id, row_ptr)?, ), SquashedOffset::COMMITTED_STATE => { if self.tx_state.is_deleted(table_id, row_ptr) { @@ -4661,9 +4651,7 @@ fn iter_by_col_range<'a, R: RangeBounds>( // It's sufficient to check that the committed state has an index // as index schema changes are applied immediately. if let Some(commit_index) = committed_state.get_index_by_cols(table_id, &cols) { - let tx_index = tx_state - .get_index_by_cols(table_id, &cols) - .map(|index| index.with_read_eviction(committed_state)); + let tx_index = tx_state.get_index_by_cols(table_id, &cols); if let Ok(iter) = MutTxId::index_scan_range_via_algebraic_value(tx_state, table_id, tx_index, commit_index, &range) { @@ -4709,9 +4697,7 @@ fn iter_by_col_eq<'a, 'r>( // as index schema changes are applied immediately. let cols = cols.into(); if let Some(commit_index) = committed_state.get_index_by_cols(table_id, &cols) { - let tx_index = tx_state - .get_index_by_cols(table_id, &cols) - .map(|index| index.with_read_eviction(committed_state)); + let tx_index = tx_state.get_index_by_cols(table_id, &cols); let key = commit_index.index().key_from_algebraic_value(val); let iter = MutTxId::index_scan_point_inner(tx_state, table_id, tx_index, commit_index, &key); Ok(ScanOrIndex::Index(iter)) diff --git a/crates/datastore/src/locking_tx_datastore/state_view.rs b/crates/datastore/src/locking_tx_datastore/state_view.rs index 912c01c4e35..1aecc042108 100644 --- a/crates/datastore/src/locking_tx_datastore/state_view.rs +++ b/crates/datastore/src/locking_tx_datastore/state_view.rs @@ -428,7 +428,7 @@ pub(crate) fn iter_st_column_for_table<'a>( } pub struct IterMutTx<'a> { - tx_state_ins: Option<(&'a Table, &'a BlobSet, &'a CommittedState)>, + tx_state_ins: Option<(&'a Table, &'a BlobSet)>, stage: ScanStage<'a>, } @@ -443,12 +443,9 @@ impl<'a> IterMutTx<'a> { let tx_state_ins = tx_state .insert_tables .get(&table_id) - .map(|table| (table, &tx_state.blob_store, committed_state)); + .map(|table| (table, &tx_state.blob_store)); - let iter = commit_table - .scan_rows(committed_state.storage.blobs()) - .with_read_eviction(committed_state) - .err_into(); + let iter = commit_table.scan_rows(committed_state.storage.blobs()).err_into(); let stage = if let Some(deletes) = tx_state.get_delete_table(table_id) { // There are deletes in the tx state // so we must exclude those (1b). @@ -534,11 +531,8 @@ impl<'a> Iterator for IterMutTx<'a> { // (2) We got here, so we must've exhausted the committed changes. // Start looking in the current tx for inserts, if any, in (3). - let (insert_table, blob_store, committed_state) = self.tx_state_ins?; - let iter = insert_table - .scan_rows(blob_store) - .with_read_eviction(committed_state) - .err_into(); + let (insert_table, blob_store) = self.tx_state_ins?; + let iter = insert_table.scan_rows(blob_store).err_into(); self.stage = ScanStage::CurrentTx { iter }; } } diff --git a/crates/datastore/src/locking_tx_datastore/tx.rs b/crates/datastore/src/locking_tx_datastore/tx.rs index 3c981b0a4b8..6fbf5ab4907 100644 --- a/crates/datastore/src/locking_tx_datastore/tx.rs +++ b/crates/datastore/src/locking_tx_datastore/tx.rs @@ -145,7 +145,6 @@ impl TxId { .and_then(|table| { table .get_index_by_id_with_table(self.committed_state_shared_lock.storage.blobs(), index_id) - .map(|index| index.with_read_eviction(&*self.committed_state_shared_lock)) .map(seek) .ok_or_else(|| anyhow::anyhow!("IndexId `{index_id}` does not exist")) }) diff --git a/crates/table/src/table.rs b/crates/table/src/table.rs index 47d380f43e4..79591e834cc 100644 --- a/crates/table/src/table.rs +++ b/crates/table/src/table.rs @@ -2217,7 +2217,6 @@ impl Table { current_page_idx: PageIndex(0), table: self, blobs, - read_eviction: None, } } @@ -2252,7 +2251,6 @@ impl Table { table: self, blobs, index: self.get_index_by_id(index_id)?, - read_eviction: None, }) } @@ -2268,7 +2266,6 @@ impl Table { table: self, blobs, index, - read_eviction: None, }) } @@ -3054,14 +3051,6 @@ pub struct TableScanIter<'table> { pub(crate) table: &'table Table, /// The [`BlobSet`] that row references may refer into. pub(crate) blobs: &'table BlobSet, - read_eviction: Option<&'table dyn ReadEviction>, -} - -impl<'table> TableScanIter<'table> { - pub fn with_read_eviction(mut self, eviction: &'table dyn ReadEviction) -> Self { - self.read_eviction = Some(eviction); - self - } } enum CurrentPage<'a> { @@ -3132,12 +3121,7 @@ impl<'a> Iterator for TableScanIter<'a> { page_handle, ) }; - // This offset was consumed; retry the same row if loading its blobs failed. - return Some(retry_read(row_ref.map_err(Into::into), self.read_eviction, || { - self.table - .get_row_ref(self.blobs, ptr) - .map(|row| row.expect("row being scanned remains present")) - })); + return Some(row_ref.map_err(Into::into)); } else { // We've finished visiting that page, so set `current_page` to `None`, // increment `self.current_page_idx` to the index of the next page, @@ -3161,8 +3145,7 @@ impl<'a> Iterator for TableScanIter<'a> { // We're past the end of the pages. return None; } - let read_page = || self.table.pages().get_page(self.current_page_idx).map_err(Into::into); - match retry_read(read_page(), self.read_eviction, read_page) { + match self.table.pages().get_page(self.current_page_idx) { Ok(Some(next_page)) => { self.current_page = Some(CurrentPage::new(next_page, self.table.row_size())); @@ -3173,7 +3156,7 @@ impl<'a> Iterator for TableScanIter<'a> { // so continue past it to the next page slot. self.current_page_idx.0 += 1; } - Err(e) => return Some(Err(e)), + Err(e) => return Some(Err(e.into())), } } } @@ -3189,15 +3172,9 @@ pub struct TableAndIndex<'a> { table: &'a Table, blobs: &'a BlobSet, index: &'a TableIndex, - read_eviction: Option<&'a dyn ReadEviction>, } impl<'a> TableAndIndex<'a> { - pub fn with_read_eviction(mut self, eviction: &'a dyn ReadEviction) -> Self { - self.read_eviction = Some(eviction); - self - } - pub fn table(&self) -> &'a Table { self.table } @@ -3224,7 +3201,6 @@ impl<'a> TableAndIndex<'a> { table: self.table, blobs: self.blobs, btree_index_iter: self.index.seek_point(key), - read_eviction: self.read_eviction, } } @@ -3240,7 +3216,6 @@ impl<'a> TableAndIndex<'a> { table: self.table, blobs: self.blobs, btree_index_iter: self.index.seek_range(range)?, - read_eviction: self.read_eviction, }) } @@ -3268,7 +3243,6 @@ impl<'a> TableAndIndex<'a> { table: self.table, blobs: self.blobs, btree_index_iter, - read_eviction: self.read_eviction, }) } } @@ -3284,7 +3258,6 @@ pub struct IndexScanPointIter<'a> { blobs: &'a BlobSet, /// The iterator performing the index scan yielding row pointers. btree_index_iter: TableIndexPointIter<'a>, - read_eviction: Option<&'a dyn ReadEviction>, } impl<'a> IndexScanPointIter<'a> { @@ -3301,13 +3274,7 @@ impl<'a> Iterator for IndexScanPointIter<'a> { fn next(&mut self) -> Option { self.btree_index_iter.next().map(|ptr| { // SAFETY: `ptr` came from the index, which always holds pointers to valid rows for its table. - let row = unsafe { self.table.get_row_ref_unchecked(self.blobs, ptr) }; - // Retry this pointer; advancing the index again would skip a row. - retry_read(row, self.read_eviction, || { - self.table - .get_row_ref(self.blobs, ptr) - .map(|row| row.expect("row from index remains present")) - }) + unsafe { self.table.get_row_ref_unchecked(self.blobs, ptr) } }) } } @@ -3323,7 +3290,6 @@ pub struct IndexScanRangeIter<'a> { blobs: &'a BlobSet, /// The iterator performing the index scan yielding row pointers. btree_index_iter: TableIndexRangeIter<'a>, - read_eviction: Option<&'a dyn ReadEviction>, } impl<'a> Iterator for IndexScanRangeIter<'a> { @@ -3333,13 +3299,7 @@ impl<'a> Iterator for IndexScanRangeIter<'a> { fn next(&mut self) -> Option { self.btree_index_iter.next().map(|ptr| { // SAFETY: `ptr` came from the index, which always holds pointers to valid rows for its table. - let row = unsafe { self.table.get_row_ref_unchecked(self.blobs, ptr) }; - // Retry this pointer; advancing the index again would skip a row. - retry_read(row, self.read_eviction, || { - self.table - .get_row_ref(self.blobs, ptr) - .map(|row| row.expect("row from index remains present")) - }) + unsafe { self.table.get_row_ref_unchecked(self.blobs, ptr) } }) } } From 866005b165bfcf816781bb935840605960657b1c Mon Sep 17 00:00:00 2001 From: Kim Altintop Date: Tue, 17 Nov 2026 13:03:46 +0100 Subject: [PATCH 2/5] Revert "Use database-wide eviction instead of per-table (#6586)" This reverts commit 6786826db918acba38ba5e3d76599f4de5e419da. --- .../src/locking_tx_datastore/committed_state.rs | 12 +----------- .../src/locking_tx_datastore/mut_tx.rs | 17 ++--------------- crates/table/src/page.rs | 9 +++------ crates/table/src/tiered/page_set.rs | 2 +- crates/table/src/var_len.rs | 7 +++++-- 5 files changed, 12 insertions(+), 35 deletions(-) diff --git a/crates/datastore/src/locking_tx_datastore/committed_state.rs b/crates/datastore/src/locking_tx_datastore/committed_state.rs index 84003f6e49f..f06b8f98c71 100644 --- a/crates/datastore/src/locking_tx_datastore/committed_state.rs +++ b/crates/datastore/src/locking_tx_datastore/committed_state.rs @@ -748,17 +748,7 @@ impl CommittedState { view_instances: ViewInstanceTxState, ctx: &ExecutionContext, ) -> Result { - let preparation = self.prepare_merge(&tx_state).or_else(|error| { - if error.is_resident_memory_limit() { - // Preparation hit the memory limit. - // Try to evict resident pages and then prepare again. - self.trim_resident()?; - self.prepare_merge(&tx_state) - } else { - Err(error) - } - }); - let prepared = match preparation { + let prepared = match self.prepare_merge(&tx_state) { Ok(prepared) => prepared, Err(error) => { self.rollback(tx_state); diff --git a/crates/datastore/src/locking_tx_datastore/mut_tx.rs b/crates/datastore/src/locking_tx_datastore/mut_tx.rs index 7948eadbf67..809617b9605 100644 --- a/crates/datastore/src/locking_tx_datastore/mut_tx.rs +++ b/crates/datastore/src/locking_tx_datastore/mut_tx.rs @@ -4032,21 +4032,8 @@ fn insert_physically_maybe_generate<'a, const GENERATE: bool>( }; // 1. Insert the physical row. - let insert_physical = |table: &mut Table, blobs: &mut BlobSet| { - table - .insert_physically_bsatn(blobs, row) - .map(|(row, bytes)| (row.into_pinned_row(), bytes)) - .map_err(DatastoreError::from) - }; - let (tx_pinned_row, blob_bytes) = match insert_physical(tx_table, tx_blob_store) { - Err(error) if error.is_resident_memory_limit() => { - // The insertion hit the memory limit. - // Try to evict resident pages and insert again. - committed_state.trim_resident()?; - insert_physical(tx_table, tx_blob_store)? - } - result => result?, - }; + let (tx_row_ref, blob_bytes) = tx_table.insert_physically_bsatn(tx_blob_store, row)?; + let tx_pinned_row = tx_row_ref.into_pinned_row(); // 2. Optionally: Detect, generate, write sequence values. let (tx_parts, gen_cols) = if GENERATE { // When `GENERATE` is enabled, we're instructed to deal with sequence value generation. diff --git a/crates/table/src/page.rs b/crates/table/src/page.rs index e0559c433a0..e314f6b4a7b 100644 --- a/crates/table/src/page.rs +++ b/crates/table/src/page.rs @@ -730,15 +730,12 @@ impl<'page> VarView<'page> { /// Allocates a granule for a large blob object /// and returns a [`VarLenRef`] pointing to that granule. /// - /// Initialize an empty header so cleanup can free the granule if writing the blob fails. - /// The caller must still write the blob hash before reading the granule's data. + /// The granule is not initialized by this method, and contains valid-unconstrained bytes. + /// It is the caller's responsibility to initialize it with a [`BlobHash`](super::blob_hash::BlobHash). #[cold] fn alloc_blob_hash(&mut self) -> Result { // Var-len hashes are 32 bytes, which fits within a single granule. - let granule = self.alloc_granule()?; - // SAFETY: The allocation is unused and aligned, and NULL terminates the list. - unsafe { self.write_chunk_to_granule(&[], 0, granule, PageOffset::VAR_LEN_NULL) }; - Ok(VarLenRef::large_blob(granule)) + self.alloc_granule().map(VarLenRef::large_blob) } /// Inserts `var_len_obj` into `blob_store` diff --git a/crates/table/src/tiered/page_set.rs b/crates/table/src/tiered/page_set.rs index 942a2def6e4..af62e2a9d3b 100644 --- a/crates/table/src/tiered/page_set.rs +++ b/crates/table/src/tiered/page_set.rs @@ -216,7 +216,7 @@ impl TieredPages { mut f: impl FnMut() -> Result, ) -> Result { match f() { - Err(PageError::MemoryLimitExceeded(_)) if !self.slots.is_empty() => { + Err(PageError::MemoryLimitExceeded(_)) => { self.trim(manager)?; f() } diff --git a/crates/table/src/var_len.rs b/crates/table/src/var_len.rs index 7af87e6630d..c331fe783b6 100644 --- a/crates/table/src/var_len.rs +++ b/crates/table/src/var_len.rs @@ -145,8 +145,11 @@ impl VarLenGranuleHeader { /// However, a granule can never store more than [`VarLenGranule::DATA_SIZE`] (`62`), /// which is `2` less than `2^6`. /// - /// Completed granules have a nonzero length. A reserved blob-hash granule - /// has length 0 until the hash is written; length 63 remains unused. + /// We will also never allocate a `VarLenGranule` with len 0. + /// + /// This means that the `len` field of a `VarLenGranule` has two dead states, + /// 0 and 63. We could use these as sentinels, + /// but currently have no use for them. const LEN_BITMASK: u16 = (1 << Self::LEN_BITS) - 1; /// The [`LEN_BITMASK`] will preserve all granule lengths possible. From 597e2fa08fe9b748b0d1767e45f25c70d268b6c4 Mon Sep 17 00:00:00 2001 From: Kim Altintop Date: Wed, 18 Nov 2026 08:10:32 +0100 Subject: [PATCH 3/5] Revert "Database-wide eviction for snapshot creation and commitlog replay" This reverts commit 1474e62306b3d5a952f05c1f6afe612657ff10f0. Tests added in that commit are preserved. --- .../src/locking_tx_datastore/replay.rs | 119 +++++++++--------- crates/snapshot/src/lib.rs | 21 +--- 2 files changed, 61 insertions(+), 79 deletions(-) diff --git a/crates/datastore/src/locking_tx_datastore/replay.rs b/crates/datastore/src/locking_tx_datastore/replay.rs index 48227794b83..2d21a16b5e0 100644 --- a/crates/datastore/src/locking_tx_datastore/replay.rs +++ b/crates/datastore/src/locking_tx_datastore/replay.rs @@ -1,7 +1,7 @@ use super::committed_state::CommittedState; use super::datastore::{Locking, Result}; use crate::db_metrics::DB_METRICS; -use crate::error::{DatastoreError, TableError, ViewError}; +use crate::error::{DatastoreError, IndexError, TableError, ViewError}; use crate::locking_tx_datastore::state_view::{iter_st_column_for_table, StateView}; use crate::system_tables::{ is_built_in_meta_row, table_id_is_reserved, StColumnRow, StConstraintData, StConstraintRow, StEventTableFields, @@ -494,18 +494,6 @@ impl<'cs> ReplayCommittedState<'cs> { } } - // Retry only an operation that leaves logical state unchanged on error. - // Replaying a whole record again could repeat rows already applied before the failure. - fn with_eviction_retry(&mut self, mut operation: impl FnMut(&mut Self) -> Result) -> Result { - match operation(self) { - Err(error) if error.is_resident_memory_limit() => { - self.trim_resident()?; - operation(self) - } - result => result, - } - } - /// The purpose of this is to rebuild the state of the datastore /// after having inserted all of rows from the message log. /// This is necessary because, for example, inserting a row into `st_table` @@ -701,21 +689,18 @@ impl<'cs> ReplayCommittedState<'cs> { for index_row in rows { let index_id = index_row.index_id; let table_id = index_row.table_id; + let (table, blob_store, index_id_map) = self + .get_table_and_blob_store_mut(table_id) + .expect("index should exist in committed state; cannot create it"); let algo: IndexAlgorithm = index_row.index_algorithm.into(); let columns: ColSet = algo.columns().into(); let is_unique = unique_constraints.contains(&(table_id, columns)); - self.with_eviction_retry(|state| { - let (table, blob_store, index_id_map) = state - .get_table_and_blob_store_mut(table_id) - .expect("index should exist in committed state; cannot create it"); - let index = table.new_index(&algo, is_unique)?; - // SAFETY: `index` was derived from `table`. - unsafe { table.insert_index(blob_store, index_id, index) }? - .expect("rebuilding should not cause constraint violations"); - index_id_map.insert(index_id, table_id); - Ok(()) - })?; + let index = table.new_index(&algo, is_unique)?; + // SAFETY: `index` was derived from `table`. + unsafe { table.insert_index(blob_store, index_id, index) }? + .expect("rebuilding should not cause constraint violations"); + index_id_map.insert(index_id, table_id); } Ok(()) } @@ -789,19 +774,32 @@ impl<'cs> ReplayCommittedState<'cs> { return Ok(()); } - let Some(row_pin) = self.with_eviction_retry(|state| { - let (table, blob_store) = state.get_table_and_blob_store_or_create(table_id, schema); - match table.insert(blob_store, row) { - // An owned pin ends the table borrow before any eviction retry. - Ok((_, row)) => Ok(Some(row.into_pinned_row())), - // Bootstrap may have already inserted an identical system descriptor. - Err(InsertError::Duplicate(_)) if is_built_in_meta_row(table_id, row)? => Ok(None), - Err(error) => Err(error.into()), + let (table, blob_store) = self.get_table_and_blob_store_or_create(table_id, schema); + + let (_, row_ref) = match table.insert(blob_store, row) { + Ok(stuff) => stuff, + Err(InsertError::Duplicate(e)) => { + if is_built_in_meta_row(table_id, row)? { + // If this is a meta-descriptor for a system object, + // and it already exists exactly, then we can safely ignore the insert. + // Any error other than `Duplicate` means the commitlog + // has system table schemas which do not match our expectations, + // which is almost certainly an unrecoverable error. + return Ok(()); + } else { + return Err(TableError::Duplicate(e).into()); + } } - })? - else { - return Ok(()); + Err(InsertError::Bflatn(e)) => return Err(TableError::Bflatn(e).into()), + Err(InsertError::IndexError(e)) => return Err(IndexError::UniqueConstraintViolation(e).into()), + Err(InsertError::Table(e)) => return Err(e.into()), }; + + // `row_ref` is treated as having a mutable borrow on `self` because it + // derives from `self.get_table_and_blob_store_or_create`, so we have to + // downgrade it to a pinned row and then re-upgrade it again as an + // immutable row pointer later. + let row_pin = row_ref.into_pinned_row(); let row_ptr = row_pin.pointer(); if table_id == ST_TABLE_ID { @@ -982,11 +980,13 @@ impl<'cs> ReplayCommittedState<'cs> { return Ok(()); } - let row_ptr = self - .with_eviction_retry(|state| { - let (table, blob_store, _) = state.get_table_and_blob_store_mut(table_id)?; - Ok(table.delete_equal_row(blob_store, row).map_err(TableError::Bflatn)?) - })? + // Get the table for mutation. + let (table, blob_store, _) = self.get_table_and_blob_store_mut(table_id)?; + + // Delete the row. + let row_ptr = table + .delete_equal_row(blob_store, row) + .map_err(TableError::Bflatn)? .ok_or_else(|| anyhow!("Delete for non-existent row when replaying transaction"))?; if table_id == ST_TABLE_CACHE_POLICY_ID { @@ -1019,8 +1019,7 @@ impl<'cs> ReplayCommittedState<'cs> { // Later deletes and truncates for a dropped table are // ignored, so release every blob reference before forgetting // its pages. - self.retry_read(|| Ok(table.prepare_blob_release()?))? - .apply(self.storage.blobs()); + table.prepare_blob_release()?.apply(self.storage.blobs()); } self.tables.remove(&dropped_table_id); @@ -1091,12 +1090,13 @@ impl<'cs> ReplayCommittedState<'cs> { } } + // Get the table for mutation. + let (table, blob_store, ..) = self.get_table_and_blob_store_mut(table_id)?; + // We do not need to consider a truncation of `st_table` itself, // as if that happens, the database is bricked. - self.with_eviction_retry(|state| { - let (table, blob_store, ..) = state.get_table_and_blob_store_mut(table_id)?; - Ok(table.clear(blob_store)?) - })?; + + table.clear(blob_store)?; Ok(()) } @@ -1105,21 +1105,18 @@ impl<'cs> ReplayCommittedState<'cs> { // Read policies only after the whole transaction has been replayed: a // replacement can contain both an insert and a delete of policy metadata. // Read the system tables rather than the table's old cached schema. - let prepared_changes = self.with_eviction_retry(|state| { - let mut prepared_changes = Vec::new(); - for &table_id in &state.replay_cache_policy_changed { - let Some(table) = state.get_table(table_id) else { - // Dropped tables need no conversion. New empty tables may not - // have been materialized yet; creation will read their policy. - continue; - }; - let schema = state.schema_for_table_raw(table_id)?; - let eviction_policy = state.page_eviction_policy(&schema); - let change = table.prepare_eviction_policy(state.storage.blobs(), eviction_policy)?; - prepared_changes.push((table_id, schema.cache_policy, change)); - } - Ok(prepared_changes) - })?; + let mut prepared_changes = Vec::new(); + for &table_id in &self.replay_cache_policy_changed { + let Some(table) = self.get_table(table_id) else { + // Dropped tables need no conversion. New empty tables may not + // have been materialized yet; creation will read their policy. + continue; + }; + let schema = self.schema_for_table_raw(table_id)?; + let eviction_policy = self.page_eviction_policy(&schema); + let change = table.prepare_eviction_policy(self.storage.blobs(), eviction_policy)?; + prepared_changes.push((table_id, schema.cache_policy, change)); + } // Load every affected table before converting any of them, using the // same preparation and application rules as a live commit. diff --git a/crates/snapshot/src/lib.rs b/crates/snapshot/src/lib.rs index 7a477eb76b5..9226e8c5650 100644 --- a/crates/snapshot/src/lib.rs +++ b/crates/snapshot/src/lib.rs @@ -473,26 +473,11 @@ impl Snapshot { &mut self, object_repo: &DirTrie, tables: impl Iterator, - blobs: &BlobSet, prev_snapshot: Option<&DirTrie>, counter: &mut CountCreated, ) -> Result<(), SnapshotError> { - let mut tables = tables.collect::>(); - for index in 0..tables.len() as u64 { - match self.write_table(object_repo, tables[index as usize], prev_snapshot, counter) { - Err(SnapshotError::Page(PageError::MemoryLimitExceeded(_))) => { - // The failed page fault could only evict from its own table. - // Its guards are gone, so other tables and blobs can now make room. - for table in &tables { - table.trim()?; - } - blobs.trim()?; - // write_table adds metadata only on success. Files already written - // by this attempt are reused rather than written again. - self.write_table(object_repo, tables[index as usize], prev_snapshot, counter)?; - } - result => result?, - } + for table in tables { + self.write_table(object_repo, table, prev_snapshot, counter)?; } Ok(()) } @@ -952,7 +937,7 @@ impl SnapshotRepository { // Populate both the in-memory `Snapshot` object and the on-disk object repository // with all the blobs and pages. snapshot.write_all_blobs(&object_repo, blobs, prev_snapshot.as_ref(), &mut counter)?; - snapshot.write_all_tables(&object_repo, tables, blobs, prev_snapshot.as_ref(), &mut counter)?; + snapshot.write_all_tables(&object_repo, tables, prev_snapshot.as_ref(), &mut counter)?; log::info!( "[{}] SNAPSHOT {:0>20}: Hardlinked {} objects and wrote {} objects", From 34129bc0252e6a8a5ac1c12e7d8eb7f8b9d81cb6 Mon Sep 17 00:00:00 2001 From: Kim Altintop Date: Mon, 16 Nov 2026 11:25:21 +0100 Subject: [PATCH 4/5] Global eviction --- crates/datastore/src/error.rs | 10 +- .../locking_tx_datastore/committed_state.rs | 26 +- .../src/locking_tx_datastore/mut_tx.rs | 2 +- .../src/locking_tx_datastore/tx_state.rs | 2 +- crates/table/src/table.rs | 43 +- crates/table/src/tiered/blob_set.rs | 324 +++++++++++++-- crates/table/src/tiered/budget.rs | 15 + crates/table/src/tiered/error.rs | 34 +- crates/table/src/tiered/mem.rs | 105 ++++- crates/table/src/tiered/mod.rs | 6 +- crates/table/src/tiered/page_manager.rs | 50 ++- crates/table/src/tiered/page_set.rs | 380 +++++++++++++++--- 12 files changed, 800 insertions(+), 197 deletions(-) diff --git a/crates/datastore/src/error.rs b/crates/datastore/src/error.rs index 06e8b20279a..a6c0f2ad5bb 100644 --- a/crates/datastore/src/error.rs +++ b/crates/datastore/src/error.rs @@ -10,7 +10,7 @@ use spacetimedb_sats::{AlgebraicType, AlgebraicValue}; use spacetimedb_schema::def::error::LibError; #[cfg(feature = "durability")] use spacetimedb_snapshot::SnapshotError; -use spacetimedb_table::tiered; +use spacetimedb_table::tiered::{self, EvictionError}; use spacetimedb_table::{ bflatn_to, read_column, table::{self, ReadViaBsatnError, UniqueConstraintViolation}, @@ -52,10 +52,6 @@ pub enum DatastoreError { } impl DatastoreError { - pub(crate) fn is_resident_memory_limit(&self) -> bool { - self.resident_memory_limit().is_some() - } - pub fn resident_memory_limit(&self) -> Option<&tiered::BudgetExceeded> { match self { Self::Page(PageError::MemoryLimitExceeded(error)) @@ -137,10 +133,10 @@ pub enum TableError { #[derive(Error, Debug)] pub enum TrimTableError { - #[error(transparent)] - Pages(#[from] PageError), #[error(transparent)] Storage(#[from] tiered::TrimError), + #[error(transparent)] + Eviction(#[from] EvictionError), } #[derive(Error, Debug, PartialEq, Eq)] diff --git a/crates/datastore/src/locking_tx_datastore/committed_state.rs b/crates/datastore/src/locking_tx_datastore/committed_state.rs index f06b8f98c71..cc1b07e03ef 100644 --- a/crates/datastore/src/locking_tx_datastore/committed_state.rs +++ b/crates/datastore/src/locking_tx_datastore/committed_state.rs @@ -1198,35 +1198,11 @@ impl CommittedState { .set(self.storage.blobs().bytes_used_by_blobs() as _); } - /// Evict objects from the cache until the resident size is below the low watermark, - /// or no more objects can be evicted. - /// - /// TODO: Use a database-scoped LRU eviction policy instead of evicting table by table. - pub(super) fn trim_resident(&self) -> Result<()> { - let pages = self.storage.pages(); - let target = pages.resident_budget().low_water_bytes; - for table in self.tables.values() { - if pages.resident_usage().accounted_bytes() <= target { - return Ok(()); - } - table.trim()?; - } - if pages.resident_usage().accounted_bytes() > target { - self.storage.blobs().trim()?; - } - Ok(()) - } - /// Evict live objects when under budget pressure, and reclaim space used by /// orphaned objects. #[cfg(feature = "durability")] pub(super) fn trim(&self) -> std::result::Result<(), crate::error::TrimTableError> { - for table in self.tables.values() { - table.trim()?; - } - self.storage.trim()?; - - Ok(()) + self.storage.trim().map(drop).map_err(Into::into) } /// Reclaim space used by orphaned objects. diff --git a/crates/datastore/src/locking_tx_datastore/mut_tx.rs b/crates/datastore/src/locking_tx_datastore/mut_tx.rs index 809617b9605..0c2106ad534 100644 --- a/crates/datastore/src/locking_tx_datastore/mut_tx.rs +++ b/crates/datastore/src/locking_tx_datastore/mut_tx.rs @@ -617,7 +617,7 @@ pub struct MutTxId { } // The transaction-local blob map is inline to avoid an allocation when empty. -static_assert_size!(MutTxId, 624); +static_assert_size!(MutTxId, 544); impl MutTxId { /// Record that a view performs a table scan in this transaction's read set diff --git a/crates/datastore/src/locking_tx_datastore/tx_state.rs b/crates/datastore/src/locking_tx_datastore/tx_state.rs index ef0fa3fecce..aa60751970c 100644 --- a/crates/datastore/src/locking_tx_datastore/tx_state.rs +++ b/crates/datastore/src/locking_tx_datastore/tx_state.rs @@ -80,7 +80,7 @@ pub(super) struct TxState { pub(super) pending_schema_changes: ThinVec, } -static_assert_size!(TxState, 144); +static_assert_size!(TxState, 64); impl MemoryUsage for TxState { fn heap_usage(&self) -> usize { diff --git a/crates/table/src/table.rs b/crates/table/src/table.rs index 79591e834cc..c3d64e5d408 100644 --- a/crates/table/src/table.rs +++ b/crates/table/src/table.rs @@ -3,9 +3,9 @@ use crate::{ blob_store::BlobHash, page, tiered::{ - BlobError, BlobHandle, BlobReadSet, BlobSet, DiskPinnedBlobHandle, DiskPinnedPageHandle, EvictionPolicy, - ObjectStoreError, PageBorrow, PageError, PageHandle, PageManager, PageRef, PageSet, PreparedCommit, - ReservedPage, + BlobError, BlobHandle, BlobReadSet, BlobSet, DiskPinnedBlobHandle, DiskPinnedPageHandle, EvictionError, + EvictionPolicy, ObjectStoreError, PageBorrow, PageError, PageHandle, PageManager, PageRef, PageSet, + PreparedCommit, ReservedPage, }, var_len::VarLenMembers as _, }; @@ -107,37 +107,6 @@ impl From for TableError { } } -/// Allows a read to request eviction from its enclosing datastore. -pub trait ReadEviction: Send + Sync { - fn evict_for_read(&self) -> Result<(), TableError>; -} - -fn retry_read( - result: Result, - eviction: Option<&dyn ReadEviction>, - retry: impl FnOnce() -> Result, -) -> Result { - let Err(error) = result else { - return result; - }; - let Some(eviction) = eviction else { - return Err(error); - }; - let memory_limit = match &error { - TableError::Page(error) => matches!(error.as_ref(), PageError::MemoryLimitExceeded(_)), - TableError::Blob(error) => matches!(error.as_ref(), BlobError::MemoryLimitExceeded(_)), - TableError::Storage(error) => { - matches!(error.as_ref(), ObjectStoreError::StorageLimitExceeded(_)) - } - }; - if !memory_limit { - return Err(error); - } - // The failed access has returned and released its temporary locks. - eviction.evict_for_read()?; - retry() -} - impl From for TableError { fn from(error: ObjectStoreError) -> Self { Self::Storage(Box::new(error)) @@ -334,12 +303,12 @@ impl TableInner { Ok(self.try_page_and_offset(ptr)?.unwrap()) } - fn trim(&self) -> Result { + fn trim(&self) -> Result { self.pages.trim() } } -static_assert_size!(Table, 336); +static_assert_size!(Table, 328); impl MemoryUsage for Table { fn heap_usage(&self) -> usize { @@ -2604,7 +2573,7 @@ impl Table { } } - pub fn trim(&self) -> Result { + pub fn trim(&self) -> Result { self.inner.trim() } } diff --git a/crates/table/src/tiered/blob_set.rs b/crates/table/src/tiered/blob_set.rs index 904eccb41dd..77cbadf153d 100644 --- a/crates/table/src/tiered/blob_set.rs +++ b/crates/table/src/tiered/blob_set.rs @@ -15,9 +15,9 @@ use crate::{ page::Page, row_type_visitor::VarLenVisitorProgram, tiered::{ - error::{BlobError, ObjectStoreError}, + error::{BlobError, EvictionError, ObjectStoreError}, map::{BlobHashWrapper, ObjectKey}, - mem::{self, BlobEvictionCandidate, BlobFrame, ReservedBlob}, + mem::{self, BlobEvictionCandidate, BlobFrame, EvictionSource, ReservedBlob}, storage::{DiskObject, DiskRetention, Object}, ByteBudget, ByteBudgetUsage, EvictionPolicy, TieredStorage, }, @@ -31,6 +31,19 @@ use crate::{ /// that get evicted from memory are handed off to the shared [TieredStorage]. #[derive(Debug)] pub struct BlobSet { + inner: Arc, +} + +impl Deref for BlobSet { + type Target = BlobSetInner; + + fn deref(&self) -> &Self::Target { + &self.inner + } +} + +#[derive(Debug)] +pub struct BlobSetInner { resident: Arc, storage: Arc, entries: RwLock>, @@ -41,12 +54,20 @@ pub struct BlobSet { impl BlobSet { /// Create a new, empty [BlobSet]. pub fn new(resident: Arc, storage: Arc) -> Self { - Self { + Self::from_inner(BlobSetInner { resident, storage, entries: <_>::default(), evictable: <_>::default(), - } + }) + } + + fn from_inner(inner: BlobSetInner) -> Self { + let inner = Arc::new(inner); + let source: Arc = inner.clone(); + inner.resident.register_eviction_source(&source); + + Self { inner } } /// Create a new [BlobSet] from externally loaded blobs. @@ -54,7 +75,11 @@ impl BlobSet { /// This is used when restoring from a snapshot. /// /// All blobs in the map will initially be resident, bypassing the memory budget. - pub fn from_blob_map(resident: Arc, storage: Arc, map: BlobMap) -> Self { + pub fn from_blob_map( + resident: Arc, + storage: Arc, + map: BlobMap, + ) -> Self { let mut entries = IntMap::default(); for (key, BlobMapEntry { uses, blob }) in map.inner { let frame = resident.register_blob_unchecked(blob); @@ -70,12 +95,12 @@ impl BlobSet { ); } - Self { + Self::from_inner(BlobSetInner { resident, storage, entries: RwLock::new(entries), evictable: <_>::default(), - } + }) } pub fn new_for_test() -> Self { @@ -89,8 +114,8 @@ impl BlobSet { /// met. /// /// See also: [Self::evict]. - pub fn trim(&self) -> Result { - self.evict(self.resident.budget().config().low_water_bytes) + fn trim(&self) -> Result { + self.resident.trim() } /// Attempt to evict resident blobs in this set that have no external @@ -101,9 +126,9 @@ impl BlobSet { /// resident pages may also prevent the usage to meet the target. /// /// Returns the number of bytes freed. - pub fn evict(&self, target_usage: u64) -> Result { + pub fn evict(&self, target_usage: u64) -> Result { let timer = self.resident.metrics().timer(); - let result = self.evict_inner(target_usage); + let result = self.inner.evict(target_usage); self.resident .metrics() .eviction(EvictionDirection::MemoryToDisk, timer.nanos()); @@ -120,15 +145,26 @@ impl BlobSet { let mut candidates = self.evictable.lock(); self.resident.evictable_blobs(&mut candidates); for candidate in candidates.drain(..) { - let maybe_resident = self.entries.read().get(&candidate.key).and_then(|entry| match entry { - BlobEntry::Resident { blob, pins, .. } => (pins == &0).then(|| blob.clone()), - BlobEntry::NonResident { .. } => None, - }); + let maybe_resident = + self.entries + .read() + .get(&candidate.key) + .and_then(|entry| match entry { + BlobEntry::Resident { blob, pins, .. } => { + (pins == &0).then(|| blob.clone()) + } + BlobEntry::NonResident { .. } => None, + }); if let Some(blob) = maybe_resident { - let mut backing = self.storage.write(Object::from(&blob), DiskRetention::Required)?; + let mut backing = self + .storage + .write(Object::from(&blob), DiskRetention::Required)?; assert_eq!( - backing.key().as_blob_hash().expect("storage key to be a blob hash"), + backing + .key() + .as_blob_hash() + .expect("storage key to be a blob hash"), &candidate.key ); @@ -157,7 +193,8 @@ impl BlobSet { // // An evictable frame must have exactly two references: one in // `entries` + the clone of `blob` that was done above. - if !Arc::ptr_eq(&blob.frame, ¤t.frame) || Arc::strong_count(&blob.frame) != 2 { + if !Arc::ptr_eq(&blob.frame, ¤t.frame) || Arc::strong_count(&blob.frame) != 2 + { continue; }; @@ -168,9 +205,11 @@ impl BlobSet { size, backing, }; - self.resident - .metrics() - .evicted(ObjectType::Blob, EvictionDirection::MemoryToDisk, size); + self.resident.metrics().evicted( + ObjectType::Blob, + EvictionDirection::MemoryToDisk, + size, + ); drop(blob); self.resident.evict_blob(candidate); drop(entries); @@ -211,7 +250,11 @@ impl BlobSet { /// Insert `bytes` into this set, making it a resident blob. /// /// Subject to the memory budget. - pub fn insert(&self, eviction_policy: EvictionPolicy, bytes: &[u8]) -> Result { + pub fn insert( + &self, + eviction_policy: EvictionPolicy, + bytes: &[u8], + ) -> Result { self.insert_with_memory_limit_exemption(eviction_policy, bytes, false) } @@ -351,7 +394,11 @@ impl BlobSet { /// entry catalog. /// /// On success returns the size in bytes of the blob. - pub fn free_ref(&self, hash: BlobHashWrapper, eviction_policy: EvictionPolicy) -> Result { + pub fn free_ref( + &self, + hash: BlobHashWrapper, + eviction_policy: EvictionPolicy, + ) -> Result { let mut entries = self.entries.write(); match entries.entry(hash) { hash_map::Entry::Vacant(_) => Err(BlobError::MissingBlob(Box::new(hash.into()))), @@ -397,7 +444,9 @@ impl BlobSet { BlobEntry::Resident { blob, .. } => Ok::<_, BlobError>(Ok(blob.clone())), BlobEntry::NonResident { .. } => { let fault_guard = fault.insert(self.resident.metrics().fault(ObjectType::Blob)); - let bytes = self.storage.read_with_source(hash.into(), &mut fault_guard.source)?; + let bytes = self + .storage + .read_with_source(hash.into(), &mut fault_guard.source)?; Ok(Err(bytes)) } } @@ -529,7 +578,10 @@ impl BlobSet { /// object is present on disk and eviction is prevented. Otherwise, the /// memory-resident blob's [BlobHandle] is retained, preventing memory /// eviction. - pub(crate) fn ensure_disk(&self, hash: BlobHashWrapper) -> Result { + pub(crate) fn ensure_disk( + &self, + hash: BlobHashWrapper, + ) -> Result { let mut entries = self.entries.write(); let Some(entry) = entries.get_mut(&hash) else { return Err(ObjectStoreError::UnknownObject(hash.into())); @@ -627,7 +679,9 @@ impl BlobSet { #[cfg(test)] impl BlobSet { - pub fn usage_counter(&self) -> spacetimedb_data_structures::map::HashMap { + pub fn usage_counter( + &self, + ) -> spacetimedb_data_structures::map::HashMap { self.entries .read() .iter() @@ -644,8 +698,14 @@ impl MemoryUsage for BlobSet { fn heap_usage(&self) -> usize { // Cache and backing store are counted by `TieredDatabaseStorage`. let scratch = self.evictable.lock().capacity() * size_of::(); + self.inner.heap_usage() + } +} - self.entries.read().heap_usage() + scratch +impl MemoryUsage for BlobSetInner { + fn heap_usage(&self) -> usize { + let scratch = self.evictable.lock().capacity() + size_of::(); + scratch + self.entries.read().heap_usage() } } @@ -723,7 +783,9 @@ impl BlobEntry { fn pin_disk(&mut self) { match self { - Self::Resident { backing, disk_pins, .. } => { + Self::Resident { + backing, disk_pins, .. + } => { *disk_pins = disk_pins.checked_add(1).expect("disk pin count overflow"); if let Some(backing) = backing { backing.pin(); @@ -735,7 +797,9 @@ impl BlobEntry { fn unpin_disk(&mut self) { match self { - Self::Resident { backing, disk_pins, .. } => { + Self::Resident { + backing, disk_pins, .. + } => { *disk_pins = disk_pins .checked_sub(1) .expect("attempt to decrement disk pin count already at zero"); @@ -814,7 +878,9 @@ impl BlobReadSet { let row_data = page.get_row_data(offset, layout.size()); let mut inner = SmallHashMap::default(); for vlr in unsafe { visitor.visit_var_len(row_data) }.filter(|vlr| vlr.is_large_blob()) { - let granule = unsafe { page.iter_var_len_object(vlr.first_granule) }.next().unwrap(); + let granule = unsafe { page.iter_var_len_object(vlr.first_granule) } + .next() + .unwrap(); let blob_hash = granule.blob_hash().into(); let blob = blobs.get(blob_hash)?; inner.insert(blob_hash, blob); @@ -855,7 +921,8 @@ impl BlobMap { /// equal to `BlobHash::hash_from_bytes(blob)`. pub fn insert_with_uses(&mut self, hash: &BlobHash, uses: NonZeroUsize, blob: Box<[u8]>) { debug_assert_eq!(hash, &BlobHash::hash_from_bytes(&blob)); - self.inner.insert((*hash).into(), BlobMapEntry { uses, blob }); + self.inner + .insert((*hash).into(), BlobMapEntry { uses, blob }); } pub fn iter(&self) -> impl Iterator { @@ -886,21 +953,200 @@ impl IntoIterator for BlobMap { } } +impl EvictionSource for BlobSetInner { + fn evict(&self, target_usage: u64) -> Result { + let mut bytes_freed = 0; + + if self.resident.usage().accounted_bytes() <= target_usage { + return Ok(bytes_freed); + } + + let mut candidates = self.evictable.lock(); + self.resident.evictable_blobs(&mut candidates); + for candidate in candidates.drain(..) { + let maybe_resident = + self.entries + .read() + .get(&candidate.key) + .and_then(|entry| match entry { + BlobEntry::Resident { blob, pins, .. } => { + (pins == &0).then(|| blob.clone()) + } + BlobEntry::NonResident { .. } => None, + }); + + if let Some(blob) = maybe_resident { + let mut backing = self + .storage + .write(Object::from(&blob), DiskRetention::Required) + .map_err(Box::new)?; + assert_eq!( + backing + .key() + .as_blob_hash() + .expect("storage key to be a blob hash"), + &candidate.key + ); + + let mut entries = self.entries.write(); + let Some(entry) = entries.get_mut(&candidate.key) else { + continue; + }; + let BlobEntry::Resident { + uses, + blob: current, + pins, + disk_pins, + .. + } = entry + else { + continue; + }; + // Skip pinned entries. + if *pins > 0 { + continue; + } + // Eviction may proceed concurrent to blob set access, in + // particular we're not holding an entries lock while writing to + // the tiered storage. Therefore, ensure that the entry is still + // the same allocation. + // + // An evictable frame must have exactly two references: one in + // `entries` + the clone of `blob` that was done above. + if !Arc::ptr_eq(&blob.frame, ¤t.frame) || Arc::strong_count(&blob.frame) != 2 + { + continue; + }; + + let size = blob.size(); + backing.set_pins(*disk_pins); + *entry = BlobEntry::NonResident { + uses: *uses, + size, + backing, + }; + self.resident.metrics().evicted( + ObjectType::Blob, + EvictionDirection::MemoryToDisk, + size, + ); + drop(blob); + self.resident.evict_blob(candidate); + drop(entries); + bytes_freed += size; + + if self.resident.usage().accounted_bytes() <= target_usage { + break; + } + } + } + + Ok(bytes_freed) + } +} + #[cfg(test)] mod tests { - use std::{collections::HashMap, sync::Arc}; + use std::{collections::HashMap, num::NonZeroUsize, sync::Arc}; use proptest::{collection::vec, prelude::*}; use crate::{ blob_store::BlobHash, tiered::{ - map::BlobHashWrapper, metrics::CacheTier, BlobError, BlobSet, ByteBudget, ByteBudgetConfig, EvictionPolicy, - ResidentObjects, TieredStorage, + map::BlobHashWrapper, metrics::CacheTier, BlobError, BlobMap, BlobSet, ByteBudget, + ByteBudgetConfig, EvictionPolicy, ResidentObjects, TieredStorage, }, }; proptest! { + #[test] + fn global_eviction_reclaims_another_catalog_and_preserves_it_after_rollback( + first in vec(any::(), 1..2048), + second in vec(any::(), 1..2048), + restored in any::(), + ) { + let first_hash = BlobHash::hash_from_bytes(&first); + let second_hash = BlobHash::hash_from_bytes(&second); + prop_assume!(first_hash != second_hash); + + // The shared budget can hold either blob, but never both. Exercise + // registration both for ordinary catalogs and snapshot restoration. + let limit = first.len().max(second.len()) as u64; + let budget = ByteBudget::new(ByteBudgetConfig { + tier: CacheTier::Memory, + low_water_bytes: 0, + soft_limit_bytes: limit, + hard_limit_bytes: limit, + }).unwrap(); + let resident = Arc::new(ResidentObjects::new(budget)); + let storage = Arc::new(TieredStorage::new_for_test()); + let committed = if restored { + let mut map = BlobMap::default(); + map.insert_with_uses(&first_hash, NonZeroUsize::MIN, first.clone().into_boxed_slice()); + BlobSet::from_blob_map(resident.clone(), storage.clone(), map) + } else { + let set = BlobSet::new(resident.clone(), storage.clone()); + drop(set.insert(EvictionPolicy::Memory, &first).unwrap()); + set + }; + let transaction = BlobSet::new(resident.clone(), storage); + + // Allocation in an empty transaction must reclaim committed memory. + // Faulting either catalog back in must also be able to evict the other. + drop(transaction.insert(EvictionPolicy::Memory, &second).unwrap()); + prop_assert_eq!(committed.resident_bytes_used_by_blobs(), 0); + prop_assert_eq!(&*committed.get(first_hash.into()).unwrap(), first.as_slice()); + prop_assert_eq!(transaction.resident_bytes_used_by_blobs(), 0); + prop_assert_eq!(&*transaction.get(second_hash.into()).unwrap(), second.as_slice()); + prop_assert_eq!(committed.resident_bytes_used_by_blobs(), 0); + + // Discarding the transaction must not discard or change the committed + // catalog, even though it evicted the committed blob during execution. + drop(transaction); + prop_assert_eq!(resident.usage().accounted_bytes(), 0); + prop_assert_eq!(committed.num_blobs(), 1); + prop_assert_eq!(committed.uses(first_hash.into()), Some(1)); + prop_assert_eq!(&*committed.get(first_hash.into()).unwrap(), first.as_slice()); + prop_assert_eq!(resident.usage().accounted_bytes(), first.len() as u64); + } + + #[test] + fn global_eviction_respects_a_handle_in_another_catalog( + first in vec(any::(), 1..2048), + second in vec(any::(), 1..2048), + ) { + prop_assume!(BlobHash::hash_from_bytes(&first) != BlobHash::hash_from_bytes(&second)); + let limit = first.len().max(second.len()) as u64; + let budget = ByteBudget::new(ByteBudgetConfig { + tier: CacheTier::Memory, + low_water_bytes: 0, + soft_limit_bytes: limit, + hard_limit_bytes: limit, + }).unwrap(); + let resident = Arc::new(ResidentObjects::new(budget)); + let storage = Arc::new(TieredStorage::new_for_test()); + let committed = BlobSet::new(resident.clone(), storage.clone()); + let transaction = BlobSet::new(resident.clone(), storage); + let pin = committed.insert(EvictionPolicy::Memory, &first).unwrap(); + + // A global sweep must preserve a live handle and leave no partial + // catalog entry behind when the allocation still cannot fit. + prop_assert!(matches!( + transaction.insert(EvictionPolicy::Memory, &second), + Err(BlobError::MemoryLimitExceeded(_)) + )); + prop_assert_eq!(&*pin, first.as_slice()); + prop_assert_eq!(transaction.num_blobs(), 0); + prop_assert_eq!(resident.usage().accounted_bytes(), first.len() as u64); + + // Releasing the handle makes the same request succeed across catalogs. + drop(pin); + let inserted = transaction.insert(EvictionPolicy::Memory, &second).unwrap(); + prop_assert_eq!(&*inserted, second.as_slice()); + prop_assert_eq!(committed.resident_bytes_used_by_blobs(), 0); + } + #[test] fn insertion_deduplicates_content_and_tracks_reference_counts( blobs in vec(vec(any::(), 0..1024), 0..100), @@ -1024,14 +1270,20 @@ mod tests { let committed = BlobSet::new(resident.clone(), storage); // Emulate transaction prepare. - transaction.insert(EvictionPolicy::Memory, bytes).map(drop).unwrap(); + transaction + .insert(EvictionPolicy::Memory, bytes) + .map(drop) + .unwrap(); let pins = transaction.fault_all().unwrap(); // Emulate transaction commit. // The shared [ResidentObjects] notices that it's the same object, so // reuses the already-held budget permit. assert!(committed.usage_counter().is_empty()); - committed.insert(EvictionPolicy::Memory, bytes).map(drop).unwrap(); + committed + .insert(EvictionPolicy::Memory, bytes) + .map(drop) + .unwrap(); assert_eq!(committed.usage_counter().get(&pins[0].hash()), Some(&1)); assert_eq!(resident.usage().accounted_bytes(), bytes.len() as u64); diff --git a/crates/table/src/tiered/budget.rs b/crates/table/src/tiered/budget.rs index e9d5347320a..04731fb123e 100644 --- a/crates/table/src/tiered/budget.rs +++ b/crates/table/src/tiered/budget.rs @@ -59,6 +59,10 @@ impl ByteBudget { } } + pub fn budget_view(&self) -> ByteBudgetStateView { + ByteBudgetStateView(self.state.clone()) + } + pub fn acquire(&self, bytes: u64) -> Result { self.acquire_with_exemption(bytes, false) } @@ -191,6 +195,17 @@ impl ByteBudgetUsage { } } +/// A read-only [ByteBudgetState]. +#[derive(Debug)] +pub struct ByteBudgetStateView(Arc>); + +impl ByteBudgetStateView { + pub fn usage(&self) -> ByteBudgetUsage { + let accounted_bytes = self.0.lock().unwrap().accounted_bytes; + ByteBudgetUsage { accounted_bytes } + } +} + #[derive(Debug)] pub struct BudgetPermit { state: Arc>, diff --git a/crates/table/src/tiered/error.rs b/crates/table/src/tiered/error.rs index 632e14b1ded..8fc710d5dcf 100644 --- a/crates/table/src/tiered/error.rs +++ b/crates/table/src/tiered/error.rs @@ -25,6 +25,8 @@ pub enum PageError { Deserialize(#[from] Box), #[error(transparent)] Storage(#[from] Box), + #[error("failed to evict objects")] + Eviction(#[from] Box), } impl From for PageError { @@ -57,6 +59,7 @@ impl PageError { | PageError::Deserialize(_) => false, PageError::Storage(storage) => storage.is_transient(), + PageError::Eviction(eviction) => eviction.is_transient(), } } } @@ -69,6 +72,8 @@ pub enum BlobError { MissingBlob(Box), #[error(transparent)] Storage(#[from] Box), + #[error("failed to evict objects")] + Eviction(#[from] Box), } impl From for BlobError { @@ -83,11 +88,18 @@ impl From for BlobError { } } +impl From for BlobError { + fn from(error: EvictionError) -> Self { + Self::Eviction(Box::new(error)) + } +} + impl BlobError { pub fn is_transient(&self) -> bool { match self { BlobError::MemoryLimitExceeded(_) | BlobError::MissingBlob(_) => false, BlobError::Storage(storage) => storage.is_transient(), + BlobError::Eviction(inner) => inner.is_transient(), } } } @@ -137,7 +149,27 @@ impl ObjectStoreError { #[derive(Debug, thiserror::Error)] pub enum TrimError { #[error(transparent)] - Blob(#[from] BlobError), + Eviction(#[from] EvictionError), #[error(transparent)] Store(#[from] ObjectStoreError), } + +#[derive(Debug, thiserror::Error)] +pub enum EvictionError { + #[error("failed to evict pages")] + Page(#[from] Box), + #[error("failed to evict blobs")] + Blob(#[from] Box), + #[error("failed to demote to lower tier")] + Storage(#[from] Box), +} + +impl EvictionError { + pub fn is_transient(&self) -> bool { + match self { + Self::Page(e) => e.is_transient(), + Self::Blob(e) => e.is_transient(), + Self::Storage(e) => e.is_transient(), + } + } +} diff --git a/crates/table/src/tiered/mem.rs b/crates/table/src/tiered/mem.rs index 137cc0b2de0..06c48df80d8 100644 --- a/crates/table/src/tiered/mem.rs +++ b/crates/table/src/tiered/mem.rs @@ -5,11 +5,11 @@ use std::{ ops::{Deref, DerefMut}, sync::{ atomic::{AtomicU64, Ordering}, - Arc, Mutex, Weak, + Arc, Weak, }, }; -use parking_lot::{ArcRwLockReadGuard, ArcRwLockWriteGuard, RawRwLock, RwLock, RwLockWriteGuard}; +use parking_lot::{ArcRwLockReadGuard, ArcRwLockWriteGuard, Mutex, RawRwLock, RwLock, RwLockWriteGuard}; use spacetimedb_data_structures::map::{hash_map, IntMap, ValidAsIdentityHash}; use spacetimedb_memory_usage::MemoryUsage; @@ -18,7 +18,10 @@ use crate::{ indexes::PAGE_SIZE, page::Page, page_pool::PagePool, - tiered::{map::BlobHashWrapper, BudgetExceeded, BudgetPermit, ByteBudget, ByteBudgetUsage}, + tiered::{ + budget::ByteBudgetStateView, error::EvictionError, map::BlobHashWrapper, metrics::EvictionDirection, + BudgetExceeded, BudgetPermit, ByteBudget, ByteBudgetUsage, + }, }; #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -170,6 +173,7 @@ pub struct ResidentObjects { page_id: AtomicU64, pages: Mutex>>, blobs: Mutex>>, + eviction: Arc, } impl ResidentObjects { @@ -198,12 +202,17 @@ impl ResidentObjects { } pub fn new(budget: ByteBudget) -> Self { + let eviction = Eviction { + usage: budget.budget_view(), + sources: <_>::default(), + }; Self { budget, access_epoch: AtomicU64::new(1), page_id: <_>::default(), pages: <_>::default(), blobs: <_>::default(), + eviction: Arc::new(eviction), } } @@ -216,7 +225,7 @@ impl ResidentObjects { ) -> Result { // Transaction and committed blob set share this registry. // Hand out an existing frame if there is one. - if let Some(frame) = self.blobs.lock().unwrap().get(&hash).and_then(Weak::upgrade) { + if let Some(frame) = self.blobs.lock().get(&hash).and_then(Weak::upgrade) { return Ok(ReservedBlob { frame }); } let permit = self.acquire(size, memory_limit_exempt)?; @@ -237,7 +246,7 @@ impl ResidentObjects { pub(super) fn redeem_blob(&self, ReservedBlob { frame }: ReservedBlob) -> Arc { let key = frame.hash; - let mut blobs = self.blobs.lock().unwrap(); + let mut blobs = self.blobs.lock(); // Transaction and committed blob sets share this registry. Reuse live // frames and replace stale weak entries when a hash becomes resident again. if let Some(existing) = blobs.get(&key).and_then(Weak::upgrade) { @@ -256,7 +265,7 @@ impl ResidentObjects { // - one ref is held by a blob set const EVICTABLE_REFCOUNT: usize = 2; - let mut blobs = self.blobs.lock().unwrap(); + let mut blobs = self.blobs.lock(); blobs.retain(|&key, weak| { let Some(frame) = weak.upgrade() else { return false; @@ -276,7 +285,7 @@ impl ResidentObjects { } pub(super) fn evict_blob(&self, victim: BlobEvictionCandidate) { - let mut blobs = self.blobs.lock().unwrap(); + let mut blobs = self.blobs.lock(); if let hash_map::Entry::Occupied(entry) = blobs.entry(victim.key) && entry.get().strong_count() == 0 { @@ -300,13 +309,13 @@ impl ResidentObjects { pub(super) fn redeem_page(&self, ReservedPage { id, frame }: ReservedPage) -> Arc { let frame = Arc::new(frame); - assert!(self.pages.lock().unwrap().insert(id, Arc::downgrade(&frame)).is_none()); + assert!(self.pages.lock().insert(id, Arc::downgrade(&frame)).is_none()); frame } pub(super) fn evictable_pages(&self, candidates: &mut Vec) { { - let mut pages = self.pages.lock().unwrap(); + let mut pages = self.pages.lock(); pages.retain(|&id, weak| { let Some(frame) = weak.upgrade() else { return false; @@ -327,7 +336,7 @@ impl ResidentObjects { } pub(super) fn evict_page(&self, victim: PageEvictionCandidate) { - let mut pages = self.pages.lock().unwrap(); + let mut pages = self.pages.lock(); if let hash_map::Entry::Occupied(entry) = pages.entry(victim.id) && entry.get().strong_count() == 0 { @@ -352,7 +361,7 @@ impl ResidentObjects { pub(super) fn detach_page(&self, frame: Arc) -> (Box, BudgetPermit) { // The memory table will own the page directly. Remove the frame from // eviction tracking, but keep its allocation and memory charge alive. - assert!(self.pages.lock().unwrap().remove(&frame.id).is_some()); + assert!(self.pages.lock().remove(&frame.id).is_some()); Arc::try_unwrap(frame) .expect("page ownership transfer requires all eviction pins to be dropped") .into_owned() @@ -388,15 +397,36 @@ impl ResidentObjects { ReservedBlob { frame } } + + pub(super) fn trim(&self) -> Result { + self.evict(self.budget.config().low_water_bytes) + } + + pub(super) fn evict(&self, target_usage: u64) -> Result { + let timer = self.metrics().timer(); + let result = self.eviction.evict(target_usage); + self.metrics().eviction(EvictionDirection::MemoryToDisk, timer.nanos()); + result + } + + pub(super) fn register_eviction_source(&self, source: &Arc) { + self.eviction.register(source); + } } impl MemoryUsage for ResidentObjects { fn heap_usage(&self) -> usize { - // `pages` and `blobs` contain weak references, count just the container - // allocations. - self.budget.heap_usage() - + self.pages.lock().unwrap().allocation_size() - + self.blobs.lock().unwrap().allocation_size() + let Self { + budget, + access_epoch: _, + page_id: _, + pages, + blobs, + eviction, + } = self; + // `pages` and `blobs` contain only weak references, so report only the + // size of the map allocations. + pages.lock().allocation_size() + blobs.lock().allocation_size() + budget.heap_usage() + eviction.heap_usage() } } @@ -534,3 +564,46 @@ impl fmt::Debug for PooledPage { f.debug_struct("PooledPage").field("page", &self.page).finish() } } + +pub(super) trait EvictionSource: fmt::Debug + Send + Sync { + fn evict(&self, target: u64) -> Result; +} + +#[derive(Debug)] +struct Eviction { + usage: ByteBudgetStateView, + sources: Mutex>>, +} + +impl Eviction { + fn register(&self, source: &Arc) { + self.sources.lock().push(Arc::downgrade(source)) + } + + fn evict(&self, target: u64) -> Result { + let mut bytes_freed = 0; + let sources = { + let mut sources = self.sources.lock(); + sources.retain(|s| s.strong_count() > 0); + sources.iter().filter_map(Weak::upgrade).collect::>() + }; + + for source in sources { + if self.usage.usage().accounted_bytes <= target { + break; + } + + bytes_freed += source.evict(target)?; + } + + Ok(bytes_freed) + } +} + +impl MemoryUsage for Eviction { + fn heap_usage(&self) -> usize { + // Don't count the budget, as it is already accounted for by + // [ResidentObjects]. + self.sources.lock().capacity() + size_of::>() + } +} diff --git a/crates/table/src/tiered/mod.rs b/crates/table/src/tiered/mod.rs index bcfdd63f8c7..48c85558911 100644 --- a/crates/table/src/tiered/mod.rs +++ b/crates/table/src/tiered/mod.rs @@ -19,7 +19,7 @@ pub(crate) use self::{blob_set::DiskPinnedBlobHandle, page_set::DiskPinnedPageHa pub use self::{ blob_set::{BlobHandle, BlobMap, BlobReadSet, BlobSet}, budget::{BudgetExceeded, BudgetPermit, ByteBudget, ByteBudgetConfig, ByteBudgetUsage}, - error::{BlobError, ObjectStoreError, PageError, TrimError}, + error::{BlobError, EvictionError, ObjectStoreError, PageError, TrimError}, map::ObjectKey, mem::ResidentObjects, page_manager::{PageHandle, PageManager, ReservedPage}, @@ -138,11 +138,11 @@ impl TieredDatabaseStorage { } /// Attempt to free space by reclaiming orphaned objects and evicting from - /// the shared blob set and local storage. + /// memory resident sets and local storage. /// /// Returns the total number of bytes freed. pub fn trim(&self) -> Result { - let mut bytes_freed = self.blobs.trim()?; + let mut bytes_freed = self.cache.trim()?; bytes_freed += self.store.trim()?; Ok(bytes_freed) diff --git a/crates/table/src/tiered/page_manager.rs b/crates/table/src/tiered/page_manager.rs index 840c2704f9d..ab64601abb8 100644 --- a/crates/table/src/tiered/page_manager.rs +++ b/crates/table/src/tiered/page_manager.rs @@ -1,7 +1,7 @@ use super::metrics::{with_fault, CacheTier, Fault, Metrics, ObjectType}; use std::{ ops::{Deref, DerefMut}, - sync::Arc, + sync::{Arc, Weak}, }; use parking_lot::{ @@ -17,9 +17,9 @@ use crate::{ page::{Page, PageMetadata}, page_pool::PagePool, tiered::{ - error::PageError, + error::{EvictionError, PageError}, map::PageHash, - mem::{self, PageEvictionCandidate, PageFrame, PageId, PooledPage}, + mem::{self, EvictionSource, PageEvictionCandidate, PageFrame, PageId, PooledPage}, storage::{DiskObject, TieredStorage}, BudgetExceeded, BudgetPermit, ByteBudget, ByteBudgetConfig, ByteBudgetUsage, EvictionPolicy, ObjectStoreError, ResidentObjects, @@ -155,11 +155,26 @@ impl PageSlotHandle { self.slot.lock().page_id() } + pub(super) fn try_page_id(&self) -> Option { + let guard = self.slot.try_lock()?; + guard.page_id() + } + + pub(super) fn downgrade(&self) -> WeakPageSlotHandle { + WeakPageSlotHandle { + slot: Arc::downgrade(&self.slot), + } + } + pub(super) fn lock_ref(&self) -> MutexGuard<'_, PageSlot> { self.slot.lock() } - fn lock_owned(&self) -> ArcMutexGuard { + pub(super) fn try_lock_ref(&self) -> Option> { + self.slot.try_lock() + } + + pub(super) fn lock_owned(&self) -> ArcMutexGuard { self.slot.lock_arc() } @@ -196,6 +211,21 @@ impl MemoryUsage for PageSlotHandle { } } +#[derive(Debug)] +pub(crate) struct WeakPageSlotHandle { + slot: Weak>, +} + +impl WeakPageSlotHandle { + pub fn upgrade(&self) -> Option { + self.slot.upgrade().map(|slot| PageSlotHandle { slot }) + } + + pub fn strong_count(&self) -> usize { + self.slot.strong_count() + } +} + /// State of a page. #[derive(Debug)] #[allow(unused)] @@ -759,6 +789,18 @@ impl PageManager { ) -> Result { self.storage.write(page.into(), eviction_policy) } + + pub(super) fn trim_all(&self) -> Result { + self.resident.trim() + } + + pub(super) fn evict_all(&self, target_usage: u64) -> Result { + self.resident.evict(target_usage) + } + + pub(super) fn register_eviction_source(&self, source: &Arc) { + self.resident.register_eviction_source(source); + } } impl MemoryUsage for PageManager { diff --git a/crates/table/src/tiered/page_set.rs b/crates/table/src/tiered/page_set.rs index af62e2a9d3b..01c12913349 100644 --- a/crates/table/src/tiered/page_set.rs +++ b/crates/table/src/tiered/page_set.rs @@ -2,9 +2,10 @@ use super::metrics::{with_fault, CacheTier, EvictionDirection, Fault, ObjectType use std::{ collections::{btree_map, BTreeMap, BTreeSet}, convert::Infallible, - sync::{Arc, Mutex}, + sync::Arc, }; +use parking_lot::Mutex; use spacetimedb_data_structures::map::IntMap; use spacetimedb_lib::ProductValue; use spacetimedb_memory_usage::MemoryUsage; @@ -17,10 +18,10 @@ use crate::{ table::{BlobNumBytes, PreparedInsert, Table, TableError}, tiered::{ blob_set::BlobHandle, - mem::{PageEvictionCandidate, PageId}, - page_manager::{PageHandle, PageManager, PageSlot, PageSlotHandle, ReservedPage}, + mem::{EvictionSource, PageEvictionCandidate, PageId}, + page_manager::{PageHandle, PageManager, PageSlot, PageSlotHandle, ReservedPage, WeakPageSlotHandle}, storage::DiskObject, - BlobSet, BudgetPermit, EvictionPolicy, ObjectStoreError, PageError, PageRead, PageRef, + BlobSet, BudgetPermit, EvictionError, EvictionPolicy, Object, ObjectStoreError, PageError, PageRead, PageRef, }, var_len::VarLenMembers, }; @@ -50,11 +51,18 @@ enum PageStorage { } /// Evictable pages retain shared slots and frames so readers can pin their contents. -#[derive(Debug, Default)] +#[derive(Debug)] struct TieredPages { slots: Vec, + eviction: Arc, free_page_slots: BTreeSet, non_full_pages: BTreeSet<(usize, PageIndex)>, +} + +#[derive(Debug)] +struct PageSetEviction { + manager: Arc, + slots: Mutex>, evictable: Mutex, } @@ -118,7 +126,7 @@ impl ResidentPages { let mut tiered = TieredPages { free_page_slots: std::mem::take(&mut self.pages.free_page_slots), non_full_pages: std::mem::take(&mut self.pages.non_full_pages), - ..TieredPages::default() + ..TieredPages::new(manager) }; // Move each allocation together with its existing memory charge. Keep // empty slots too: compacting the slots would invalidate row pointers. @@ -186,9 +194,25 @@ impl ResidentPages { } impl TieredPages { + fn new(manager: &Arc) -> Self { + let eviction = Arc::new(PageSetEviction { + manager: manager.clone(), + slots: <_>::default(), + evictable: <_>::default(), + }); + manager.register_eviction_source(&(eviction.clone() as Arc)); + Self { + eviction, + slots: <_>::default(), + free_page_slots: <_>::default(), + non_full_pages: <_>::default(), + } + } + fn into_resident(self, manager: &PageManager, fixed_row_size: Size) -> ResidentPages { - let mut pages = Vec::with_capacity(self.slots.len()); - let mut permits = smallvec::SmallVec::with_capacity(self.slots.len()); + let slot_count = self.slots.len(); + let mut pages = Vec::with_capacity(slot_count); + let mut permits = smallvec::SmallVec::with_capacity(slot_count); for slot in self.slots { let (page, permit) = manager.detach_resident(slot).unzip(); pages.push(page); @@ -204,28 +228,25 @@ impl TieredPages { fn with_page_retry<'a, T>( &self, - manager: &'a PageManager, mut f: impl FnMut(&mut Option>) -> Result, ) -> Result { - with_fault(|fault| self.with_eviction_retry(manager, || f(fault))) + with_fault(|fault| self.with_eviction_retry(|| f(fault))) } - fn with_eviction_retry( - &self, - manager: &PageManager, - mut f: impl FnMut() -> Result, - ) -> Result { + fn with_eviction_retry(&self, mut f: impl FnMut() -> Result) -> Result { match f() { Err(PageError::MemoryLimitExceeded(_)) => { - self.trim(manager)?; + self.eviction.trim().map_err(Box::new)?; f() } res => res, } } - pub fn trim(&self, manager: &PageManager) -> Result { - self.evict(manager, manager.resident_budget().low_water_bytes) + fn reset_eviction(&mut self) { + let mut weak_slots = self.eviction.slots.lock(); + weak_slots.clear(); + weak_slots.extend(self.slots.iter().map(PageSlotHandle::downgrade)); } fn apply_eviction_policy(&self, policy: EvictionPolicy) { @@ -252,34 +273,36 @@ impl TieredPages { } } } +} - pub fn evict(&self, manager: &PageManager, target_usage: u64) -> Result { - let timer = manager.metrics().timer(); - let result = self.evict_inner(manager, target_usage); - manager - .metrics() - .eviction(EvictionDirection::MemoryToDisk, timer.nanos()); - result +impl PageSetEviction { + fn trim(&self) -> Result { + self.manager.trim_all() } +} - fn evict_inner(&self, manager: &PageManager, target_usage: u64) -> Result { +impl EvictionSource for PageSetEviction { + fn evict(&self, target_usage: u64) -> Result { let mut bytes_freed = 0; - if manager.resident_usage().accounted_bytes() <= target_usage { + if self.manager.resident_usage().accounted_bytes() <= target_usage { return Ok(bytes_freed); } - let mut guard = self.evictable.lock().unwrap(); + let mut guard = self.evictable.lock(); let (candidates, slots) = &mut *guard; - manager.evictable(candidates); + self.manager.evictable(candidates); if candidates.is_empty() { return Ok(bytes_freed); } + let mut weak_slots = self.slots.lock(); + weak_slots.retain(|s| s.strong_count() > 0); slots.clear(); - slots.extend(self.slots.iter().enumerate().filter_map(|(idx, slot_handle)| { - let page_id = slot_handle.page_id()?; + slots.extend(weak_slots.iter().enumerate().filter_map(|(idx, weak_handle)| { + let handle = weak_handle.upgrade()?; + let page_id = handle.try_page_id()?; Some((page_id, PageIndex(idx as _))) })); @@ -287,7 +310,12 @@ impl TieredPages { let Some(page_index) = slots.remove(&candidate.id) else { continue; }; - let mut slot = self.slots[page_index.idx()].lock_ref(); + let Some(slot) = weak_slots[page_index.idx()].upgrade() else { + continue; + }; + let Some(mut slot) = slot.try_lock_ref() else { + continue; + }; let PageSlot::Resident { handle: page_handle, metadata, @@ -307,19 +335,22 @@ impl TieredPages { Some(disk_object) => disk_object.clone(), // TODO: Consider releasing the slot lock when performing I/O. // Elevates the chances of creating garbage. - None => manager.ensure_lower_tier_stored(page_handle, *eviction_policy)?, + None => self + .manager + .ensure_lower_tier_stored(page_handle, *eviction_policy) + .map_err(Box::new)?, }; *slot = PageSlot::NonResident { metadata: *metadata, backing, }; - manager.evicted(candidate); - manager + self.manager.evicted(candidate); + self.manager .metrics() .evicted(ObjectType::Page, EvictionDirection::MemoryToDisk, PAGE_SIZE as u64); bytes_freed += PAGE_SIZE as u64; - if manager.resident_usage().accounted_bytes() <= target_usage { + if self.manager.resident_usage().accounted_bytes() <= target_usage { break; } } @@ -446,7 +477,7 @@ impl PageSet { if policy == self.eviction_policy { return; } - let old = std::mem::replace(&mut self.storage, PageStorage::Tiered(TieredPages::default())); + let old = std::mem::replace(&mut self.storage, PageStorage::Tiered(TieredPages::new(&self.manager))); self.storage = match old { PageStorage::Resident(resident) => { assert!(matches!(policy, EvictionPolicy::Memory | EvictionPolicy::Disk)); @@ -508,7 +539,11 @@ impl PageSet { pages: Pages::default(), permits: smallvec::SmallVec::new(), }), - EvictionPolicy::Memory | EvictionPolicy::Disk => PageStorage::Tiered(TieredPages::default()), + EvictionPolicy::Memory | EvictionPolicy::Disk => { + let tiered = TieredPages::new(&manager); + manager.register_eviction_source(&(tiered.eviction.clone() as Arc)); + PageStorage::Tiered(tiered) + } }; Self { eviction_policy, @@ -544,6 +579,8 @@ impl PageSet { pages, &mut self.storage.tiered_mut().slots, ); + self.storage.tiered_mut().reset_eviction(); + self.storage.tiered_mut().non_full_pages = self .storage .tiered() @@ -590,9 +627,7 @@ impl PageSet { return Ok(None); }; tiered - .with_page_retry(&self.manager, |fault| { - self.manager.get_with_fault(slot, self.eviction_policy, fault) - }) + .with_page_retry(|fault| self.manager.get_with_fault(slot, self.eviction_policy, fault)) .map(|page| page.map(PageRef::Tiered)) } @@ -626,7 +661,7 @@ impl PageSet { if slot.is_absent() { Ok(None) } else { - let mut page = tiered.with_page_retry(&self.manager, |fault| { + let mut page = tiered.with_page_retry(|fault| { self.manager .get_mut_with_fault(slot, self.eviction_policy, self.fixed_row_size, fault) })?; @@ -663,7 +698,7 @@ impl PageSet { let Some(slot) = tiered.slots.get(index.idx()) else { return Err(PageError::MissingPage(index)); }; - tiered.with_page_retry(&self.manager, |fault| { + tiered.with_page_retry(|fault| { self.manager .get_mut_with_fault(slot, self.eviction_policy, self.fixed_row_size, fault) })? @@ -837,9 +872,10 @@ impl PageSet { fn allocate_new_page(&mut self, fixed_row_size: Size) -> Result { let free_page = self.storage.tiered_mut().free_page_slots.pop_first(); let page_index = free_page.map(Ok).unwrap_or_else(|| self.can_allocate_new_page())?; - let allocation = self.storage.tiered().with_eviction_retry(&self.manager, || { - self.manager.allocate(fixed_row_size, self.eviction_policy) - }); + let allocation = self + .storage + .tiered() + .with_eviction_retry(|| self.manager.allocate(fixed_row_size, self.eviction_policy)); let slot = allocation.inspect_err(|_| { if free_page.is_some() { self.storage.tiered_mut().free_page_slots.insert(page_index); @@ -869,14 +905,20 @@ impl PageSet { /// absent. unsafe fn install_page_slot(&mut self, index: PageIndex, slot: PageSlotHandle) -> PageHandle { let page = slot.page().expect("page must be resident"); + let storage = self.storage.tiered_mut(); - let idx = index.idx(); - if idx == self.storage.tiered().slots.len() { - self.storage.tiered_mut().slots.push(slot); - } else { - assert!(self.storage.tiered().slots[idx].is_absent()); - self.storage.tiered_mut().free_page_slots.remove(&index); - self.storage.tiered_mut().slots[idx] = slot; + { + let mut weak_slots = storage.eviction.slots.lock(); + let idx = index.idx(); + if idx == storage.slots.len() { + weak_slots.push(slot.downgrade()); + storage.slots.push(slot); + } else { + assert!(storage.slots[idx].is_absent()); + storage.free_page_slots.remove(&index); + weak_slots[idx] = slot.downgrade(); + storage.slots[idx] = slot; + } } self.storage @@ -1118,11 +1160,8 @@ impl PageSet { /// as before when it returns. /// /// Returns the number of bytes freed, as a multiple of [PAGE_SIZE]. - pub fn trim(&self) -> Result { - match &self.storage { - PageStorage::Resident(_) => Ok(0), - PageStorage::Tiered(tiered) => tiered.trim(&self.manager), - } + pub fn trim(&self) -> Result { + self.manager.trim_all() } /// Attempt to evict pages from this page set until `target_usage` is met. @@ -1132,11 +1171,8 @@ impl PageSet { /// as before when it returns. /// /// Returns the number of bytes freed, as a multiple of [PAGE_SIZE]. - pub fn evict(&self, target_usage: u64) -> Result { - match &self.storage { - PageStorage::Resident(_) => Ok(0), - PageStorage::Tiered(tiered) => tiered.evict(&self.manager, target_usage), - } + pub fn evict(&self, target_usage: u64) -> Result { + self.manager.evict_all(target_usage) } fn reserve_page(&self, fixed_row_size: Size) -> Result { @@ -1147,7 +1183,7 @@ impl PageSet { }; match &self.storage { PageStorage::Resident(_) => reserve(), - PageStorage::Tiered(tiered) => tiered.with_eviction_retry(&self.manager, reserve), + PageStorage::Tiered(tiered) => tiered.with_eviction_retry(reserve), } } } @@ -1539,11 +1575,223 @@ impl<'a> PageAllocator<'a> { mod tests { use super::*; use crate::{ - indexes::PAGE_SIZE, + indexes::{PageOffset, PAGE_SIZE}, page_pool::PagePool, - tiered::{metrics::CacheTier, ByteBudget, ByteBudgetConfig, ResidentObjects, TieredStorage}, + tiered::{metrics::CacheTier, BlobError, ByteBudget, ByteBudgetConfig, ResidentObjects, TieredStorage}, + var_len::NullVarLenVisitor, }; + fn shared_page_and_blob_cache(page_count: u64) -> (Arc, BlobSet) { + // Bound the shared resident cache while leaving backing storage unlimited. + let limit = page_count * PAGE_SIZE as u64; + let budget = ByteBudget::new(ByteBudgetConfig { + tier: CacheTier::Memory, + low_water_bytes: 0, + soft_limit_bytes: limit, + hard_limit_bytes: limit, + }) + .unwrap(); + let resident = Arc::new(ResidentObjects::new(budget)); + let storage = Arc::new(TieredStorage::new_for_test()); + let blobs = BlobSet::new(resident.clone(), storage.clone()); + let manager = Arc::new(PageManager::new(resident, PagePool::new_for_test(), storage)); + + (manager, blobs) + } + + fn write_fixed_row(pages: &mut PageSet, blobs: &mut BlobSet, index: PageIndex, value: u64) -> PageOffset { + pages + .with_page_mut(index, Size(8), |page| { + // SAFETY: These pages contain only eight-byte integers, with no + // variable-length fields for the visitor to inspect. + unsafe { + page.insert_row( + &value.to_le_bytes(), + &[] as &[&[u8]], + &NullVarLenVisitor, + blobs, + EvictionPolicy::Memory, + ) + } + .unwrap() + }) + .unwrap() + } + + fn assert_fixed_row(pages: &PageSet, index: PageIndex, offset: PageOffset, value: u64) { + let pin = pages.get_page(index).unwrap().unwrap(); + assert_eq!(pin.read().get_row_data(offset, Size(8)), &value.to_le_bytes()); + } + + #[test] + fn global_eviction_reclaims_pages_from_another_page_set() { + let (manager, mut blobs) = shared_page_and_blob_cache(1); + let mut committed = PageSet::new(manager.clone(), EvictionPolicy::Memory, Size(8)); + let mut transaction = PageSet::new(manager, EvictionPolicy::Memory, Size(8)); + let first = committed.allocate_new_page(Size(8)).unwrap(); + let first_offset = write_fixed_row(&mut committed, &mut blobs, first, 17); + + // Distinct sets share a manager but own their slots independently. An + // empty transaction must be able to evict a committed set's page. + let second = transaction.allocate_new_page(Size(8)).unwrap(); + let second_offset = write_fixed_row(&mut transaction, &mut blobs, second, 29); + assert!(!committed.storage.tiered().slots[first.idx()].is_resident()); + assert!(transaction.storage.tiered().slots[second.idx()].is_resident()); + + // Read faults must reclaim the other set too, preserving both rows and + // each set's page indices across repeated changes of residency. + assert_fixed_row(&committed, first, first_offset, 17); + assert!(!transaction.storage.tiered().slots[second.idx()].is_resident()); + assert_fixed_row(&transaction, second, second_offset, 29); + assert!(!committed.storage.tiered().slots[first.idx()].is_resident()); + + drop(transaction); + assert_fixed_row(&committed, first, first_offset, 17); + } + + #[test] + fn global_eviction_allows_pages_and_blobs_to_reclaim_each_other() { + let (manager, blobs) = shared_page_and_blob_cache(1); + let mut pages = PageSet::new(manager, EvictionPolicy::Memory, Size(8)); + let bytes = vec![b'x'; PAGE_SIZE]; + let hash = blobs.insert(EvictionPolicy::Memory, &bytes).unwrap().hash(); + + // The blob fills the entire budget. Allocating a page can only succeed + // by evicting that blob, even though the requesting page set is empty. + let index = pages.allocate_new_page(Size(8)).unwrap(); + assert_eq!(blobs.resident_bytes_used_by_blobs(), 0); + assert!(pages.storage.tiered().slots[index.idx()].is_resident()); + + // Faulting the blob back in must perform the opposite eviction. Then + // fault the page again to cover both allocation and read-fault retries. + assert_eq!(&*blobs.get(hash).unwrap(), bytes.as_slice()); + assert!(!pages.storage.tiered().slots[index.idx()].is_resident()); + drop(pages.get_page(index).unwrap().unwrap()); + assert!(pages.storage.tiered().slots[index.idx()].is_resident()); + assert_eq!(blobs.resident_bytes_used_by_blobs(), 0); + assert_eq!(blobs.resident_usage().accounted_bytes(), PAGE_SIZE as u64); + } + + #[test] + fn global_eviction_preserves_a_pinned_page_when_a_blob_cannot_fit() { + let (manager, blobs) = shared_page_and_blob_cache(1); + let mut pages = PageSet::new(manager, EvictionPolicy::Memory, Size(8)); + let index = pages.allocate_new_page(Size(8)).unwrap(); + let pin = pages.get_page(index).unwrap().unwrap(); + + // A live page handle must block eviction triggered by a different type + // of object. Failed allocation must not publish a blob catalog entry. + assert!(matches!( + blobs.insert(EvictionPolicy::Memory, b"new blob"), + Err(BlobError::MemoryLimitExceeded(_)) + )); + assert_eq!(blobs.num_blobs(), 0); + assert!(pages.storage.tiered().slots[index.idx()].is_resident()); + assert_eq!(blobs.resident_usage().accounted_bytes(), PAGE_SIZE as u64); + + drop(pin); + drop(blobs.insert(EvictionPolicy::Memory, b"new blob").unwrap()); + assert!(!pages.storage.tiered().slots[index.idx()].is_resident()); + } + + #[test] + fn global_eviction_registers_pages_created_by_policy_conversion() { + let (manager, blobs) = shared_page_and_blob_cache(1); + let mut pages = PageSet::new(manager, EvictionPolicy::Never, Size(8)); + pages.set_contents([Some(Page::new(Size(8)))], Size(8)); + + // Never pages cannot spill. Conversion creates their eviction source, + // which must be registered even though PageSet::new was called earlier. + assert!(matches!( + blobs.insert(EvictionPolicy::Memory, b"new blob"), + Err(BlobError::MemoryLimitExceeded(_)) + )); + pages.apply_eviction_policy(EvictionPolicy::Memory); + drop(blobs.insert(EvictionPolicy::Memory, b"new blob").unwrap()); + assert!(!pages.storage.tiered().slots[0].is_resident()); + + drop(pages.get_page(PageIndex(0)).unwrap().unwrap()); + assert!(pages.storage.tiered().slots[0].is_resident()); + assert_eq!(blobs.resident_bytes_used_by_blobs(), 0); + } + + #[test] + fn global_eviction_registers_restored_pages_without_changing_their_indices() { + let (manager, blobs) = shared_page_and_blob_cache(1); + let mut pages = PageSet::new(manager, EvictionPolicy::Memory, Size(8)); + + // Restore bypasses ordinary allocation and can contain absent slots. + // Its eviction registry must include the live page at its original index. + pages.set_contents([None, Some(Page::new(Size(8)))], Size(8)); + let bytes = vec![b'x'; PAGE_SIZE]; + drop(blobs.insert(EvictionPolicy::Memory, &bytes).unwrap()); + assert!(!pages.storage.tiered().slots[1].is_resident()); + assert!(pages.get_page(PageIndex(0)).unwrap().is_none()); + + drop(pages.get_page(PageIndex(1)).unwrap().unwrap()); + assert!(pages.storage.tiered().slots[1].is_resident()); + assert_eq!(blobs.resident_bytes_used_by_blobs(), 0); + assert!(pages.get_page(PageIndex(0)).unwrap().is_none()); + } + + #[test] + fn global_eviction_skips_a_write_locked_page_during_blob_allocation() { + use std::{sync::mpsc, thread, time::Duration}; + + // Run the allocation on a worker so regressing to a blocking slot lock + // fails with a timeout instead of hanging the whole test suite. + let (completed, completion) = mpsc::sync_channel(1); + let worker = thread::spawn(move || { + let (manager, blobs) = shared_page_and_blob_cache(2); + let mut pages = PageSet::new(manager, EvictionPolicy::Memory, Size(8)); + let locked = pages.allocate_new_page(Size(8)).unwrap(); + let victim = pages.allocate_new_page(Size(8)).unwrap(); + + // Blob writes normally happen while mutating a page. The sweep must + // skip that locked slot, find the other page, and make forward progress. + pages + .with_page_mut(locked, Size(8), |_| { + drop(blobs.insert(EvictionPolicy::Memory, b"new blob").unwrap()); + }) + .unwrap(); + assert!(pages.storage.tiered().slots[locked.idx()].is_resident()); + assert!(!pages.storage.tiered().slots[victim.idx()].is_resident()); + completed.send(()).unwrap(); + }); + + completion + .recv_timeout(Duration::from_secs(10)) + .expect("global eviction blocked on the allocating thread's page lock"); + worker.join().unwrap(); + } + + #[test] + fn global_eviction_does_not_keep_dropped_page_sets_alive() { + let (manager, blobs) = shared_page_and_blob_cache(1); + let weak_manager = Arc::downgrade(&manager); + + // Repeatedly discard transaction-like sets. Their weak registrations + // must not retain resident allocations or prevent subsequent eviction. + for _ in 0..3 { + let mut temporary = PageSet::new(manager.clone(), EvictionPolicy::Memory, Size(8)); + temporary.allocate_new_page(Size(8)).unwrap(); + drop(temporary); + assert_eq!(blobs.resident_usage().accounted_bytes(), 0); + } + let mut live = PageSet::new(manager.clone(), EvictionPolicy::Memory, Size(8)); + let index = live.allocate_new_page(Size(8)).unwrap(); + drop(blobs.insert(EvictionPolicy::Memory, b"new blob").unwrap()); + assert!(!live.storage.tiered().slots[index.idx()].is_resident()); + + drop(live); + drop(manager); + drop(blobs); + assert!( + weak_manager.upgrade().is_none(), + "eviction sources formed an ownership cycle" + ); + } + fn bounded_page_set() -> PageSet { let budget = ByteBudget::new(ByteBudgetConfig { tier: CacheTier::Memory, From f5d2f124e22e4a49bfc30fef11534d007b024d9c Mon Sep 17 00:00:00 2001 From: Kim Altintop Date: Thu, 26 Nov 2026 14:44:32 +0100 Subject: [PATCH 5/5] Integrate global LRU from #6649 --- .../locking_tx_datastore/committed_state.rs | 7 +- crates/table/src/bflatn_to.rs | 20 +- crates/table/src/table.rs | 35 +- crates/table/src/tiered/blob_set.rs | 9 +- crates/table/src/tiered/budget.rs | 2 +- crates/table/src/tiered/error.rs | 6 + crates/table/src/tiered/mem.rs | 88 +++- crates/table/src/tiered/page_manager.rs | 168 +++++-- crates/table/src/tiered/page_set.rs | 443 +++++++++--------- crates/table/src/tiered/storage.rs | 18 - 10 files changed, 479 insertions(+), 317 deletions(-) diff --git a/crates/datastore/src/locking_tx_datastore/committed_state.rs b/crates/datastore/src/locking_tx_datastore/committed_state.rs index cc1b07e03ef..20b1b7073c0 100644 --- a/crates/datastore/src/locking_tx_datastore/committed_state.rs +++ b/crates/datastore/src/locking_tx_datastore/committed_state.rs @@ -458,12 +458,7 @@ impl CommittedState { /// Returns an iterator doing a full table scan on `table_id`. pub(super) fn table_scan<'a>(&'a self, table_id: TableId) -> Option> { - Some( - self.get_table(table_id)? - .scan_rows(self.storage.blobs()) - .with_read_eviction(self) - .err_into(), - ) + Some(self.get_table(table_id)?.scan_rows(self.storage.blobs()).err_into()) } /// Returns an index for `table_id` on `cols`, if any. diff --git a/crates/table/src/bflatn_to.rs b/crates/table/src/bflatn_to.rs index d3c300facdb..9a7ab55e327 100644 --- a/crates/table/src/bflatn_to.rs +++ b/crates/table/src/bflatn_to.rs @@ -6,7 +6,7 @@ use crate::{ blob_store::BlobHash, indexes::PageIndex, table::TableError, - tiered::{BlobError, BlobSet, EvictionPolicy, PageError, PageSet, ReservedPage}, + tiered::{BlobError, BlobSet, EvictionPolicy, PageError, PageHandle, PageSet, ReservedPage}, }; use super::{ @@ -47,6 +47,8 @@ pub enum Error { /// Writes `row` typed at `ty` to `pages` /// using `blob_store` as needed to write large blobs. /// +/// Keep the returned page pin until the inserted row has its own handle. +/// /// Panics if `val` is not of type `ty`. /// /// # Safety @@ -63,7 +65,7 @@ pub unsafe fn write_row_to_pages_bsatn( mut bytes: &[u8], squashed_offset: SquashedOffset, eviction_policy: EvictionPolicy, -) -> Result<(RowPointer, BlobNumBytes), Error> { +) -> Result<(RowPointer, BlobNumBytes, Option), Error> { let val = ty.product().deserialize(bsatn::Deserializer::new(&mut bytes))?; unsafe { write_row_to_pages(pages, None, visitor, blobs, ty, &val, squashed_offset, eviction_policy) } } @@ -71,6 +73,8 @@ pub unsafe fn write_row_to_pages_bsatn( /// Writes `row` typed at `ty` to `pages` /// using `blob_store` as needed to write large blobs. /// +/// Keep the returned page pin until the inserted row has its own handle. +/// /// Panics if `val` is not of type `ty`. /// /// # Safety @@ -89,7 +93,7 @@ pub unsafe fn write_row_to_pages( val: &ProductValue, squashed_offset: SquashedOffset, eviction_policy: EvictionPolicy, -) -> Result<(RowPointer, BlobNumBytes), Error> { +) -> Result<(RowPointer, BlobNumBytes, Option), Error> { let num_granules = if ty.layout().fixed { // Fast-path: The row type doesn't contain var-len members, // so 0 granules are needed. @@ -118,10 +122,12 @@ pub unsafe fn write_row_to_pages( ) } })? { - (page, Ok((offset, blob_inserted))) => { - Ok((RowPointer::new(false, page, offset, squashed_offset), blob_inserted)) - } - (_, Err(e)) => Err(e), + (page, Ok((offset, blob_inserted)), pin) => Ok(( + RowPointer::new(false, page, offset, squashed_offset), + blob_inserted, + pin, + )), + (_, Err(e), _) => Err(e), } } diff --git a/crates/table/src/table.rs b/crates/table/src/table.rs index c3d64e5d408..ffaaf6176e2 100644 --- a/crates/table/src/table.rs +++ b/crates/table/src/table.rs @@ -836,7 +836,7 @@ impl Table { let source_page = source_page.read(); let source = source_page.get_row_data(source_offset, fixed_row_size); let squashed_offset = self.squashed_offset; - let (page_index, fixed_offset) = + let (page_index, fixed_offset, page_pin) = self.inner .pages .with_page_to_insert_row(fixed_row_size, 0, reservation, |page| { @@ -852,6 +852,7 @@ impl Table { // SAFETY: We just inserted `ptr`, so it must be present. let row_ref = unsafe { self.inner.get_row_ref_unchecked(blobs, squashed_offset, ptr) }?; + drop(page_pin); Ok((row_ref, BlobNumBytes::default())) } @@ -869,7 +870,7 @@ impl Table { ) -> Result<(RowRef<'a>, BlobNumBytes), Error> { // SAFETY: `self.pages` is known to be specialized for `self.row_layout`, // as `self.pages` was constructed from `self.row_layout` in `Table::new`. - let (ptr, blob_bytes) = unsafe { + let (ptr, blob_bytes, page_pin) = unsafe { write_row_to_pages( &mut self.inner.pages, reservation, @@ -882,7 +883,7 @@ impl Table { ) }?; - self.finish_physical_insert(blobs, ptr, blob_bytes) + self.finish_physical_insert(blobs, ptr, blob_bytes, page_pin) } /// Physically insert a `row`, encoded in BSATN, into this table, @@ -905,7 +906,8 @@ impl Table { row: &[u8], ) -> Result<(RowRef<'a>, BlobNumBytes), Error> { // Got a static layout? => Use fast-path insertion. - let (ptr, blob_bytes) = if let Some((static_layout, static_validator)) = self.inner.static_layout.as_ref() { + let static_layout = self.inner.static_layout.as_ref(); + let (ptr, blob_bytes, page_pin) = if let Some((static_layout, static_validator)) = static_layout { // Before inserting, validate the row, ensuring type safety. // SAFETY: The `static_validator` was derived from the same row layout as the static layout. unsafe { validate_bsatn(static_validator, static_layout, row) }.map_err(Error::Decode)?; @@ -929,8 +931,12 @@ impl Table { }) .map_err(Error::Pages)?; match res { - (page, Ok(offset)) => (RowPointer::new(false, page, offset, squashed_offset), 0usize.into()), - (_, Err(e)) => return Err(e), + (page, Ok(offset), pin) => ( + RowPointer::new(false, page, offset, squashed_offset), + 0usize.into(), + pin, + ), + (_, Err(e), _) => return Err(e), } } else { // SAFETY: `self.pages` is known to be specialized for `self.row_layout`, @@ -948,7 +954,7 @@ impl Table { }? }; - self.finish_physical_insert(blobs, ptr, blob_bytes) + self.finish_physical_insert(blobs, ptr, blob_bytes, page_pin) } /// Finish a physical insertion without leaving an untracked row if pinning @@ -961,6 +967,7 @@ impl Table { blobs: &BlobSet, ptr: RowPointer, blob_bytes: BlobNumBytes, + page_pin: Option, ) -> Result<(RowRef<'a>, BlobNumBytes), Error> { let page = self .inner @@ -968,6 +975,8 @@ impl Table { .get_page(ptr.page_index()) .expect("just written page is resident") .expect("just written page exists"); + // The page reference now owns the pin that protects subsequent blob faults. + drop(page_pin); let row_blobs = if self.inner.row_layout.layout().fixed { Ok(BlobReadSet::empty()) } else { @@ -1765,7 +1774,7 @@ impl Table { // fail after serialization succeeds, and that must also run cleanup. // // SAFETY: The page set, visitor, and row layout belong to this table. - let (temp_ptr, _) = unsafe { + let (temp_ptr, _, page_pin) = unsafe { write_row_to_pages( &mut self.inner.pages, None, @@ -1791,6 +1800,7 @@ impl Table { PageRef::Tiered(page_handle) => Some(page_handle), }; let temp_pin = PinnedRow::new(temp_ptr, temp_page, BlobReadSet::empty()); + drop(page_pin); // SAFETY: The temporary row is live and its page is pinned. // Keep blob-pinning errors in `result` so they also run cleanup below. @@ -3526,6 +3536,8 @@ impl PreparedEvictionPolicy { } } + /// Apply a prepared cache-policy change while holding the database write lock. + /// Other users of the shared storage must not request eviction concurrently. pub fn apply(self, table: &mut Table, blobs: &BlobSet) { assert_eq!(table.eviction_policy, self.old_policy); if self.policy == self.old_policy { @@ -3555,9 +3567,10 @@ impl PreparedEvictionPolicy { } } - // Release memory pins before conversion unwraps shared frames. Keep - // disk preparation protection until permanent backing pins are - // installed. + // The caller holds the database write lock, excluding other transactions + // and trimming. Conversion performs no faults or allocations that request + // eviction, so preparation pins can be released before unwrapping frames. + // Keep disk preparation protection until permanent backing pins are installed. let disk_pins = self .pins .filter(|pins| matches!(pins, PreparedEvictionPolicyPins::Disk { .. })); diff --git a/crates/table/src/tiered/blob_set.rs b/crates/table/src/tiered/blob_set.rs index 77cbadf153d..6b005e500a4 100644 --- a/crates/table/src/tiered/blob_set.rs +++ b/crates/table/src/tiered/blob_set.rs @@ -64,8 +64,9 @@ impl BlobSet { fn from_inner(inner: BlobSetInner) -> Self { let inner = Arc::new(inner); - let source: Arc = inner.clone(); - inner.resident.register_eviction_source(&source); + inner + .resident + .register_eviction_source(EvictionSource::Blobs(Arc::downgrade(&inner))); Self { inner } } @@ -953,8 +954,8 @@ impl IntoIterator for BlobMap { } } -impl EvictionSource for BlobSetInner { - fn evict(&self, target_usage: u64) -> Result { +impl BlobSetInner { + pub(super) fn evict(&self, target_usage: u64) -> Result { let mut bytes_freed = 0; if self.resident.usage().accounted_bytes() <= target_usage { diff --git a/crates/table/src/tiered/budget.rs b/crates/table/src/tiered/budget.rs index 04731fb123e..5d657cd6f6a 100644 --- a/crates/table/src/tiered/budget.rs +++ b/crates/table/src/tiered/budget.rs @@ -201,7 +201,7 @@ pub struct ByteBudgetStateView(Arc>); impl ByteBudgetStateView { pub fn usage(&self) -> ByteBudgetUsage { - let accounted_bytes = self.0.lock().unwrap().accounted_bytes; + let accounted_bytes = self.0.lock().accounted_bytes; ByteBudgetUsage { accounted_bytes } } } diff --git a/crates/table/src/tiered/error.rs b/crates/table/src/tiered/error.rs index 8fc710d5dcf..d202508cc86 100644 --- a/crates/table/src/tiered/error.rs +++ b/crates/table/src/tiered/error.rs @@ -47,6 +47,12 @@ impl From for PageError { } } +impl From for PageError { + fn from(error: EvictionError) -> Self { + Self::Eviction(Box::new(error)) + } +} + impl PageError { pub fn is_transient(&self) -> bool { match self { diff --git a/crates/table/src/tiered/mem.rs b/crates/table/src/tiered/mem.rs index 06c48df80d8..87e03551dd3 100644 --- a/crates/table/src/tiered/mem.rs +++ b/crates/table/src/tiered/mem.rs @@ -19,7 +19,12 @@ use crate::{ page::Page, page_pool::PagePool, tiered::{ - budget::ByteBudgetStateView, error::EvictionError, map::BlobHashWrapper, metrics::EvictionDirection, + blob_set::BlobSetInner, + budget::ByteBudgetStateView, + error::EvictionError, + map::BlobHashWrapper, + metrics::EvictionDirection, + page_manager::{PageEviction, WeakPageSlotHandle}, BudgetExceeded, BudgetPermit, ByteBudget, ByteBudgetUsage, }, }; @@ -171,7 +176,7 @@ pub struct ResidentObjects { budget: ByteBudget, access_epoch: AtomicU64, page_id: AtomicU64, - pages: Mutex>>, + pages: Mutex>, blobs: Mutex>>, eviction: Arc, } @@ -307,23 +312,33 @@ impl ResidentObjects { Ok(self.reserve_page_with_permit(permit, page)) } - pub(super) fn redeem_page(&self, ReservedPage { id, frame }: ReservedPage) -> Arc { + pub(super) fn redeem_page( + &self, + ReservedPage { id, frame }: ReservedPage, + slot: WeakPageSlotHandle, + ) -> Arc { let frame = Arc::new(frame); - assert!(self.pages.lock().insert(id, Arc::downgrade(&frame)).is_none()); + let entry = RegisteredPage { + frame: Arc::downgrade(&frame), + slot, + }; + assert!(self.pages.lock().insert(id, entry).is_none()); + frame } pub(super) fn evictable_pages(&self, candidates: &mut Vec) { { let mut pages = self.pages.lock(); - pages.retain(|&id, weak| { - let Some(frame) = weak.upgrade() else { + pages.retain(|&id, entry| { + let Some(frame) = entry.frame.upgrade() else { return false; }; if Arc::strong_count(&frame) <= 2 { candidates.push(PageEvictionCandidate { id, + slot: entry.slot.clone(), access: frame.access(), }); } @@ -338,7 +353,7 @@ impl ResidentObjects { pub(super) fn evict_page(&self, victim: PageEvictionCandidate) { let mut pages = self.pages.lock(); if let hash_map::Entry::Occupied(entry) = pages.entry(victim.id) - && entry.get().strong_count() == 0 + && entry.get().frame.strong_count() == 0 { entry.remove(); } @@ -352,10 +367,15 @@ impl ResidentObjects { self.budget.usage() } - pub(super) fn register_page_unchecked(&self, pool: PagePool, page: Box) -> Arc { + pub(super) fn register_page_unchecked( + &self, + pool: PagePool, + page: Box, + slot: WeakPageSlotHandle, + ) -> Arc { let permit = self.restored_page_permit(); let reservation = self.reserve_page_with_permit(permit, PooledPage::new(page, pool)); - self.redeem_page(reservation) + self.redeem_page(reservation, slot) } pub(super) fn detach_page(&self, frame: Arc) -> (Box, BudgetPermit) { @@ -409,7 +429,7 @@ impl ResidentObjects { result } - pub(super) fn register_eviction_source(&self, source: &Arc) { + pub(super) fn register_eviction_source(&self, source: EvictionSource) { self.eviction.register(source); } } @@ -436,9 +456,16 @@ pub struct BlobEvictionCandidate { access: AccessSnapshot, } +#[derive(Debug)] +struct RegisteredPage { + frame: Weak, + slot: WeakPageSlotHandle, +} + #[derive(Debug)] pub struct PageEvictionCandidate { pub id: PageId, + pub(super) slot: WeakPageSlotHandle, access: AccessSnapshot, } @@ -565,27 +592,52 @@ impl fmt::Debug for PooledPage { } } -pub(super) trait EvictionSource: fmt::Debug + Send + Sync { - fn evict(&self, target: u64) -> Result; +/// [Eviction] coordinates eviction across eviction sources. +/// +/// Each page and blob set is registered with [Eviction] as a source. Eviction +/// sources are [Weak] references, so de-registration is not necessary (e.g. on +/// transaction commit / abort). +#[derive(Clone, Debug)] +pub(super) enum EvictionSource { + Pages(Weak), + Blobs(Weak), +} + +impl EvictionSource { + fn is_alive(&self) -> bool { + match self { + Self::Pages(source) => source.strong_count() > 0, + Self::Blobs(source) => source.strong_count() > 0, + } + } + + fn evict(&self, target: u64) -> Result { + // Upgrade outside the registry lock. A source dropped since discovery + // has no remaining catalog for the coordinator to evict. + match self { + Self::Pages(source) => source.upgrade().map_or(Ok(0), |source| source.evict(target)), + Self::Blobs(source) => source.upgrade().map_or(Ok(0), |source| source.evict(target)), + } + } } #[derive(Debug)] struct Eviction { usage: ByteBudgetStateView, - sources: Mutex>>, + sources: Mutex>, } impl Eviction { - fn register(&self, source: &Arc) { - self.sources.lock().push(Arc::downgrade(source)) + fn register(&self, source: EvictionSource) { + self.sources.lock().push(source) } fn evict(&self, target: u64) -> Result { let mut bytes_freed = 0; let sources = { let mut sources = self.sources.lock(); - sources.retain(|s| s.strong_count() > 0); - sources.iter().filter_map(Weak::upgrade).collect::>() + sources.retain(EvictionSource::is_alive); + sources.clone() }; for source in sources { @@ -604,6 +656,6 @@ impl MemoryUsage for Eviction { fn heap_usage(&self) -> usize { // Don't count the budget, as it is already accounted for by // [ResidentObjects]. - self.sources.lock().capacity() + size_of::>() + self.sources.lock().capacity() * size_of::() } } diff --git a/crates/table/src/tiered/page_manager.rs b/crates/table/src/tiered/page_manager.rs index ab64601abb8..ded59b72eea 100644 --- a/crates/table/src/tiered/page_manager.rs +++ b/crates/table/src/tiered/page_manager.rs @@ -1,4 +1,4 @@ -use super::metrics::{with_fault, CacheTier, Fault, Metrics, ObjectType}; +use super::metrics::{with_fault, CacheTier, EvictionDirection, Fault, Metrics, ObjectType}; use std::{ ops::{Deref, DerefMut}, sync::{Arc, Weak}, @@ -21,8 +21,7 @@ use crate::{ map::PageHash, mem::{self, EvictionSource, PageEvictionCandidate, PageFrame, PageId, PooledPage}, storage::{DiskObject, TieredStorage}, - BudgetExceeded, BudgetPermit, ByteBudget, ByteBudgetConfig, ByteBudgetUsage, EvictionPolicy, ObjectStoreError, - ResidentObjects, + BudgetExceeded, BudgetPermit, ByteBudget, ByteBudgetConfig, ByteBudgetUsage, EvictionPolicy, ResidentObjects, }, }; @@ -155,11 +154,6 @@ impl PageSlotHandle { self.slot.lock().page_id() } - pub(super) fn try_page_id(&self) -> Option { - let guard = self.slot.try_lock()?; - guard.page_id() - } - pub(super) fn downgrade(&self) -> WeakPageSlotHandle { WeakPageSlotHandle { slot: Arc::downgrade(&self.slot), @@ -211,7 +205,7 @@ impl MemoryUsage for PageSlotHandle { } } -#[derive(Debug)] +#[derive(Clone, Debug)] pub(crate) struct WeakPageSlotHandle { slot: Weak>, } @@ -220,10 +214,6 @@ impl WeakPageSlotHandle { pub fn upgrade(&self) -> Option { self.slot.upgrade().map(|slot| PageSlotHandle { slot }) } - - pub fn strong_count(&self) -> usize { - self.slot.strong_count() - } } /// State of a page. @@ -472,6 +462,14 @@ pub struct PageManager { resident_cache: Pool, resident: Arc, pub(crate) storage: Arc, + eviction: Arc, +} + +#[derive(Debug)] +pub(super) struct PageEviction { + resident: Arc, + storage: Arc, + candidates: Mutex>, } impl PageManager { @@ -555,9 +553,17 @@ impl PageManager { // Bound this cache by the configured page-pool capacity. let resident_cache = Pool::new(usize::try_from(pool.capacity()).expect("existing pool capacity fits the address space")); + let eviction = Arc::new(PageEviction { + resident: resident.clone(), + storage: storage.clone(), + candidates: Mutex::new(Vec::new()), + }); + resident.register_eviction_source(EvictionSource::Pages(Arc::downgrade(&eviction))); + Self { pool, resident_cache, + eviction, resident, storage, } @@ -588,7 +594,7 @@ impl PageManager { eviction_policy: EvictionPolicy, fault: &mut Option>, ) -> Result, PageError> { - self.may_fault(&mut slot.lock_ref(), eviction_policy, fault) + self.may_fault(slot, &mut slot.lock_ref(), eviction_policy, fault) } /// Get a [PageFrameWriteGuard] for the page at the given `slot`. @@ -617,7 +623,7 @@ impl PageManager { ) -> Result { let mut slot_guard = slot.lock_owned(); let handle = self - .may_fault(&mut slot_guard, eviction_policy, fault)? + .may_fault(slot, &mut slot_guard, eviction_policy, fault)? .expect("page requested for mutation to be present"); // SAFETY: We just faulted the page, so the handle contains the resident // frame we want to lock. @@ -626,6 +632,7 @@ impl PageManager { fn may_fault<'a>( &'a self, + slot: &PageSlotHandle, slot_guard: &mut PageSlot, eviction_policy: EvictionPolicy, fault: &mut Option>, @@ -658,7 +665,7 @@ impl PageManager { Ok::<_, PageError>(page) })?; - let frame = self.resident.redeem_page(reservation); + let frame = self.resident.redeem_page(reservation, slot.downgrade()); let handle = PageHandle { frame }; *slot_guard = PageSlot::Resident { handle: handle.clone(), @@ -713,24 +720,34 @@ impl PageManager { /// /// The page must have been created by [Self::reserve()] on the same page /// manager instance. - pub fn redeem( + pub fn redeem(&self, reservation: ReservedPage, eviction_policy: EvictionPolicy) -> PageSlotHandle { + self.redeem_pinned(reservation, eviction_policy).0 + } + + /// Keep a pin until the caller has installed the slot and acquired its own handle. + pub(super) fn redeem_pinned( &self, ReservedPage { inner, metadata }: ReservedPage, eviction_policy: EvictionPolicy, - ) -> PageSlotHandle { + ) -> (PageSlotHandle, PageHandle) { let slot = Arc::new(Mutex::new(PageSlot::Absent)); - { + let handle = { let mut slot_guard = slot.lock(); - let frame = self.resident.redeem_page(inner); + let owner = WeakPageSlotHandle { + slot: Arc::downgrade(&slot), + }; + let frame = self.resident.redeem_page(inner, owner); + let handle = PageHandle { frame }; *slot_guard = PageSlot::Resident { - handle: PageHandle { frame }, + handle: handle.clone(), metadata, backing: None, eviction_policy, }; - } + handle + }; - PageSlotHandle { slot } + (PageSlotHandle { slot }, handle) } pub fn resident_usage(&self) -> ByteBudgetUsage { @@ -758,8 +775,11 @@ impl PageManager { if let Some(page) = page { let metadata = page.metadata(fixed_row_size); - let frame = self.resident.register_page_unchecked(self.pool.clone(), page); let mut slot_guard = slot.lock(); + let owner = WeakPageSlotHandle { + slot: Arc::downgrade(&slot), + }; + let frame = self.resident.register_page_unchecked(self.pool.clone(), page, owner); *slot_guard = PageSlot::Resident { handle: PageHandle { frame }, metadata, @@ -774,37 +794,105 @@ impl PageManager { } } - pub(super) fn evictable(&self, candidates: &mut Vec) { - self.resident.evictable_pages(candidates); + pub(super) fn trim_all(&self) -> Result { + self.resident.trim() } - pub(super) fn evicted(&self, victim: PageEvictionCandidate) { - self.resident.evict_page(victim); + pub(super) fn evict_all(&self, target_usage: u64) -> Result { + self.resident.evict(target_usage) } - pub(super) fn ensure_lower_tier_stored( + pub(super) fn with_page_retry<'a, T>( &self, - page: &PageHandle, - eviction_policy: EvictionPolicy, - ) -> Result { - self.storage.write(page.into(), eviction_policy) + mut f: impl FnMut(&mut Option>) -> Result, + ) -> Result { + with_fault(|fault| self.with_eviction_retry(|| f(fault))) } - pub(super) fn trim_all(&self) -> Result { - self.resident.trim() + pub(super) fn with_eviction_retry(&self, mut f: impl FnMut() -> Result) -> Result { + match f() { + Err(PageError::MemoryLimitExceeded(_)) => { + self.trim_all()?; + f() + } + res => res, + } } +} - pub(super) fn evict_all(&self, target_usage: u64) -> Result { - self.resident.evict(target_usage) - } +impl PageEviction { + pub(super) fn evict(&self, target_usage: u64) -> Result { + let mut bytes_freed = 0; + + if self.resident.usage().accounted_bytes() <= target_usage { + return Ok(bytes_freed); + } + + let mut candidates = self.candidates.lock(); + if self.resident.usage().accounted_bytes() <= target_usage { + return Ok(bytes_freed); + } + // Faults register frames under the slot lock, so release the registry + // before locking any candidate slot. + self.resident.evictable_pages(&mut candidates); + for candidate in candidates.drain(..) { + let Some(slot) = candidate.slot.upgrade() else { + continue; + }; + // A caller can request eviction while working on another page. + let Some(mut slot) = slot.try_lock_ref() else { + continue; + }; + let PageSlot::Resident { + handle: page_handle, + metadata, + backing, + eviction_policy, + } = &*slot + else { + continue; + }; + + if *eviction_policy == EvictionPolicy::Never { + continue; + } + + // The candidate may have been pinned or replaced since discovery. + if page_handle.page_id() != candidate.id || page_handle.is_pinned() { + continue; + } + + let backing = match backing { + Some(disk_object) => disk_object.clone(), + // TODO: Consider releasing the slot lock when performing I/O. + // Elevates the chances of creating garbage. + None => self + .storage + .write(page_handle.into(), *eviction_policy) + .map_err(Box::new)?, + }; + *slot = PageSlot::NonResident { + metadata: *metadata, + backing, + }; + self.resident.evict_page(candidate); + self.resident + .metrics() + .evicted(ObjectType::Page, EvictionDirection::MemoryToDisk, PAGE_SIZE as u64); + bytes_freed += PAGE_SIZE as u64; + + if self.resident.usage().accounted_bytes() <= target_usage { + break; + } + } - pub(super) fn register_eviction_source(&self, source: &Arc) { - self.resident.register_eviction_source(source); + Ok(bytes_freed) } } impl MemoryUsage for PageManager { fn heap_usage(&self) -> usize { self.resident_cache.heap_usage() + + self.eviction.candidates.lock().capacity() * size_of::() } } diff --git a/crates/table/src/tiered/page_set.rs b/crates/table/src/tiered/page_set.rs index 01c12913349..b0b92852051 100644 --- a/crates/table/src/tiered/page_set.rs +++ b/crates/table/src/tiered/page_set.rs @@ -1,27 +1,24 @@ -use super::metrics::{with_fault, CacheTier, EvictionDirection, Fault, ObjectType}; +use super::metrics::{CacheTier, ObjectType}; use std::{ collections::{btree_map, BTreeMap, BTreeSet}, convert::Infallible, sync::Arc, }; -use parking_lot::Mutex; -use spacetimedb_data_structures::map::IntMap; use spacetimedb_lib::ProductValue; use spacetimedb_memory_usage::MemoryUsage; use spacetimedb_sats::layout::Size; use crate::{ - indexes::{PageIndex, RowPointer, PAGE_SIZE}, + indexes::{PageIndex, RowPointer}, page::{Page, PageCapacity}, pages::Pages, table::{BlobNumBytes, PreparedInsert, Table, TableError}, tiered::{ blob_set::BlobHandle, - mem::{EvictionSource, PageEvictionCandidate, PageId}, - page_manager::{PageHandle, PageManager, PageSlot, PageSlotHandle, ReservedPage, WeakPageSlotHandle}, + page_manager::{PageFrameWriteGuard, PageHandle, PageManager, PageSlot, PageSlotHandle, ReservedPage}, storage::DiskObject, - BlobSet, BudgetPermit, EvictionError, EvictionPolicy, Object, ObjectStoreError, PageError, PageRead, PageRef, + BlobSet, BudgetPermit, EvictionError, EvictionPolicy, ObjectStoreError, PageError, PageRead, PageRef, }, var_len::VarLenMembers, }; @@ -51,21 +48,13 @@ enum PageStorage { } /// Evictable pages retain shared slots and frames so readers can pin their contents. -#[derive(Debug)] +#[derive(Debug, Default)] struct TieredPages { slots: Vec, - eviction: Arc, free_page_slots: BTreeSet, non_full_pages: BTreeSet<(usize, PageIndex)>, } -#[derive(Debug)] -struct PageSetEviction { - manager: Arc, - slots: Mutex>, - evictable: Mutex, -} - impl PageStorage { #[inline] fn resident(&self) -> Option<&ResidentPages> { @@ -126,7 +115,7 @@ impl ResidentPages { let mut tiered = TieredPages { free_page_slots: std::mem::take(&mut self.pages.free_page_slots), non_full_pages: std::mem::take(&mut self.pages.non_full_pages), - ..TieredPages::new(manager) + ..TieredPages::default() }; // Move each allocation together with its existing memory charge. Keep // empty slots too: compacting the slots would invalidate row pointers. @@ -194,21 +183,6 @@ impl ResidentPages { } impl TieredPages { - fn new(manager: &Arc) -> Self { - let eviction = Arc::new(PageSetEviction { - manager: manager.clone(), - slots: <_>::default(), - evictable: <_>::default(), - }); - manager.register_eviction_source(&(eviction.clone() as Arc)); - Self { - eviction, - slots: <_>::default(), - free_page_slots: <_>::default(), - non_full_pages: <_>::default(), - } - } - fn into_resident(self, manager: &PageManager, fixed_row_size: Size) -> ResidentPages { let slot_count = self.slots.len(); let mut pages = Vec::with_capacity(slot_count); @@ -226,29 +200,6 @@ impl TieredPages { } } - fn with_page_retry<'a, T>( - &self, - mut f: impl FnMut(&mut Option>) -> Result, - ) -> Result { - with_fault(|fault| self.with_eviction_retry(|| f(fault))) - } - - fn with_eviction_retry(&self, mut f: impl FnMut() -> Result) -> Result { - match f() { - Err(PageError::MemoryLimitExceeded(_)) => { - self.eviction.trim().map_err(Box::new)?; - f() - } - res => res, - } - } - - fn reset_eviction(&mut self) { - let mut weak_slots = self.eviction.slots.lock(); - weak_slots.clear(); - weak_slots.extend(self.slots.iter().map(PageSlotHandle::downgrade)); - } - fn apply_eviction_policy(&self, policy: EvictionPolicy) { assert!(matches!(policy, EvictionPolicy::Memory | EvictionPolicy::Disk)); @@ -275,90 +226,6 @@ impl TieredPages { } } -impl PageSetEviction { - fn trim(&self) -> Result { - self.manager.trim_all() - } -} - -impl EvictionSource for PageSetEviction { - fn evict(&self, target_usage: u64) -> Result { - let mut bytes_freed = 0; - - if self.manager.resident_usage().accounted_bytes() <= target_usage { - return Ok(bytes_freed); - } - - let mut guard = self.evictable.lock(); - let (candidates, slots) = &mut *guard; - - self.manager.evictable(candidates); - if candidates.is_empty() { - return Ok(bytes_freed); - } - - let mut weak_slots = self.slots.lock(); - weak_slots.retain(|s| s.strong_count() > 0); - slots.clear(); - slots.extend(weak_slots.iter().enumerate().filter_map(|(idx, weak_handle)| { - let handle = weak_handle.upgrade()?; - let page_id = handle.try_page_id()?; - Some((page_id, PageIndex(idx as _))) - })); - - for candidate in candidates.drain(..) { - let Some(page_index) = slots.remove(&candidate.id) else { - continue; - }; - let Some(slot) = weak_slots[page_index.idx()].upgrade() else { - continue; - }; - let Some(mut slot) = slot.try_lock_ref() else { - continue; - }; - let PageSlot::Resident { - handle: page_handle, - metadata, - backing, - eviction_policy, - } = &*slot - else { - continue; - }; - - // The candidate may have been pinned or replaced since discovery. - if page_handle.page_id() != candidate.id || page_handle.is_pinned() { - continue; - } - - let backing = match backing { - Some(disk_object) => disk_object.clone(), - // TODO: Consider releasing the slot lock when performing I/O. - // Elevates the chances of creating garbage. - None => self - .manager - .ensure_lower_tier_stored(page_handle, *eviction_policy) - .map_err(Box::new)?, - }; - *slot = PageSlot::NonResident { - metadata: *metadata, - backing, - }; - self.manager.evicted(candidate); - self.manager - .metrics() - .evicted(ObjectType::Page, EvictionDirection::MemoryToDisk, PAGE_SIZE as u64); - bytes_freed += PAGE_SIZE as u64; - - if self.manager.resident_usage().accounted_bytes() <= target_usage { - break; - } - } - - Ok(bytes_freed) - } -} - pub enum PageInfo<'a> { Resident(&'a Page), Tiered(&'a PageSlotHandle), @@ -407,7 +274,6 @@ impl PageInfo<'_> { } } } -type EvictionScratch = (Box>, Box>); /// Created by [PageSet::ensure_disk], ownership of this handle guarantees that /// a page is either pinned to memory, or present and pinned to the local @@ -472,12 +338,13 @@ impl PageSet { } /// Change who owns the existing page allocations, without copying their contents. + /// The caller must hold the database write lock to exclude concurrent eviction. /// All page handles must be released first. Disk-table pages must already be loaded. pub(crate) fn apply_eviction_policy(&mut self, policy: EvictionPolicy) { if policy == self.eviction_policy { return; } - let old = std::mem::replace(&mut self.storage, PageStorage::Tiered(TieredPages::new(&self.manager))); + let old = std::mem::replace(&mut self.storage, PageStorage::Tiered(TieredPages::default())); self.storage = match old { PageStorage::Resident(resident) => { assert!(matches!(policy, EvictionPolicy::Memory | EvictionPolicy::Disk)); @@ -539,11 +406,7 @@ impl PageSet { pages: Pages::default(), permits: smallvec::SmallVec::new(), }), - EvictionPolicy::Memory | EvictionPolicy::Disk => { - let tiered = TieredPages::new(&manager); - manager.register_eviction_source(&(tiered.eviction.clone() as Arc)); - PageStorage::Tiered(tiered) - } + EvictionPolicy::Memory | EvictionPolicy::Disk => PageStorage::Tiered(TieredPages::default()), }; Self { eviction_policy, @@ -579,7 +442,6 @@ impl PageSet { pages, &mut self.storage.tiered_mut().slots, ); - self.storage.tiered_mut().reset_eviction(); self.storage.tiered_mut().non_full_pages = self .storage @@ -626,7 +488,7 @@ impl PageSet { let Some(slot) = tiered.slots.get(index.idx()) else { return Ok(None); }; - tiered + self.manager .with_page_retry(|fault| self.manager.get_with_fault(slot, self.eviction_policy, fault)) .map(|page| page.map(PageRef::Tiered)) } @@ -661,7 +523,7 @@ impl PageSet { if slot.is_absent() { Ok(None) } else { - let mut page = tiered.with_page_retry(|fault| { + let mut page = self.manager.with_page_retry(|fault| { self.manager .get_mut_with_fault(slot, self.eviction_policy, self.fixed_row_size, fault) })?; @@ -693,12 +555,23 @@ impl PageSet { return Ok(resident.pages.with_page_mut(index, fixed_row_size, f)); } + self.with_tiered_page_mut(index, fixed_row_size, f) + .map(|(result, _)| result) + } + + // Retain the write guard so inserts can transfer its pin before unlocking. + fn with_tiered_page_mut( + &mut self, + index: PageIndex, + fixed_row_size: Size, + f: impl FnOnce(&mut Page) -> T, + ) -> Result<(T, PageFrameWriteGuard), PageError> { let mut page = { let tiered = self.storage.tiered(); let Some(slot) = tiered.slots.get(index.idx()) else { return Err(PageError::MissingPage(index)); }; - tiered.with_page_retry(|fault| { + self.manager.with_page_retry(|fault| { self.manager .get_mut_with_fault(slot, self.eviction_policy, self.fixed_row_size, fault) })? @@ -715,7 +588,8 @@ impl PageSet { .non_full_pages .insert((page.available_var_len_granules(), index)); } - Ok(ret) + + Ok((ret, page)) } /// Run a closure over a mutable [Page]. @@ -730,7 +604,8 @@ impl PageSet { /// [PageSet], and the closure is run against exactly this page. /// /// The fullness status of the page is updated, but the page is not freed if - /// it ends up being empty after `f` returns. + /// it ends up being empty after `f` returns. Keep the returned pin until the + /// inserted row has acquired its own page handle. #[inline(always)] pub fn with_page_to_insert_row( &mut self, @@ -738,16 +613,18 @@ impl PageSet { num_var_len_granules: usize, reservation: Option<(PageIndex, ReservedPage)>, f: impl FnOnce(&mut Page) -> T, - ) -> Result<(PageIndex, T), PageError> { + ) -> Result<(PageIndex, T, Option), PageError> { if let Some(resident) = self.storage.resident_mut() { - return resident.with_page_to_insert_row( + let (index, result) = resident.with_page_to_insert_row( &self.manager, fixed_row_size, self.memory_limit_exempt, num_var_len_granules, reservation, f, - ); + )?; + + return Ok((index, result, None)); } self.with_tiered_page_to_insert_row(fixed_row_size, num_var_len_granules, reservation, f) } @@ -758,15 +635,17 @@ impl PageSet { num_var_len_granules: usize, reservation: Option<(PageIndex, ReservedPage)>, f: impl FnOnce(&mut Page) -> T, - ) -> Result<(PageIndex, T), PageError> { - let index = match reservation { + ) -> Result<(PageIndex, T, Option), PageError> { + // Keep a newly published reservation pinned through the mutation. Blob + // allocations inside `f` can trigger the shared eviction coordinator. + let (index, _allocation_pin) = match reservation { None => self.find_page_with_space_for_row(fixed_row_size, num_var_len_granules)?, - Some((index, page)) => { - self.register(index, page); - index - } + Some((index, page)) => (index, Some(self.register(index, page))), }; - self.with_page_mut(index, fixed_row_size, f).map(|res| (index, res)) + let (result, page) = self.with_tiered_page_mut(index, fixed_row_size, f)?; + // Transfer the write guard's pin before releasing either write lock. + + Ok((index, result, Some(page.into_page_handle()))) } /// Free the row that is pointed to by `row_ptr`, @@ -842,7 +721,7 @@ impl PageSet { &mut self, fixed_row_size: Size, num_var_len_granules: usize, - ) -> Result { + ) -> Result<(PageIndex, Option), PageError> { if let Some((_, page_idx)) = self .storage .tiered() @@ -855,10 +734,11 @@ impl PageSet { .expect("page in `self.storage.tiered().non_full_pages` to be present in `self.pages`") }) { - return Ok(page_idx); + return Ok((page_idx, None)); } - self.allocate_new_page(fixed_row_size) + self.allocate_new_page_pinned(fixed_row_size) + .map(|(index, pin)| (index, Some(pin))) } /// Allocates one additional page, @@ -869,14 +749,15 @@ impl PageSet { /// /// The new page is initially empty, but is not added to the non-full set. /// Callers should call [`Pages::record_page_non_full`] after operating on the new page. - fn allocate_new_page(&mut self, fixed_row_size: Size) -> Result { + fn allocate_new_page_pinned(&mut self, fixed_row_size: Size) -> Result<(PageIndex, PageHandle), PageError> { let free_page = self.storage.tiered_mut().free_page_slots.pop_first(); let page_index = free_page.map(Ok).unwrap_or_else(|| self.can_allocate_new_page())?; - let allocation = self - .storage - .tiered() - .with_eviction_retry(|| self.manager.allocate(fixed_row_size, self.eviction_policy)); - let slot = allocation.inspect_err(|_| { + let allocation = self.manager.with_eviction_retry(|| { + let reservation = self.manager.reserve(fixed_row_size)?; + + Ok(self.manager.redeem_pinned(reservation, self.eviction_policy)) + }); + let (slot, pin) = allocation.inspect_err(|_| { if free_page.is_some() { self.storage.tiered_mut().free_page_slots.insert(page_index); } @@ -884,41 +765,40 @@ impl PageSet { // SAFETY: The page is resident and the index is from free slots or // fresh. - unsafe { self.install_page_slot(page_index, slot) }; + let pin = unsafe { self.install_page_slot(page_index, slot, pin) }; - Ok(page_index) + Ok((page_index, pin)) + } + + #[cfg(test)] + fn allocate_new_page(&mut self, fixed_row_size: Size) -> Result { + self.allocate_new_page_pinned(fixed_row_size).map(|(index, _)| index) } /// Register a [ReservedPage] with this [PageSet]. /// /// Pages are reserved during [Self::prepare_commit]. - fn register(&mut self, index: PageIndex, reservation: ReservedPage) { - let slot = self.manager.redeem(reservation, self.eviction_policy); + fn register(&mut self, index: PageIndex, reservation: ReservedPage) -> PageHandle { + let (slot, pin) = self.manager.redeem_pinned(reservation, self.eviction_policy); // SAFETY: The page is resident. The index was obtained during commit // planning. - unsafe { self.install_page_slot(index, slot) }; + unsafe { self.install_page_slot(index, slot, pin) } } /// SAFETY: - /// - The [PageSlotHandle] must contain a resident page. + /// - The [PageSlotHandle] must contain the resident page held by `page`. /// - If there already exists an entry at `index`, the existing slot must be /// absent. - unsafe fn install_page_slot(&mut self, index: PageIndex, slot: PageSlotHandle) -> PageHandle { - let page = slot.page().expect("page must be resident"); + unsafe fn install_page_slot(&mut self, index: PageIndex, slot: PageSlotHandle, page: PageHandle) -> PageHandle { + assert_eq!(slot.page_id(), Some(page.page_id())); let storage = self.storage.tiered_mut(); - - { - let mut weak_slots = storage.eviction.slots.lock(); - let idx = index.idx(); - if idx == storage.slots.len() { - weak_slots.push(slot.downgrade()); - storage.slots.push(slot); - } else { - assert!(storage.slots[idx].is_absent()); - storage.free_page_slots.remove(&index); - weak_slots[idx] = slot.downgrade(); - storage.slots[idx] = slot; - } + let idx = index.idx(); + if idx == storage.slots.len() { + storage.slots.push(slot); + } else { + assert!(storage.slots[idx].is_absent()); + storage.free_page_slots.remove(&index); + storage.slots[idx] = slot; } self.storage @@ -1152,25 +1032,14 @@ impl PageSet { }) } - /// Attempt to evict pages from this page set until the budget's low - /// watermark is met. - /// - /// Eviction will stop once the usage is at or below the low watermark. - /// The method may not free any pages, so the budget usage may be the same - /// as before when it returns. - /// - /// Returns the number of bytes freed, as a multiple of [PAGE_SIZE]. + /// Evict pages and blobs sharing this manager until the budget's low watermark + /// is met, or no eligible objects remain. Returns the total number of bytes freed. pub fn trim(&self) -> Result { self.manager.trim_all() } - /// Attempt to evict pages from this page set until `target_usage` is met. - /// - /// Eviction will stop once the usage is at or below the low watermark. - /// The method may not free any pages, so the budget usage may be the same - /// as before when it returns. - /// - /// Returns the number of bytes freed, as a multiple of [PAGE_SIZE]. + /// Evict pages and blobs sharing this manager until `target_usage` is met, + /// or no eligible objects remain. Returns the total number of bytes freed. pub fn evict(&self, target_usage: u64) -> Result { self.manager.evict_all(target_usage) } @@ -1183,7 +1052,7 @@ impl PageSet { }; match &self.storage { PageStorage::Resident(_) => reserve(), - PageStorage::Tiered(tiered) => tiered.with_eviction_retry(reserve), + PageStorage::Tiered(_) => self.manager.with_eviction_retry(reserve), } } } @@ -1330,16 +1199,19 @@ impl PreparedCommit { // and the commitlog. if !schema.is_event { let reservation = self.reserved.remove(&page_index).map(|page| (page_index, page)); + let allocated = reservation.is_some(); let row_ref = table .insert_prepared(blobs, &row, reservation) .map(|(_, row_ref)| row_ref) .expect("failed to insert during transaction commit"); let (page, _) = row_ref.page_and_offset(); let inserted_index = row_ref.pointer().page_index(); - if let btree_map::Entry::Vacant(entry) = pinned.entry(inserted_index) + // A deleted page's index can now name a different frame. + // Replace its old pin so subsequent inserts cannot evict the new page. + if (allocated || !pinned.contains_key(&inserted_index)) && let Some(pin) = page.pin() { - entry.insert(pin); + pinned.insert(inserted_index, pin); } assert_eq!(inserted_index, page_index, "planned and actual placement differ"); @@ -1623,6 +1495,153 @@ mod tests { assert_eq!(pin.read().get_row_data(offset, Size(8)), &value.to_le_bytes()); } + proptest::proptest! { + #![proptest_config(proptest::test_runner::Config::with_cases(64))] + + #[test] + fn global_page_eviction_matches_lru_two_across_tables( + accesses in proptest::collection::vec(0u8..4, 0..48), + restored in proptest::prelude::any::(), + disk_policy in proptest::prelude::any::(), + empty_slots in 0u8..3, + ) { + let (manager, _blobs) = shared_page_and_blob_cache(4); + let policy = if disk_policy { EvictionPolicy::Disk } else { EvictionPolicy::Memory }; + let mut tables = Vec::new(); + let mut history = [(0u64, 0u64); 4]; + + // Allocation and snapshot recovery must both publish owning slots. + // Holes in restored tables must not affect victim lookup. + for table_index in 0u8..4 { + let mut pages = PageSet::new(manager.clone(), policy, Size(8)); + let index = if restored { + pages.set_contents( + (0..empty_slots).map(|_| None).chain([Some(Page::new(Size(8)))]), + Size(8), + ); + PageIndex(u64::from(empty_slots)) + } else { + pages.allocate_new_page(Size(8)).unwrap() + }; + history[usize::from(table_index)].1 = u64::from(table_index) + 1; + tables.push((pages, index)); + } + + // Model access history independently of the resident registry. + let mut epoch = 5u64; + for table_index in accesses { + let index = usize::from(table_index); + let (pages, page_index) = &tables[index]; + drop(pages.get_page(*page_index).unwrap().unwrap()); + history[index] = (history[index].1, epoch); + epoch += 1; + } + let victim = (0u8..4).min_by_key(|&index| { + let (previous, last) = history[usize::from(index)]; + (previous != 0, if previous == 0 { last } else { previous }, last) + }).unwrap(); + + // The coordinator must choose one global victim, regardless of + // the order in which tables would have registered their sources. + let freed = manager.evict_all(3 * PAGE_SIZE as u64).unwrap(); + proptest::prop_assert_eq!(freed, PAGE_SIZE as u64); + for (index, (pages, page_index)) in tables.iter().enumerate() { + proptest::prop_assert_eq!( + pages.storage.tiered().slots[page_index.idx()].is_resident(), + index != usize::from(victim), + ); + } + } + } + + #[test] + fn allocation_evicts_the_colder_page_from_a_later_table() { + let limit = 2 * PAGE_SIZE as u64; + let budget = ByteBudget::new(ByteBudgetConfig { + tier: CacheTier::Memory, + low_water_bytes: PAGE_SIZE as u64, + soft_limit_bytes: limit, + hard_limit_bytes: limit, + }) + .unwrap(); + let manager = Arc::new(PageManager::new( + Arc::new(ResidentObjects::new(budget)), + PagePool::new_for_test(), + Arc::new(TieredStorage::new_for_test()), + )); + let mut hot = PageSet::new(manager.clone(), EvictionPolicy::Memory, Size(8)); + let mut cold = PageSet::new(manager.clone(), EvictionPolicy::Memory, Size(8)); + let mut writer = PageSet::new(manager, EvictionPolicy::Memory, Size(8)); + let hot_index = hot.allocate_new_page(Size(8)).unwrap(); + let cold_index = cold.allocate_new_page(Size(8)).unwrap(); + + // The earlier table has the hotter page. A table-ordered sweep would + // reclaim it before considering the unread page in the later table. + drop(hot.get_page(hot_index).unwrap().unwrap()); + let writer_index = writer.allocate_new_page(Size(8)).unwrap(); + assert!(hot.storage.tiered().slots[hot_index.idx()].is_resident()); + assert!(!cold.storage.tiered().slots[cold_index.idx()].is_resident()); + assert!(writer.storage.tiered().slots[writer_index.idx()].is_resident()); + } + + #[test] + fn insertion_pin_protects_the_row_after_releasing_the_write_lock() { + for reserved in [false, true] { + let (manager, mut blobs) = shared_page_and_blob_cache(1); + let mut pages = PageSet::new(manager.clone(), EvictionPolicy::Memory, Size(8)); + let reservation = reserved.then(|| (PageIndex(0), manager.reserve(Size(8)).unwrap())); + let (index, offset, pin) = pages + .with_page_to_insert_row(Size(8), 0, reservation, |page| { + // SAFETY: This page and visitor both describe eight-byte integers. + unsafe { + page.insert_row( + &73u64.to_le_bytes(), + &[] as &[&[u8]], + &NullVarLenVisitor, + &mut blobs, + EvictionPolicy::Memory, + ) + } + .unwrap() + }) + .unwrap(); + + // Simulate another set trimming between the write and creation of + // the RowRef. The returned pin must bridge that unlocked interval. + assert!(pin.is_some()); + assert_eq!(manager.evict_all(0).unwrap(), 0); + let row_pin = pages.get_page(index).unwrap().unwrap(); + drop(pin); + assert_eq!(manager.evict_all(0).unwrap(), 0); + drop(row_pin); + + assert_eq!(manager.evict_all(0).unwrap(), PAGE_SIZE as u64); + assert_fixed_row(&pages, index, offset, 73); + } + } + + #[test] + fn allocation_pin_protects_a_page_before_its_slot_is_installed() { + let (manager, _blobs) = shared_page_and_blob_cache(1); + let mut pages = PageSet::new(manager.clone(), EvictionPolicy::Memory, Size(8)); + let reservation = manager.reserve(Size(8)).unwrap(); + let (slot, pin) = manager.redeem_pinned(reservation, EvictionPolicy::Memory); + + // Simulate another set requesting eviction after publication but before + // installation. The allocation pin must keep the page resident. + assert_eq!(manager.evict_all(0).unwrap(), 0); + assert!(slot.is_resident()); + // SAFETY: The pin identifies this slot's resident frame, and the index is fresh. + let pin = unsafe { pages.install_page_slot(PageIndex(0), slot, pin) }; + assert_eq!(manager.evict_all(0).unwrap(), 0); + + // Installation must not leave behind permanent protection. + drop(pin); + assert_eq!(manager.evict_all(0).unwrap(), PAGE_SIZE as u64); + assert!(!pages.storage.tiered().slots[0].is_resident()); + assert!(pages.get_page(PageIndex(0)).unwrap().is_some()); + } + #[test] fn global_eviction_reclaims_pages_from_another_page_set() { let (manager, mut blobs) = shared_page_and_blob_cache(1); @@ -1700,8 +1719,8 @@ mod tests { let mut pages = PageSet::new(manager, EvictionPolicy::Never, Size(8)); pages.set_contents([Some(Page::new(Size(8)))], Size(8)); - // Never pages cannot spill. Conversion creates their eviction source, - // which must be registered even though PageSet::new was called earlier. + // Never pages cannot spill. Conversion must register their slots even + // though the page set was originally created with directly owned pages. assert!(matches!( blobs.insert(EvictionPolicy::Memory, b"new blob"), Err(BlobError::MemoryLimitExceeded(_)) diff --git a/crates/table/src/tiered/storage.rs b/crates/table/src/tiered/storage.rs index 76b59f7142a..0d057cf9a94 100644 --- a/crates/table/src/tiered/storage.rs +++ b/crates/table/src/tiered/storage.rs @@ -865,24 +865,6 @@ fn object_from_trusted_bytes(key: ObjectKey, bytes: ObjectBytes) -> Object { Object { inner } } -pub(crate) fn write_atomically(data: &[u8], path: &Path, fsync: Fsync) -> io::Result<()> { - let dir = path.parent().expect("output path must have a parent"); - - let mut tmp = NamedTempFile::new_in(dir)?; - tmp.write_all(data)?; - if let Fsync::Require = fsync { - tmp.as_file().sync_data()?; - } - tmp.persist(path)?; - - if let Fsync::Require = fsync { - #[cfg(not(target_os = "windows"))] - fs::File::open(dir)?.sync_all()?; - } - - Ok(()) -} - /// Helper struct for promoting an object from remote to local storage. struct Promotion<'a> { key: ObjectKey,