diff --git a/crates/bench/benches/special.rs b/crates/bench/benches/special.rs index f66379b9582..f09a564f344 100644 --- a/crates/bench/benches/special.rs +++ b/crates/bench/benches/special.rs @@ -142,7 +142,7 @@ fn serialize_benchmarks< Arc::new(table_schema), spacetimedb_table::indexes::SquashedOffset::COMMITTED_STATE, PageManager::new_for_test().into(), - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, ); let blob_store = spacetimedb_table::tiered::BlobSet::new_for_test(); diff --git a/crates/datastore/src/locking_tx_datastore/committed_state.rs b/crates/datastore/src/locking_tx_datastore/committed_state.rs index 68253411d65..26c1852ec14 100644 --- a/crates/datastore/src/locking_tx_datastore/committed_state.rs +++ b/crates/datastore/src/locking_tx_datastore/committed_state.rs @@ -20,10 +20,11 @@ use crate::{ IterByColRangeTx, }, system_tables::{ - system_tables, StColumnRow, StConstraintRow, StIndexRow, StSequenceRow, StTableRow, SystemTable, ST_CLIENT_ID, - ST_CLIENT_IDX, ST_COLUMN_ID, ST_COLUMN_IDX, ST_CONSTRAINT_ID, ST_CONSTRAINT_IDX, ST_INDEX_ID, ST_INDEX_IDX, - ST_MODULE_ID, ST_MODULE_IDX, ST_ROW_LEVEL_SECURITY_ID, ST_ROW_LEVEL_SECURITY_IDX, ST_SCHEDULED_ID, - ST_SCHEDULED_IDX, ST_SEQUENCE_ID, ST_SEQUENCE_IDX, ST_TABLE_ID, ST_TABLE_IDX, ST_VAR_ID, ST_VAR_IDX, + system_tables, StColumnRow, StConstraintRow, StIndexRow, StSequenceRow, StTableRow, + SystemTable, ST_CLIENT_ID, ST_CLIENT_IDX, ST_COLUMN_ID, ST_COLUMN_IDX, ST_CONSTRAINT_ID, + ST_CONSTRAINT_IDX, ST_INDEX_ID, ST_INDEX_IDX, ST_MODULE_ID, ST_MODULE_IDX, + ST_ROW_LEVEL_SECURITY_ID, ST_ROW_LEVEL_SECURITY_IDX, ST_SCHEDULED_ID, ST_SCHEDULED_IDX, + ST_SEQUENCE_ID, ST_SEQUENCE_IDX, ST_TABLE_ID, ST_TABLE_IDX, ST_VAR_ID, ST_VAR_IDX, ST_VIEW_ARG_ID, ST_VIEW_ARG_IDX, }, traits::{EphemeralTables, TxData}, @@ -31,12 +32,14 @@ use crate::{ use crate::{ locking_tx_datastore::ViewCallInfo, system_tables::{ - ST_COLUMN_ACCESSOR_ID, ST_COLUMN_ACCESSOR_IDX, ST_CONNECTION_CREDENTIALS_ID, ST_CONNECTION_CREDENTIALS_IDX, - ST_ENV_ID, ST_ENV_IDX, ST_EVENT_TABLE_ID, ST_EVENT_TABLE_IDX, ST_INBOUND_MSG_ID, ST_INBOUND_MSG_IDX, - ST_INBOUND_STREAM_ID, ST_INBOUND_STREAM_IDX, ST_INDEX_ACCESSOR_ID, ST_INDEX_ACCESSOR_IDX, ST_OUTBOUND_MSG_ID, - ST_OUTBOUND_MSG_IDX, ST_OUTBOUND_STREAM_ID, ST_OUTBOUND_STREAM_IDX, ST_OUTBOX_ID, ST_OUTBOX_IDX, - ST_TABLE_ACCESSOR_ID, ST_TABLE_ACCESSOR_IDX, ST_VIEW_COLUMN_ID, ST_VIEW_COLUMN_IDX, ST_VIEW_ID, ST_VIEW_IDX, - ST_VIEW_PARAM_ID, ST_VIEW_PARAM_IDX, ST_VIEW_SUB_ID, ST_VIEW_SUB_IDX, + ST_COLUMN_ACCESSOR_ID, ST_COLUMN_ACCESSOR_IDX, ST_CONNECTION_CREDENTIALS_ID, + ST_CONNECTION_CREDENTIALS_IDX, ST_ENV_ID, ST_ENV_IDX, ST_EVENT_TABLE_ID, + ST_EVENT_TABLE_IDX, ST_INBOUND_MSG_ID, ST_INBOUND_MSG_IDX, ST_INBOUND_STREAM_ID, + ST_INBOUND_STREAM_IDX, ST_INDEX_ACCESSOR_ID, ST_INDEX_ACCESSOR_IDX, ST_OUTBOUND_MSG_ID, + ST_OUTBOUND_MSG_IDX, ST_OUTBOUND_STREAM_ID, ST_OUTBOUND_STREAM_IDX, ST_OUTBOX_ID, + ST_OUTBOX_IDX, ST_TABLE_ACCESSOR_ID, ST_TABLE_ACCESSOR_IDX, ST_VIEW_COLUMN_ID, + ST_VIEW_COLUMN_IDX, ST_VIEW_ID, ST_VIEW_IDX, ST_VIEW_PARAM_ID, ST_VIEW_PARAM_IDX, + ST_VIEW_SUB_ID, ST_VIEW_SUB_IDX, }, }; use anyhow::anyhow; @@ -56,7 +59,10 @@ use spacetimedb_schema::{ }; use spacetimedb_table::{ indexes::{RowPointer, SquashedOffset}, - table::{self, PreparedBlobRelease, PreparedEvictionPolicy, ReadEviction, RowRef, Table, TableAndIndex}, + table::{ + self, PreparedBlobRelease, PreparedEvictionPolicy, ReadEviction, RowRef, Table, + TableAndIndex, + }, tiered::{BlobHandle, BlobSet, EvictionPolicy, PreparedCommit, TieredDatabaseStorage}, }; use std::{collections::BTreeMap, iter}; @@ -115,7 +121,10 @@ impl CommittedState { } /// Returns the views that perform a full scan of this table - pub(super) fn views_for_table_scan(&self, table_id: &TableId) -> impl Iterator + use<'_> { + pub(super) fn views_for_table_scan( + &self, + table_id: &TableId, + ) -> impl Iterator + use<'_> { self.read_sets.views_for_table_scan(table_id) } @@ -285,16 +294,19 @@ impl CommittedState { // and therefore has performance implications and must not be disabled. #[cfg(feature = "metrics")] let with_label_values = |table_id: TableId, table_name: &str| { - DB_METRICS - .rdb_num_table_rows - .with_label_values(&database_identity, &table_id.0, table_name) + DB_METRICS.rdb_num_table_rows.with_label_values( + &database_identity, + &table_id.0, + table_name, + ) }; let schemas = system_tables().map(Arc::new); let ref_schemas = schemas.each_ref().map(|s| &**s); // Insert the table row into st_tables, creating st_tables if it's missing. - let (st_tables, blob_store) = self.get_table_and_blob_store_or_create(ST_TABLE_ID, &schemas[ST_TABLE_IDX]); + let (st_tables, blob_store) = + self.get_table_and_blob_store_or_create(ST_TABLE_ID, &schemas[ST_TABLE_IDX]); // Insert the table row into `st_tables` for all system tables for schema in ref_schemas { let table_id = schema.table_id; @@ -315,7 +327,8 @@ impl CommittedState { } // Insert the columns into `st_columns` - let (st_columns, blob_store) = self.get_table_and_blob_store_or_create(ST_COLUMN_ID, &schemas[ST_COLUMN_IDX]); + let (st_columns, blob_store) = + self.get_table_and_blob_store_or_create(ST_COLUMN_ID, &schemas[ST_COLUMN_IDX]); for col in ref_schemas.iter().flat_map(|x| x.columns()).cloned() { let row = StColumnRow { table_id: col.table_id, @@ -352,7 +365,8 @@ impl CommittedState { } // Insert the indexes into `st_indexes` - let (st_indexes, blob_store) = self.get_table_and_blob_store_or_create(ST_INDEX_ID, &schemas[ST_INDEX_IDX]); + let (st_indexes, blob_store) = + self.get_table_and_blob_store_or_create(ST_INDEX_ID, &schemas[ST_INDEX_IDX]); for index in ref_schemas.iter().flat_map(|x| &x.indexes) { let row: StIndexRow = index.clone().into(); @@ -374,7 +388,10 @@ impl CommittedState { self.create_table(ST_SCHEDULED_ID, schemas[ST_SCHEDULED_IDX].clone()); - self.create_table(ST_ROW_LEVEL_SECURITY_ID, schemas[ST_ROW_LEVEL_SECURITY_IDX].clone()); + self.create_table( + ST_ROW_LEVEL_SECURITY_ID, + schemas[ST_ROW_LEVEL_SECURITY_IDX].clone(), + ); self.create_table( ST_CONNECTION_CREDENTIALS_ID, schemas[ST_CONNECTION_CREDENTIALS_IDX].clone(), @@ -389,14 +406,23 @@ impl CommittedState { self.create_table(ST_EVENT_TABLE_ID, schemas[ST_EVENT_TABLE_IDX].clone()); self.create_table(ST_TABLE_ACCESSOR_ID, schemas[ST_TABLE_ACCESSOR_IDX].clone()); self.create_table(ST_INDEX_ACCESSOR_ID, schemas[ST_INDEX_ACCESSOR_IDX].clone()); - self.create_table(ST_COLUMN_ACCESSOR_ID, schemas[ST_COLUMN_ACCESSOR_IDX].clone()); + self.create_table( + ST_COLUMN_ACCESSOR_ID, + schemas[ST_COLUMN_ACCESSOR_IDX].clone(), + ); self.create_table(ST_ENV_ID, schemas[ST_ENV_IDX].clone()); - self.create_table(ST_OUTBOUND_STREAM_ID, schemas[ST_OUTBOUND_STREAM_IDX].clone()); + self.create_table( + ST_OUTBOUND_STREAM_ID, + schemas[ST_OUTBOUND_STREAM_IDX].clone(), + ); self.create_table(ST_OUTBOUND_MSG_ID, schemas[ST_OUTBOUND_MSG_IDX].clone()); self.create_table(ST_INBOUND_STREAM_ID, schemas[ST_INBOUND_STREAM_IDX].clone()); self.create_table(ST_INBOUND_MSG_ID, schemas[ST_INBOUND_MSG_IDX].clone()); self.create_table(ST_OUTBOX_ID, schemas[ST_OUTBOX_IDX].clone()); - self.create_table(ST_TABLE_CACHE_POLICY_ID, schemas[ST_TABLE_CACHE_POLICY_IDX].clone()); + self.create_table( + ST_TABLE_CACHE_POLICY_ID, + schemas[ST_TABLE_CACHE_POLICY_IDX].clone(), + ); // Insert the sequences into `st_sequences` let (st_sequences, blob_store) = @@ -466,13 +492,16 @@ impl CommittedState { Some( self.get_table(table_id)? .scan_rows(self.storage.blobs()) - .with_read_eviction(self) .err_into(), ) } /// Returns an index for `table_id` on `cols`, if any. - pub(super) fn get_index_by_cols(&self, table_id: TableId, cols: &ColList) -> Option> { + pub(super) fn get_index_by_cols( + &self, + table_id: TableId, + cols: &ColList, + ) -> Option> { self.tables .get(&table_id)? .get_index_by_cols_with_table(self.storage.blobs(), cols) @@ -485,7 +514,11 @@ impl CommittedState { } /// Returns the table for `table_id` combined with the index for `index_id`, if both exist. - pub(super) fn get_index_by_id_with_table(&self, table_id: TableId, index_id: IndexId) -> Option> { + pub(super) fn get_index_by_id_with_table( + &self, + table_id: TableId, + index_id: IndexId, + ) -> Option> { self.tables .get(&table_id)? .get_index_by_id_with_table(self.storage.blobs(), index_id) @@ -555,7 +588,10 @@ impl CommittedState { self.view_instances.get(call) } - pub(super) fn active_view_calls_for_subscriber(&self, subscriber: Identity) -> HashSet { + pub(super) fn active_view_calls_for_subscriber( + &self, + subscriber: Identity, + ) -> HashSet { self.view_instances .iter() .filter(|(_, state)| { @@ -568,7 +604,9 @@ impl CommittedState { .collect() } - pub(super) fn view_instances(&self) -> impl Iterator { + pub(super) fn view_instances( + &self, + ) -> impl Iterator { self.view_instances.iter() } @@ -686,7 +724,10 @@ impl CommittedState { /// rows have changed. Preparation leaves page ownership and blob pin counts /// unchanged, so failure needs no reverse conversion: dropping the plans /// releases their temporary pins, and rollback restores the policy metadata. - fn prepare_cache_policy_changes(&self, tx_state: &TxState) -> Result> { + fn prepare_cache_policy_changes( + &self, + tx_state: &TxState, + ) -> Result> { let mut changes = BTreeMap::new(); for change in &tx_state.pending_schema_changes { let PendingSchemaChange::TableAlterCachePolicy(table_id, _) = change else { @@ -760,7 +801,14 @@ impl CommittedState { Either::Left((deletes, source)) => { let count = deletes.map_or(0, |deletes| deletes.len() as u64); let deletes = deletes.map(|deletes| deletes.iter()); - PreparedCommit::apply_resident(table, blob_store, count, deletes, source, &tx_state.blob_store) + PreparedCommit::apply_resident( + table, + blob_store, + count, + deletes, + source, + &tx_state.blob_store, + ) } Either::Right(commit) => commit.apply(table, blob_store), }; @@ -859,7 +907,10 @@ impl CommittedState { pub(super) fn rollback(&mut self, mut tx_state: TxState) -> TxOffset { // Roll back the changes in the reverse order in which they were made // so that the last change is undone first. - for change in mem::take(&mut tx_state.pending_schema_changes).into_iter().rev() { + for change in mem::take(&mut tx_state.pending_schema_changes) + .into_iter() + .rev() + { self.rollback_pending_schema_change(change); } drop(tx_state); @@ -974,8 +1025,12 @@ impl CommittedState { // and thus will only have rows compatible with it. // The rows in the tx state might not be, as they may use e.g., a new variant. // However, we don't care about that, as the tx state is being discarded. - unsafe { table.change_columns_to_unchecked(column_schemas, |_, _, _| Ok::<_, Infallible>(())) } - .unwrap_or_else(|e| match e {}); + unsafe { + table.change_columns_to_unchecked(column_schemas, |_, _, _| { + Ok::<_, Infallible>(()) + }) + } + .unwrap_or_else(|e| match e {}); } ReschemaEventTable(table_id, column_schemas) => { let table = self.tables.get_mut(&table_id)?; @@ -983,8 +1038,12 @@ impl CommittedState { // Same argument as in `TableAlterRowType` applies, // except that rather than knowing the types to be compatible, we know the commit table to be empty, // so there are no rows or pages to have a conflicting type. - unsafe { table.change_columns_to_unchecked(column_schemas, |_, _, _| Ok::<_, Infallible>(())) } - .unwrap_or_else(|e| match e {}); + unsafe { + table.change_columns_to_unchecked(column_schemas, |_, _, _| { + Ok::<_, Infallible>(()) + }) + } + .unwrap_or_else(|e| match e {}); } // A constraint was removed. Add it back. ConstraintRemoved(table_id, constraint_schema, index_ids) => { @@ -993,7 +1052,8 @@ impl CommittedState { // If the constraint had unique indices, make them unique again. for index_id in index_ids { if let Some(idx) = table.indexes.get_mut(&index_id) { - idx.make_unique().expect("rollback: index should have no duplicates"); + idx.make_unique() + .expect("rollback: index should have no duplicates"); } } // Forward `drop_constraint` calls `Table::make_index_non_unique`, which @@ -1040,7 +1100,10 @@ impl CommittedState { } #[allow(clippy::unnecessary_lazy_evaluations)] - pub fn get_table_and_blob_store(&self, table_id: TableId) -> Result> { + pub fn get_table_and_blob_store( + &self, + table_id: TableId, + ) -> Result> { let table = self .get_table(table_id) .ok_or_else(|| TableError::IdNotFoundState(table_id))?; @@ -1064,10 +1127,14 @@ impl CommittedState { pub(super) fn page_eviction_policy(&self, schema: &TableSchema) -> EvictionPolicy { // Schema recovery needs system tables to stay in memory. - if schema.table_type == StTableType::System || schema.cache_policy == TableCachePolicy::RequiredInMemory { - EvictionPolicy::NeverEvict + if schema.table_type == StTableType::System + || schema.cache_policy == TableCachePolicy::RequiredInMemory + { + EvictionPolicy::Never + } else if schema.cache_policy == TableCachePolicy::RequiredOnDisk { + EvictionPolicy::Memory } else { - EvictionPolicy::Evictable + EvictionPolicy::Disk } } @@ -1128,7 +1195,9 @@ impl CommittedState { /// Returns an iterator over all persistent tables (i.e., non-ephemeral tables) #[cfg(feature = "durability")] - pub(super) fn persistent_tables_and_blob_store(&mut self) -> (impl Iterator, &BlobSet) { + pub(super) fn persistent_tables_and_blob_store( + &mut self, + ) -> (impl Iterator, &BlobSet) { ( self.tables .iter_mut() @@ -1191,6 +1260,8 @@ impl CommittedState { 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() { diff --git a/crates/datastore/src/locking_tx_datastore/datastore.rs b/crates/datastore/src/locking_tx_datastore/datastore.rs index 318f25a2fd8..89ea7264de0 100644 --- a/crates/datastore/src/locking_tx_datastore/datastore.rs +++ b/crates/datastore/src/locking_tx_datastore/datastore.rs @@ -3715,8 +3715,16 @@ pub(crate) mod tests { #[test] fn dropped_tables_release_repeated_blob_references_with_their_own_policy() -> ResultTest<()> { - for dropped_policy in [TableCachePolicy::RequiredInMemory, TableCachePolicy::NoRequirement] { - for retained_policy in [TableCachePolicy::RequiredInMemory, TableCachePolicy::NoRequirement] { + for dropped_policy in [ + TableCachePolicy::RequiredInMemory, + TableCachePolicy::RequiredOnDisk, + TableCachePolicy::NoRequirement, + ] { + for retained_policy in [ + TableCachePolicy::RequiredInMemory, + TableCachePolicy::RequiredOnDisk, + TableCachePolicy::NoRequirement, + ] { let datastore = get_datastore()?; let mut tx = begin_mut_tx(&datastore); let baseline_bytes = tx.committed_state_write_lock.storage.resident_bytes_used_by_blobs(); @@ -5277,6 +5285,56 @@ pub(crate) mod tests { Ok(()) } + + #[test] + fn memory_disk_migrations_preserve_repeated_blob_requirements() -> ResultTest<()> { + // Observe disk reservations independently of the table's current residency. + let config = TieredStorageConfig::new_for_test(); + let local_budget = config.local_store.budget.clone(); + let datastore = Locking::bootstrap(Identity::ZERO, config)?; + + // Two references to the same content must keep two policy requirements. + let mut tx = begin_mut_tx(&datastore); + let schema = TableSchema::from_product_type([AlgebraicType::String, AlgebraicType::String].into()); + let id = datastore.create_table_mut_tx(&mut tx, schema)?; + let value = "shared".repeat(1024); + insert(&datastore, &mut tx, id, &product![value.clone(), value.clone()])?; + commit(&datastore, tx)?; + + // Exercise both directions and repeat the disk policy to expose leaked pins. + for policy in [ + TableCachePolicy::RequiredOnDisk, + TableCachePolicy::RequiredInMemory, + TableCachePolicy::RequiredOnDisk, + ] { + let mut tx = begin_mut_tx(&datastore); + tx.alter_table_cache_policy(id, policy)?; + commit(&datastore, tx)?; + + // Inspect residency only after the policy change has been applied. + let tx = begin_mut_tx(&datastore); + let blobs = tx.committed_state_write_lock.storage.blobs(); + blobs.evict(0)?; + // RequiredInMemory protects resident bytes; RequiredOnDisk protects the disk copy + // while allowing the shared blob's memory frame to be evicted. + if policy == TableCachePolicy::RequiredInMemory { + assert!(blobs.resident_bytes_used_by_blobs() >= value.len() as u64); + } else { + assert!(local_budget.usage().accounted_bytes >= value.len() as u64); + } + + commit(&datastore, tx)?; + } + + // Releasing every row must also release all restored local requirements. + let mut tx = begin_mut_tx(&datastore); + tx.drop_table(id)?; + commit(&datastore, tx)?; + assert_eq!(local_budget.usage().accounted_bytes, 0); + + Ok(()) + } + #[test] fn committed_deletion_reclaims_local_blob_capacity() -> ResultTest<()> { for drop_table in [false, true] { diff --git a/crates/datastore/src/locking_tx_datastore/replay.rs b/crates/datastore/src/locking_tx_datastore/replay.rs index c2d9f19b128..48227794b83 100644 --- a/crates/datastore/src/locking_tx_datastore/replay.rs +++ b/crates/datastore/src/locking_tx_datastore/replay.rs @@ -1532,8 +1532,16 @@ mod tests { Ok(()) } - for dropped_policy in [TableCachePolicy::RequiredInMemory, TableCachePolicy::NoRequirement] { - for retained_policy in [TableCachePolicy::RequiredInMemory, TableCachePolicy::NoRequirement] { + for dropped_policy in [ + TableCachePolicy::RequiredInMemory, + TableCachePolicy::RequiredOnDisk, + TableCachePolicy::NoRequirement, + ] { + for retained_policy in [ + TableCachePolicy::RequiredInMemory, + TableCachePolicy::RequiredOnDisk, + TableCachePolicy::NoRequirement, + ] { go(dropped_policy, retained_policy)?; } } diff --git a/crates/snapshot/src/remote.rs b/crates/snapshot/src/remote.rs index ff8b21c66cc..9b77aeac206 100644 --- a/crates/snapshot/src/remote.rs +++ b/crates/snapshot/src/remote.rs @@ -986,7 +986,7 @@ mod tests { &[] as &[&[u8]], u64_var_len_visitor(), &mut BlobSet::new_for_test(), - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, ) } .expect("Failed to insert first row") diff --git a/crates/table/benches/page.rs b/crates/table/benches/page.rs index 35730af6c23..131e4a8dee9 100644 --- a/crates/table/benches/page.rs +++ b/crates/table/benches/page.rs @@ -162,7 +162,7 @@ fn fill_with_fixed_len(page: &mut Page, val: Row, visitor: &im &[] as &[&[u8]], visitor, &mut BlobSet::new_for_test(), - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, ) }); } @@ -223,7 +223,7 @@ fn delete_all_shuffled(page: &mut Page, rng: &mut impl Rng) { row_size_for_type::(), &visitor, &BlobSet::new_for_test(), - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, ) }; } @@ -238,7 +238,7 @@ fn fill_with_var_len(page: &mut Page, var_len: &[u8], visitor: &impl VarLenMembe &[var_len], visitor, &mut BlobSet::new_for_test(), - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, ) }); } @@ -366,7 +366,7 @@ fn insert_opt_str(c: &mut Criterion) { &[] as &[&[u8]], &visitor, &mut BlobSet::new_for_test(), - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, ) }; } else { @@ -379,7 +379,7 @@ fn insert_opt_str(c: &mut Criterion) { &[&var_len_data], &visitor, &mut BlobSet::new_for_test(), - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, ) }; } @@ -414,7 +414,7 @@ fn delete_to_approx_fullness_ratio(page: &mut Page, fullness: row_size_for_type::(), &visitor, &BlobSet::new_for_test(), - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, ) }; } @@ -740,7 +740,7 @@ fn time_insert_one( visitor, ty, &val, - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, )); }); } @@ -795,7 +795,7 @@ fn extract_product_value_from_page(c: &mut Criterion) { &visitor, &ty, &value, - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, ) } .unwrap(); @@ -815,9 +815,9 @@ fn eq_in_page_same(c: &mut Criterion) { let blobs = BlobSet::new_for_test(); let (offset_0, _) = - unsafe { write_row_to_page(&mut page, &blobs, &visitor, &ty, &value, EvictionPolicy::NeverEvict) }.unwrap(); + unsafe { write_row_to_page(&mut page, &blobs, &visitor, &ty, &value, EvictionPolicy::Never) }.unwrap(); let (offset_1, _) = - unsafe { write_row_to_page(&mut page, &blobs, &visitor, &ty, &value, EvictionPolicy::NeverEvict) }.unwrap(); + unsafe { write_row_to_page(&mut page, &blobs, &visitor, &ty, &value, EvictionPolicy::Never) }.unwrap(); group.bench_function(name, |b| { b.iter(|| { @@ -852,7 +852,7 @@ fn hash_in_page(c: &mut Criterion) { &visitor, &ty, &value, - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, ) } .unwrap(); diff --git a/crates/table/benches/page_manager.rs b/crates/table/benches/page_manager.rs index a19599b8e0a..319790e12c1 100644 --- a/crates/table/benches/page_manager.rs +++ b/crates/table/benches/page_manager.rs @@ -268,7 +268,7 @@ fn make_table(c: &mut Criterion) { schema.into(), SquashedOffset::COMMITTED_STATE, PageManager::new_for_test().into(), - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, )); } let elapsed = WallTime.end(start); @@ -292,7 +292,7 @@ fn make_table_for_row_type(name: &str) -> Table { schema.into(), SquashedOffset::COMMITTED_STATE, PageManager::new_for_test().into(), - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, ) } @@ -525,7 +525,7 @@ fn make_table_with_index(unique: bool) -> (Table, IndexId) { schema.into(), SquashedOffset::COMMITTED_STATE, PageManager::new_for_test().into(), - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, ); let cols = R::indexed_columns(); diff --git a/crates/table/src/bflatn_to.rs b/crates/table/src/bflatn_to.rs index f9a6b9143eb..71d795e7731 100644 --- a/crates/table/src/bflatn_to.rs +++ b/crates/table/src/bflatn_to.rs @@ -22,7 +22,8 @@ use spacetimedb_sats::{ de::DeserializeSeed as _, i256, layout::{ - align_to, AlgebraicTypeLayout, HasLayout, ProductTypeLayoutView, RowTypeLayout, SumTypeLayout, VarLenType, + align_to, AlgebraicTypeLayout, HasLayout, ProductTypeLayoutView, RowTypeLayout, + SumTypeLayout, VarLenType, }, u256, AlgebraicType, AlgebraicValue, ProductValue, SumValue, }; @@ -64,8 +65,21 @@ pub unsafe fn write_row_to_pages_bsatn( squashed_offset: SquashedOffset, eviction_policy: EvictionPolicy, ) -> Result<(RowPointer, BlobNumBytes), 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) } + 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, + ) + } } /// Writes `row` typed at `ty` to `pages` @@ -118,9 +132,10 @@ pub unsafe fn write_row_to_pages( ) } })? { - (page, Ok((offset, blob_inserted))) => { - Ok((RowPointer::new(false, page, offset, squashed_offset), blob_inserted)) - } + (page, Ok((offset, blob_inserted))) => Ok(( + RowPointer::new(false, page, offset, squashed_offset), + blob_inserted, + )), (_, Err(e)) => Err(e), } } @@ -149,7 +164,17 @@ pub unsafe fn write_row_to_page( eviction_policy: EvictionPolicy, ) -> Result<(PageOffset, BlobNumBytes), Error> { // SAFETY: Forward the caller's guarantees about the page layout and visitor. - unsafe { write_row_to_page_with_memory_limit_exemption(page, blobs, visitor, ty, val, eviction_policy, false) } + unsafe { + write_row_to_page_with_memory_limit_exemption( + page, + blobs, + visitor, + ty, + val, + eviction_policy, + false, + ) + } } unsafe fn write_row_to_page_with_memory_limit_exemption( @@ -256,7 +281,11 @@ impl BflatnSerializedRowBuffer<'_> { /// Insert all large blobs into `blob_store` and their hashes to their granules. #[cold] #[inline(never)] - fn write_large_blobs(&mut self, blobs: &BlobSet, memory_limit_exempt: bool) -> Result { + fn write_large_blobs( + &mut self, + blobs: &BlobSet, + memory_limit_exempt: bool, + ) -> Result { let mut blob_store_inserted_bytes = BlobNumBytes::default(); for (i, (vlr, value)) in self.large_blob_insertions.iter().enumerate() { // SAFETY: `vlr` was given to us by `alloc_for_slice` @@ -308,7 +337,9 @@ impl BflatnSerializedRowBuffer<'_> { // and finally write the tag. (AlgebraicTypeLayout::Sum(ty), AlgebraicValue::Sum(val)) => self.write_sum(ty, val)?, // For products, write every element in order. - (AlgebraicTypeLayout::Product(ty), AlgebraicValue::Product(val)) => self.write_product(ty.view(), val)?, + (AlgebraicTypeLayout::Product(ty), AlgebraicValue::Product(val)) => { + self.write_product(ty.view(), val)? + } // For primitive types, write their contents by LE-encoding. (&AlgebraicTypeLayout::Bool, AlgebraicValue::Bool(val)) => self.write_bool(*val), @@ -331,7 +362,9 @@ impl BflatnSerializedRowBuffer<'_> { // For strings, we reserve space for a `VarLenRef` // and push the bytes as a var-len object. - (&AlgebraicTypeLayout::String, AlgebraicValue::String(val)) => self.write_string(val)?, + (&AlgebraicTypeLayout::String, AlgebraicValue::String(val)) => { + self.write_string(val)? + } // For array and maps, we reserve space for a `VarLenRef` // and push the bytes, after BSATN encoding, as a var-len object. @@ -366,7 +399,11 @@ impl BflatnSerializedRowBuffer<'_> { } /// Write an `val`, a [`ProductValue`], typed at `ty`, to the buffer. - fn write_product(&mut self, ty: ProductTypeLayoutView<'_>, val: &ProductValue) -> Result<(), Error> { + fn write_product( + &mut self, + ty: ProductTypeLayoutView<'_>, + val: &ProductValue, + ) -> Result<(), Error> { // `Iterator::zip` silently drops elements if the two iterators have different lengths, // so we need to check that our `ProductValue` has the same number of elements // as our `ProductTypeLayout` to be sure it's typed correctly. @@ -622,7 +659,9 @@ pub mod test { use std::sync::Arc; use super::*; - use crate::tiered::{metrics::CacheTier, ByteBudget, ByteBudgetConfig, ResidentObjects, TieredStorage}; + use crate::tiered::{ + metrics::CacheTier, ByteBudget, ByteBudgetConfig, ResidentObjects, TieredStorage, + }; use crate::{ bflatn_from::serialize_row_from_page, page::tests::hash_unmodified_save_get, row_type_visitor::row_type_visitor, tiered::BlobReadSet, @@ -652,28 +691,49 @@ pub mod test { // Pin the first blob so inserting the second cannot evict it. Writing // the row will therefore succeed for the first field and fail for the // second, exercising rollback after a partial blob-set mutation. - let first_pin = blobs.insert(EvictionPolicy::Evictable, first.as_bytes()).unwrap(); + let first_pin = blobs + .insert(EvictionPolicy::Memory, first.as_bytes()) + .unwrap(); let first_hash = first_pin.hash(); - let ty: RowTypeLayout = ProductType::from([AlgebraicType::String, AlgebraicType::String]).into(); + let ty: RowTypeLayout = + ProductType::from([AlgebraicType::String, AlgebraicType::String]).into(); let visitor = row_type_visitor(&ty); let row = spacetimedb_sats::product![first.clone(), second.clone()]; let mut page = Page::new(ty.size()); - // Repeat the failure to exercise granules reused from the freelist. - for _ in 0..2 { - let error = unsafe { write_row_to_page(&mut page, &blobs, &visitor, &ty, &row, EvictionPolicy::Evictable) } - .unwrap_err(); - assert!(matches!(error, Error::Blobs(BlobError::MemoryLimitExceeded(_)))); - assert_eq!(page.num_rows(), 0); - assert_eq!(blobs.num_blobs(), 1); - assert_eq!(blobs.usage_counter().get(&first_hash), Some(&1)); + let error = unsafe { + write_row_to_page( + &mut page, + &blobs, + &visitor, + &ty, + &row, + EvictionPolicy::Memory, + ) } + .unwrap_err(); + assert!(matches!( + error, + Error::Blobs(BlobError::MemoryLimitExceeded(_)) + )); + assert_eq!(page.num_rows(), 0); + assert_eq!(blobs.num_blobs(), 1); + assert_eq!(blobs.usage_counter().get(&first_hash), Some(&1)); // The failed row's page allocations must also be reusable. drop(first_pin); - let (offset, _) = - unsafe { write_row_to_page(&mut page, &blobs, &visitor, &ty, &row, EvictionPolicy::Evictable) }.unwrap(); - unsafe { page.delete_row(offset, ty.size(), &visitor, &blobs, EvictionPolicy::Evictable) }; + let (offset, _) = unsafe { + write_row_to_page( + &mut page, + &blobs, + &visitor, + &ty, + &row, + EvictionPolicy::Memory, + ) + } + .unwrap(); + unsafe { page.delete_row(offset, ty.size(), &visitor, &blobs, EvictionPolicy::Memory) }; assert_eq!(page.num_rows(), 0); assert_eq!(blobs.usage_counter().get(&first_hash), Some(&1)); } @@ -696,17 +756,32 @@ pub mod test { ); // This owner allows eviction. Keep its handle during the write so the // second field deterministically fails the one-blob memory limit. - let first_handle = blobs.insert(EvictionPolicy::Evictable, first.as_bytes()).unwrap(); + let first_handle = blobs + .insert(EvictionPolicy::Memory, first.as_bytes()) + .unwrap(); let hash = first_handle.hash(); - let ty: RowTypeLayout = ProductType::from([AlgebraicType::String, AlgebraicType::String]).into(); + let ty: RowTypeLayout = + ProductType::from([AlgebraicType::String, AlgebraicType::String]).into(); let visitor = row_type_visitor(&ty); let row = spacetimedb_sats::product![first, second.clone()]; let mut page = Page::new(ty.size()); // SAFETY: The page, visitor and row all use the same two-string layout. - let error = unsafe { write_row_to_page(&mut page, &blobs, &visitor, &ty, &row, EvictionPolicy::NeverEvict) } - .unwrap_err(); - assert!(matches!(error, Error::Blobs(BlobError::MemoryLimitExceeded(_)))); + let error = unsafe { + write_row_to_page( + &mut page, + &blobs, + &visitor, + &ty, + &row, + EvictionPolicy::Never, + ) + } + .unwrap_err(); + assert!(matches!( + error, + Error::Blobs(BlobError::MemoryLimitExceeded(_)) + )); assert_eq!(page.num_rows(), 0); assert_eq!(blobs.num_blobs(), 1); assert_eq!(blobs.usage_counter().get(&hash), Some(&1)); @@ -714,7 +789,7 @@ pub mod test { // The failed insertion never created a never-evict owner. After the // reader goes away, a different evictable blob must fit in its place. drop(first_handle); - let replacement = blobs.insert(EvictionPolicy::Evictable, second.as_bytes()); + let replacement = blobs.insert(EvictionPolicy::Memory, second.as_bytes()); assert!( replacement.is_ok(), "failed write retained a policy pin: {replacement:?}" @@ -732,7 +807,7 @@ pub mod test { let hash_pre_ins = hash_unmodified_save_get(&mut page); - let (offset, _) = unsafe { write_row_to_page(&mut page, blobs, &visitor, &ty, &val, EvictionPolicy::Evictable).unwrap() }; + let (offset, _) = unsafe { write_row_to_page(&mut page, blobs, &visitor, &ty, &val, EvictionPolicy::Memory).unwrap() }; let hash_pre_ser = hash_unmodified_save_get(&mut page); assert_ne!(hash_pre_ins, hash_pre_ser); diff --git a/crates/table/src/page.rs b/crates/table/src/page.rs index 13c3ddcbc67..e0559c433a0 100644 --- a/crates/table/src/page.rs +++ b/crates/table/src/page.rs @@ -2183,7 +2183,7 @@ pub(crate) mod tests { &[] as &[&[u8]], u64_var_len_visitor(), &mut BlobSet::new_for_test(), - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, ) } .expect("Failed to insert first row") @@ -2329,7 +2329,7 @@ pub(crate) mod tests { u64_row_size(), u64_var_len_visitor(), blobs, - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, ) }; } @@ -2378,7 +2378,7 @@ pub(crate) mod tests { u64_row_size(), u64_var_len_visitor(), &BlobSet::new_for_test(), - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, ) }; @@ -2421,7 +2421,7 @@ pub(crate) mod tests { &[data], str_var_len_visitor(), &mut BlobSet::new_for_test(), - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, ) } .expect("Failed to insert row") @@ -2450,7 +2450,7 @@ pub(crate) mod tests { STR_ROW_SIZE, str_var_len_visitor(), blobs, - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, ) }; assert_page_summaries_match(&page, &capacity, STR_ROW_SIZE); @@ -2586,7 +2586,7 @@ pub(crate) mod tests { STR_ROW_SIZE, str_var_len_visitor(), blobs, - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, ) }; @@ -2636,7 +2636,7 @@ pub(crate) mod tests { STR_ROW_SIZE, str_var_len_visitor(), blobs, - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, ) }; @@ -2695,7 +2695,7 @@ pub(crate) mod tests { STR_ROW_SIZE, str_var_len_visitor(), blobs, - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, ) }; @@ -2807,7 +2807,7 @@ pub(crate) mod tests { STR_ROW_SIZE, str_var_len_visitor(), blobs, - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, ) }; } @@ -2877,7 +2877,7 @@ pub(crate) mod tests { u64_row_size(), u64_var_len_visitor(), blobs, - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, ) }; None diff --git a/crates/table/src/pages.rs b/crates/table/src/pages.rs index 2ed5009fdd3..7c343f882fb 100644 --- a/crates/table/src/pages.rs +++ b/crates/table/src/pages.rs @@ -303,15 +303,7 @@ impl Pages { // - Caller promised that `fixed_row.len()` is consistent // with what has been passed to the manager in all other ops. // This entails that `fixed_row.len()` is consistent with `page`. - unsafe { - page.insert_row( - fixed_len, - var_len, - var_len_visitor, - blob_store, - EvictionPolicy::NeverEvict, - ) - } + unsafe { page.insert_row(fixed_len, var_len, var_len_visitor, blob_store, EvictionPolicy::Never) } }, )? { (page, Ok(offset)) => Ok((page, offset)), @@ -357,7 +349,7 @@ impl Pages { fixed_row_size, var_len_visitor, blob_store, - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, ) } }) diff --git a/crates/table/src/static_bsatn_validator.rs b/crates/table/src/static_bsatn_validator.rs index 2ac102253c1..114ff224204 100644 --- a/crates/table/src/static_bsatn_validator.rs +++ b/crates/table/src/static_bsatn_validator.rs @@ -411,7 +411,7 @@ pub mod test { &visitor, &ty, &val, - EvictionPolicy::NeverEvict + EvictionPolicy::Never ) }; diff --git a/crates/table/src/table.rs b/crates/table/src/table.rs index ea4427cb399..672dabc5f91 100644 --- a/crates/table/src/table.rs +++ b/crates/table/src/table.rs @@ -1871,7 +1871,15 @@ impl Table { pinned_pages: Vec::new(), pinned_blobs: Vec::new(), }; - if policy == self.eviction_policy || policy == EvictionPolicy::Evictable { + let is_noop = + // The policy is unchanged. + policy == self.eviction_policy + // `Disk` relaxes residency, we don't need to pin anything. + || policy == EvictionPolicy::Disk + // `Never` already protects every object needed to apply a new + // policy. + || self.eviction_policy == EvictionPolicy::Never; + if is_noop { return Ok(prepared); } @@ -2343,8 +2351,10 @@ impl Table { blob_store_bytes += blob.size() as usize; - if let EvictionPolicy::NeverEvict = self.eviction_policy { - blobs.pin_handle(&blob)?; + match self.eviction_policy { + EvictionPolicy::Never => blobs.pin_handle(&blob)?, + EvictionPolicy::Memory => blobs.pin_disk(blob.hash()), + EvictionPolicy::Disk => {} } } @@ -3457,12 +3467,20 @@ impl PreparedEvictionPolicy { // For disk tables, preparation holds the existing pages and blobs in memory. // The commit's insertion handles keep newly inserted blobs resident. table - .for_each_blob_ref(|hash| match self.policy { - EvictionPolicy::NeverEvict => blobs.pin(hash.into()), - EvictionPolicy::Evictable => { - blobs.unpin(hash.into()); - Ok(()) + .for_each_blob_ref(|hash| { + match self.policy { + EvictionPolicy::Never => blobs.pin(hash.into())?, + EvictionPolicy::Memory => blobs.pin_disk(hash.into()), + EvictionPolicy::Disk => {} } + + match self.old_policy { + EvictionPolicy::Never => blobs.unpin(hash.into()), + EvictionPolicy::Memory => blobs.unpin_disk(hash.into()), + EvictionPolicy::Disk => {} + } + + Ok(()) }) .expect("preparation and insertion pins keep pages and blobs resident"); // Exclusive table access prevents page eviction during conversion. @@ -3531,7 +3549,7 @@ pub(crate) mod test { schema.into(), SquashedOffset::COMMITTED_STATE, page_manager, - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, ) } @@ -3559,7 +3577,7 @@ pub(crate) mod test { schema.into(), SquashedOffset::COMMITTED_STATE, PageManager::new_for_test().into(), - EvictionPolicy::NeverEvict, + EvictionPolicy::Never, ); let blob_store = &mut BlobSet::new_for_test(); let cols = ColList::new(0.into()); @@ -4267,7 +4285,7 @@ pub(crate) mod test { schema.clone().into(), SquashedOffset::COMMITTED_STATE, manager.clone(), - EvictionPolicy::Evictable, + EvictionPolicy::Memory, ); let blobs = BlobSet::new_for_test(); let index_id = IndexId(1); @@ -4288,12 +4306,7 @@ pub(crate) mod test { // Occupy and pin the entire resident-page budget with another table. // The target table's evicted page therefore cannot be faulted in. - let mut blocker = Table::new( - schema.into(), - SquashedOffset::TX_STATE, - manager, - EvictionPolicy::Evictable, - ); + let mut blocker = Table::new(schema.into(), SquashedOffset::TX_STATE, manager, EvictionPolicy::Memory); let (_, blocker_pin) = blocker.insert(&blobs, &product![1_u64]).unwrap(); // Rebuilding the pointer map fails. The unique index must remain in @@ -4333,7 +4346,7 @@ pub(crate) mod test { schema.clone().into(), SquashedOffset::COMMITTED_STATE, manager.clone(), - EvictionPolicy::Evictable, + EvictionPolicy::Memory, ); let blobs = BlobSet::new_for_test(); let index_id = IndexId(1); @@ -4353,12 +4366,7 @@ pub(crate) mod test { // Occupy and pin the entire resident-page budget with another table. // The target table's evicted page therefore cannot be faulted in. - let mut blocker = Table::new( - schema.into(), - SquashedOffset::TX_STATE, - manager, - EvictionPolicy::Evictable, - ); + let mut blocker = Table::new(schema.into(), SquashedOffset::TX_STATE, manager, EvictionPolicy::Memory); let (_, blocker_pin) = blocker.insert(&blobs, &product![1_u64]).unwrap(); // Rebuilding the pointer map fails. The unique index must remain in @@ -4409,7 +4417,7 @@ pub(crate) mod test { schema.into(), SquashedOffset::COMMITTED_STATE, Arc::new(manager), - EvictionPolicy::Evictable, + EvictionPolicy::Memory, ); let blobs = BlobSet::new_for_test(); @@ -4456,7 +4464,7 @@ pub(crate) mod test { schema.into(), SquashedOffset::COMMITTED_STATE, manager, - EvictionPolicy::Evictable, + EvictionPolicy::Memory, ); let mut expected = Vec::new(); loop { @@ -4511,7 +4519,7 @@ pub(crate) mod test { schema.into(), SquashedOffset::COMMITTED_STATE, manager, - EvictionPolicy::Evictable, + EvictionPolicy::Memory, ); // The two blobs can be written one at a time, evicting the previous one, @@ -4612,12 +4620,7 @@ pub(crate) mod test { let manager = Arc::new(PageManager::new(resident, PagePool::new_for_test(), storage)); let schema = TableSchema::from_product_type(ProductType::from([AlgebraicType::String, AlgebraicType::String])); - let mut table = Table::new( - schema.into(), - SquashedOffset::TX_STATE, - manager, - EvictionPolicy::Evictable, - ); + let mut table = Table::new(schema.into(), SquashedOffset::TX_STATE, manager, EvictionPolicy::Memory); let row = product![first, second]; // Serialization can write and evict the blobs one at a time. The @@ -4664,7 +4667,7 @@ pub(crate) mod test { schema.into(), SquashedOffset::COMMITTED_STATE, manager, - EvictionPolicy::Evictable, + EvictionPolicy::Memory, ); // Keep an index in both cases: clearing must discard its entries, // whether set semantics are provided by it or by a pointer map. @@ -4681,7 +4684,7 @@ pub(crate) mod test { table.insert(&blobs, &product![1_u64, large.clone()]).unwrap(); // Another owner still references the same blob, so clear must // decrement the reference count rather than remove it outright. - let other_use = blobs.insert(EvictionPolicy::Evictable, large.as_bytes()).unwrap(); + let other_use = blobs.insert(EvictionPolicy::Memory, large.as_bytes()).unwrap(); let hash = other_use.hash(); // Drop the residency pin, but retain the logical reference created // by insert. Eviction can now move the bytes out of memory. @@ -4706,7 +4709,7 @@ pub(crate) mod test { let index = table.get_index_by_id(index_id).unwrap(); let key = AlgebraicValue::U64(0); assert!(index.seek_point(&index.key_from_algebraic_value(&key)).next().is_none()); - blobs.free_ref(hash, EvictionPolicy::Evictable).unwrap(); + blobs.free_ref(hash, EvictionPolicy::Memory).unwrap(); assert_eq!(blobs.num_blobs(), 0); // The empty index and page set must remain usable after clear. table.insert(&blobs, &product![0_u64, "new"]).unwrap(); @@ -4735,7 +4738,7 @@ pub(crate) mod test { schema.into(), SquashedOffset::COMMITTED_STATE, manager, - EvictionPolicy::Evictable, + EvictionPolicy::Memory, ); let large = "x".repeat(VarLenGranule::OBJECT_SIZE_BLOB_THRESHOLD + 1); // Distinct IDs make every row unique; the shared string gives one blob @@ -4800,7 +4803,7 @@ pub(crate) mod test { schema.into(), SquashedOffset::COMMITTED_STATE, manager, - EvictionPolicy::Evictable, + EvictionPolicy::Memory, ); let row = product![0_u64, large.clone()]; committed.insert(&blobs, &row).unwrap(); @@ -4856,7 +4859,7 @@ pub(crate) mod test { schema.into(), SquashedOffset::COMMITTED_STATE, manager, - EvictionPolicy::Evictable, + EvictionPolicy::Memory, ); // Fill the first page completely. Remove the row that overflowed onto // the second page so the next insertion can allocate a fresh page @@ -4900,7 +4903,7 @@ pub(crate) mod test { // An evictable table still logically owns the bytes after this table // is cleared. Drop its read handle so it does not pin residency itself. - let other_owner = blobs.insert(EvictionPolicy::Evictable, large.as_bytes()).unwrap(); + let other_owner = blobs.insert(EvictionPolicy::Memory, large.as_bytes()).unwrap(); let hash = other_owner.hash(); drop(other_owner); drop(table.insert(&blobs, &product![large]).unwrap()); @@ -4919,7 +4922,7 @@ pub(crate) mod test { let blobs = BlobSet::new_for_test(); let mut table = table(ProductType::from([AlgebraicType::String])); let large = "x".repeat(VarLenGranule::OBJECT_SIZE_BLOB_THRESHOLD + 1); - let other_owner = blobs.insert(EvictionPolicy::Evictable, large.as_bytes()).unwrap(); + let other_owner = blobs.insert(EvictionPolicy::Memory, large.as_bytes()).unwrap(); let hash = other_owner.hash(); drop(other_owner); @@ -4937,7 +4940,7 @@ pub(crate) mod test { #[test] fn row_insertion_applies_table_policy_to_blobs() { - for policy in [EvictionPolicy::Evictable, EvictionPolicy::NeverEvict] { + for policy in [EvictionPolicy::Memory, EvictionPolicy::Never] { for use_bsatn in [false, true] { let blobs = &mut BlobSet::new_for_test(); let schema = TableSchema::from_product_type(ProductType::from([AlgebraicType::String])); @@ -4961,8 +4964,8 @@ pub(crate) mod test { assert_eq!( blobs.resident_usage().accounted_bytes(), match policy { - EvictionPolicy::NeverEvict => large.len() as u64, - EvictionPolicy::Evictable => 0, + EvictionPolicy::Never => large.len() as u64, + EvictionPolicy::Memory | EvictionPolicy::Disk => 0, } ); // Reading after eviction must preserve the stored value too. @@ -4973,7 +4976,7 @@ pub(crate) mod test { #[test] fn snapshot_restore_applies_table_policy_to_shared_blobs() { - for policy in [EvictionPolicy::Evictable, EvictionPolicy::NeverEvict] { + for policy in [EvictionPolicy::Memory, EvictionPolicy::Never] { let blobs = BlobSet::new_for_test(); let schema = TableSchema::from_product_type(ProductType::from([AlgebraicType::U64, AlgebraicType::String])); let mut table = Table::new( @@ -4996,7 +4999,7 @@ pub(crate) mod test { &table.inner.visitor_prog, &table.inner.row_layout, row, - EvictionPolicy::Evictable, + EvictionPolicy::Memory, ) } .unwrap(); @@ -5018,8 +5021,8 @@ pub(crate) mod test { assert_eq!( blobs.resident_usage().accounted_bytes(), match policy { - EvictionPolicy::NeverEvict => large.len() as u64, - EvictionPolicy::Evictable => 0, + EvictionPolicy::Never => large.len() as u64, + EvictionPolicy::Memory | EvictionPolicy::Disk => 0, } ); let actual = table @@ -5060,7 +5063,7 @@ pub(crate) mod test { &table.inner.visitor_prog, &table.inner.row_layout, row, - EvictionPolicy::Evictable, + EvictionPolicy::Memory, ) } .unwrap(); @@ -5093,14 +5096,9 @@ pub(crate) mod test { schema.clone(), SquashedOffset::COMMITTED_STATE, manager.clone(), - EvictionPolicy::NeverEvict, - ); - let mut evictable = Table::new( - schema, - SquashedOffset::COMMITTED_STATE, - manager, - EvictionPolicy::Evictable, + EvictionPolicy::Never, ); + let mut evictable = Table::new(schema, SquashedOffset::COMMITTED_STATE, manager, EvictionPolicy::Memory); let large = "x".repeat(VarLenGranule::OBJECT_SIZE_BLOB_THRESHOLD + 1); let row = product![large.clone()]; drop(required.insert(&blobs, &row).unwrap()); @@ -5138,7 +5136,7 @@ pub(crate) mod test { schema.into(), SquashedOffset::COMMITTED_STATE, manager, - EvictionPolicy::Evictable, + EvictionPolicy::Memory, ); let value: AlgebraicValue = if fixed_rows { 42_u64.into() @@ -5225,4 +5223,138 @@ pub(crate) mod test { fn prepared_fixed_commit_retains_pointer_map_candidate_pins() { assert_prepared_commit_protects_pointer_map_candidates(false, true); } + + proptest! { + #[test] + fn cache_policy_changes_preserve_shared_blobs( + value in "[a-z]{1024,1100}", + restored in any::(), + initial_policy in prop_oneof![ + Just(EvictionPolicy::Never), + Just(EvictionPolicy::Memory), + ], + ) { + use crate::tiered::{BackingStore, MemoryObjectStore, Object}; + + // Give remote eviction a real alternative while measuring local reservations. + let local_budget = ByteBudget::unlimited(); + let storage = Arc::new(TieredStorage::empty( + BackingStore { + object_store: Box::new(MemoryObjectStore::default()), + budget: local_budget.clone(), + }, + Some(BackingStore { + object_store: Box::new(MemoryObjectStore::default()), + budget: ByteBudget::unlimited(), + }), + )); + let resident = Arc::new(ResidentObjects::new(ByteBudget::unlimited())); + let manager = Arc::new(PageManager::new( + resident.clone(), + PagePool::new_for_test(), + storage.clone(), + )); + let blobs = BlobSet::new(resident, storage.clone()); + let schema = + TableSchema::from_product_type([AlgebraicType::String, AlgebraicType::String].into()); + let mut table = Table::new( + schema.into(), + SquashedOffset::COMMITTED_STATE, + manager, + initial_policy, + ); + let row = product![value.clone(), value.clone()]; + let hash = BlobHash::hash_from_bytes(value.as_bytes()); + + // Both insertion and snapshot recovery must contribute two independent policy pins. + if restored { + let mut page = Page::new(table.row_size()); + // SAFETY: The page, layout, visitor, and row all use the table's schema. + unsafe { + crate::bflatn_to::write_row_to_page( + &mut page, + &blobs, + &table.inner.visitor_prog, + &table.inner.row_layout, + &row, + EvictionPolicy::Disk, + ) + } + .unwrap(); + // SAFETY: The page was written with this exact table's layout. + unsafe { table.set_pages(vec![Some(page)], &blobs) }.unwrap(); + } else { + drop(table.insert(&blobs, &row).unwrap()); + } + + // A Disk row shares the object without relaxing the table's current residency. + // Install a disk copy to model backing left behind by an earlier policy. + drop( + blobs + .insert(EvictionPolicy::Disk, value.as_bytes()) + .unwrap(), + ); + let handle = blobs.get(hash.into()).unwrap(); + let object = Object::from(&handle); + let copy = storage.write(object, EvictionPolicy::Disk).unwrap(); + let key = copy.key(); + drop(copy); + drop(handle); + + // Moving to Never makes the previous disk copy redundant. Moving back to Memory + // must restore disk protection before the resident bytes become evictable. + for policy in [ + EvictionPolicy::Never, + EvictionPolicy::Memory, + EvictionPolicy::Never, + EvictionPolicy::Memory, + ] { + table + .prepare_eviction_policy(&blobs, policy) + .unwrap() + .apply(&mut table, &blobs); + blobs.evict(0).unwrap(); + let freed = storage.evict(0).unwrap(); + match policy { + // Never keeps the blob resident, so a copy left on disk must be evictable. + EvictionPolicy::Never => { + prop_assert_eq!(freed, value.len() as u64); + prop_assert_eq!(local_budget.usage().accounted_bytes, 0); + prop_assert!(blobs.resident_bytes_used_by_blobs() >= value.len() as u64); + let actual = table + .scan_rows(&blobs) + .next() + .unwrap() + .unwrap() + .to_product_value(); + prop_assert_eq!(&actual, &row); + } + // Memory allows the resident frame to leave but must retain its disk copy. + EvictionPolicy::Memory => { + prop_assert_eq!(freed, 0); + prop_assert_eq!(local_budget.usage().accounted_bytes, value.len() as u64); + prop_assert_eq!(blobs.resident_bytes_used_by_blobs(), 0); + } + EvictionPolicy::Disk => { + unreachable!("this sequence tests memory/disk residency changes") + } + } + prop_assert_eq!(blobs.uses(hash.into()), Some(3)); + } + + // Releasing the final Memory policy drops its disk pins while the Disk row stays alive. + table.prepare_blob_release().unwrap().apply(&blobs); + drop(table); + blobs.evict(0).unwrap(); + prop_assert_eq!(storage.evict(0).unwrap(), value.len() as u64); + prop_assert_eq!(local_budget.usage().accounted_bytes, 0); + let recovered = storage.read(key).unwrap(); + prop_assert_eq!(recovered.as_ref(), value.as_bytes()); + + blobs.free_ref(hash.into(), EvictionPolicy::Disk).unwrap(); + storage.reclaim().unwrap(); + prop_assert!(!storage.contains(key)); + prop_assert_eq!(local_budget.usage().accounted_bytes, 0); + } + } } diff --git a/crates/table/src/tiered/blob_set.rs b/crates/table/src/tiered/blob_set.rs index 164bf888760..fa9971e88aa 100644 --- a/crates/table/src/tiered/blob_set.rs +++ b/crates/table/src/tiered/blob_set.rs @@ -22,7 +22,7 @@ use crate::{ error::{BlobError, ObjectStoreError}, map::{BlobHashWrapper, ObjectKey}, mem::{self, BlobEvictionCandidate, BlobFrame, ReservedBlob}, - storage::{DiskObject, Object}, + storage::{DiskObject, DiskRetention, Object}, ByteBudget, ByteBudgetUsage, EvictionPolicy, TieredStorage, }, var_len::VarLenMembers, @@ -68,7 +68,8 @@ impl BlobSet { uses: uses.get(), pins: 0, blob: BlobHandle { frame }, - _backing: None, + backing: None, + disk_pins: 0, }, ); } @@ -129,7 +130,7 @@ impl BlobSet { }); if let Some(blob) = maybe_resident { - let backing = self.storage.write(Object::from(&blob))?; + 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"), &candidate.key @@ -143,6 +144,7 @@ impl BlobSet { uses, blob: current, pins, + disk_pins, .. } = entry else { @@ -164,6 +166,7 @@ impl BlobSet { }; let size = blob.size(); + backing.set_pins(*disk_pins); *entry = BlobEntry::NonResident { uses: *uses, size, @@ -224,9 +227,10 @@ impl BlobSet { ) -> Result { let uses = NonZeroUsize::MIN; let hash = BlobHashWrapper::hash_from_bytes(bytes); + // Memory pins -- disk pins are handled below. let pins = match eviction_policy { - EvictionPolicy::Evictable => 0, - EvictionPolicy::NeverEvict => 1, + EvictionPolicy::Never => 1, + EvictionPolicy::Memory | EvictionPolicy::Disk => 0, }; { let mut entries = self.entries.write(); @@ -234,11 +238,20 @@ impl BlobSet { uses: current_uses, pins: current_pins, blob, - .. + backing, + disk_pins, }) = entries.get_mut(&hash) { *current_uses += uses.get(); *current_pins += pins; + + if DiskRetention::is_required(eviction_policy) { + *disk_pins = disk_pins.checked_add(1).expect("disk pin count overflow"); + if let Some(backing) = backing { + backing.pin(); + } + } + return Ok(blob.clone()); } } @@ -255,7 +268,8 @@ impl BlobSet { uses: uses.get(), pins, blob: handle.clone(), - _backing: None, + backing: None, + disk_pins: DiskRetention::is_required(eviction_policy).into(), }); Ok(handle) } @@ -266,10 +280,19 @@ impl BlobSet { uses: current_uses, pins: current_pins, blob, - .. + backing, + disk_pins, } => { *current_uses += uses.get(); *current_pins += pins; + + if DiskRetention::is_required(eviction_policy) { + *disk_pins = disk_pins.checked_add(1).expect("disk pin count overflow"); + if let Some(backing) = backing { + backing.pin(); + } + } + Ok(blob.clone()) } BlobEntry::NonResident { @@ -278,15 +301,24 @@ impl BlobSet { .. } => { let new_uses = *current_uses + uses.get(); - let backing = backing.clone(); let frame = self.resident.redeem_blob(reservation); let handle = BlobHandle { frame }; + + let mut backing = backing.clone(); + let mut disk_pins = backing.pins(); + if DiskRetention::is_required(eviction_policy) { + disk_pins = disk_pins.checked_add(1).expect("disk pin count overflow"); + backing.pin(); + } + entry.insert(BlobEntry::Resident { uses: new_uses, blob: handle.clone(), - _backing: Some(backing), pins, + backing: Some(backing), + disk_pins, }); + Ok(handle) } }, @@ -331,8 +363,10 @@ impl BlobSet { { let blob_entry = entry.get_mut(); blob_entry.dec_uses(); - if let EvictionPolicy::NeverEvict = eviction_policy { - blob_entry.dec_pins(); + match eviction_policy { + EvictionPolicy::Never => blob_entry.unpin_mem(), + EvictionPolicy::Memory => blob_entry.unpin_disk(), + EvictionPolicy::Disk => {} } } let blob_entry = entry.get(); @@ -389,7 +423,8 @@ impl BlobSet { uses: *uses, pins: 0, blob: handle.clone(), - _backing: Some(backing.clone()), + disk_pins: backing.pins(), + backing: Some(backing.clone()), }; Ok(handle) } @@ -421,9 +456,13 @@ impl BlobSet { hashes.into_iter().map(|hash| self.get(hash)).collect() } - /// Fault the blob with content address `hash`, and mark it as non-evictable. + /// Fault the blob at `hash` and install a [EvictionPolicy::Never] + /// requirement. + /// + /// This protects resident bytes; if the object is present in local backing + /// storage, it remains evictable there. /// - /// Call this for every reference to the blob, without deduplication. + /// Must be called for every reference to the blob, without deduplication. /// /// Faulting is subject to the resident memory budget. /// @@ -433,9 +472,12 @@ impl BlobSet { self.get(hash).and_then(|handle| self.pin_handle(&handle)) } - /// Mark the supplied blob as non-evictable. + /// Install a [EvictionPolicy::Never] for the supplied blob. + /// + /// This protects resident bytes; if the object is present in local backing + /// storage, it remains evictable there. /// - /// Call this for every reference to the blob, without deduplication. + /// Must be called for every reference to the blob, without deduplication. /// /// The blob must be in this blob set, otherwise a [BlobError::MissingBlob] /// is returned. @@ -463,6 +505,27 @@ impl BlobSet { *pins -= 1; } + /// Prevent the object at `hash` from being evicted from local backing + /// storage. + /// + /// Must be called for every reference to the blob, without deduplication. + pub(crate) fn pin_disk(&self, hash: BlobHashWrapper) { + self.entries + .write() + .get_mut(&hash) + .expect("blob to disk-pin must exist") + .pin_disk() + } + + /// Release one object's local backing storage pin. + pub(crate) fn unpin_disk(&self, hash: BlobHashWrapper) { + self.entries + .write() + .get_mut(&hash) + .expect("blob to disk-pin must exist") + .unpin_disk(); + } + /// Apply a fallible operation to each blob in this set. /// /// Note that non-resident blobs will not be faulted in, but read directly @@ -558,8 +621,12 @@ enum BlobEntry { uses: usize, pins: usize, blob: BlobHandle, - /// Ownership of the immutable version, if written to backing storage. - _backing: Option, + /// `Some` if the entry has been written to local disk. + backing: Option, + /// Disk retention requirements exist before any backing object has been + /// written. When `backing` is `Some`, its local pin contribution + /// matches this value. + disk_pins: u64, }, #[allow(unused)] NonResident { @@ -597,15 +664,45 @@ impl BlobEntry { } } - fn dec_pins(&mut self) { + fn unpin_mem(&mut self) { match self { - Self::NonResident { .. } => unreachable!("attempt to decrement pin count on non-resident blob"), - Self::Resident { pins, .. } if *pins == 0 => panic!("attempt to decrement pin count already at zero"), + Self::NonResident { .. } => { + unreachable!("attempt to decrement pin count on non-resident blob") + } + Self::Resident { pins, .. } if *pins == 0 => { + panic!("attempt to decrement pin count already at zero") + } Self::Resident { pins, .. } => { *pins -= 1; } } } + + fn pin_disk(&mut self) { + match self { + Self::Resident { backing, disk_pins, .. } => { + *disk_pins = disk_pins.checked_add(1).expect("disk pin count overflow"); + if let Some(backing) = backing { + backing.pin(); + } + } + Self::NonResident { backing, .. } => backing.pin(), + } + } + + fn unpin_disk(&mut self) { + match self { + Self::Resident { backing, disk_pins, .. } => { + *disk_pins = disk_pins + .checked_sub(1) + .expect("attempt to decrement disk pin count already at zero"); + if let Some(backing) = backing { + backing.unpin(); + } + } + Self::NonResident { backing, .. } => backing.unpin(), + } + } } impl MemoryUsage for BlobEntry { @@ -769,7 +866,7 @@ mod tests { let mut model = HashMap::, usize)>::new(); for bytes in &blobs { - let handle = set.insert(EvictionPolicy::Evictable, bytes).unwrap(); + let handle = set.insert(EvictionPolicy::Memory, bytes).unwrap(); let hash = BlobHash::hash_from_bytes(bytes); prop_assert_eq!(handle.hash(), hash.into()); prop_assert_eq!(&*handle, bytes.as_slice()); @@ -795,7 +892,7 @@ mod tests { for bytes in blobs { let hash = BlobHash::hash_from_bytes(&bytes); - prop_assert_eq!(set.free_ref(hash.into(), EvictionPolicy::Evictable).unwrap(), bytes.len() as u64); + prop_assert_eq!(set.free_ref(hash.into(), EvictionPolicy::Memory).unwrap(), bytes.len() as u64); } prop_assert_eq!(set.num_blobs(), 0); prop_assert_eq!(set.bytes_used_by_blobs(), 0); @@ -823,9 +920,9 @@ mod tests { let storage = Arc::new(TieredStorage::new_for_test()); let set = BlobSet::new(resident.clone(), storage); - set.insert(EvictionPolicy::Evictable, &first).map(drop).unwrap(); + set.insert(EvictionPolicy::Memory, &first).map(drop).unwrap(); // This should evict `first`, as there is no external handle. - set.insert(EvictionPolicy::Evictable, &second).map(drop).unwrap(); + set.insert(EvictionPolicy::Memory, &second).map(drop).unwrap(); prop_assert_eq!(set.num_blobs(), 2); // The catalog knows both entries, but only the second is resident @@ -862,8 +959,8 @@ mod tests { let storage = Arc::new(TieredStorage::new_for_test()); let set = BlobSet::new(resident.clone(), storage); - let _first_handle = set.insert(EvictionPolicy::Evictable, &first).unwrap(); - prop_assert!(matches!(set.insert(EvictionPolicy::Evictable, &second), Err(BlobError::MemoryLimitExceeded(_)))); + let _first_handle = set.insert(EvictionPolicy::Memory, &first).unwrap(); + prop_assert!(matches!(set.insert(EvictionPolicy::Memory, &second), Err(BlobError::MemoryLimitExceeded(_)))); } } @@ -884,14 +981,14 @@ mod tests { let committed = BlobSet::new(resident.clone(), storage); // Emulate transaction prepare. - transaction.insert(EvictionPolicy::Evictable, 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::Evictable, 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); @@ -900,8 +997,8 @@ mod tests { #[test] fn never_evict_policy_survives_deduplication_in_either_order() { for policies in [ - [EvictionPolicy::NeverEvict, EvictionPolicy::Evictable], - [EvictionPolicy::Evictable, EvictionPolicy::NeverEvict], + [EvictionPolicy::Never, EvictionPolicy::Memory], + [EvictionPolicy::Memory, EvictionPolicy::Never], ] { let bytes = b"shared blob"; let budget = ByteBudget::new(ByteBudgetConfig { @@ -928,7 +1025,7 @@ mod tests { // All caller handles are gone. Only the table policy now prevents // another blob from reclaiming this one's entire memory allowance. assert!(matches!( - set.insert(EvictionPolicy::Evictable, b"replacement"), + set.insert(EvictionPolicy::Memory, b"replacement"), Err(BlobError::MemoryLimitExceeded(_)) )); assert_eq!(set.num_blobs(), 1); @@ -939,7 +1036,7 @@ mod tests { set.free_ref(hash, policy).unwrap(); } assert_eq!(resident.usage().accounted_bytes(), 0); - assert!(set.insert(EvictionPolicy::Evictable, b"replacement").is_ok()); + assert!(set.insert(EvictionPolicy::Memory, b"replacement").is_ok()); } } @@ -948,13 +1045,13 @@ mod tests { let set = BlobSet::new_for_test(); let bytes = b"previously evicted"; let hash = BlobHashWrapper::hash_from_bytes(bytes); - drop(set.insert(EvictionPolicy::Evictable, bytes).unwrap()); + drop(set.insert(EvictionPolicy::Memory, bytes).unwrap()); set.evict(0).unwrap(); assert_eq!(set.resident.usage().accounted_bytes(), 0); // This uses the nonresident insertion path, rather than updating an // existing resident entry. Both paths must preserve the new policy. - drop(set.insert(EvictionPolicy::NeverEvict, bytes).unwrap()); + drop(set.insert(EvictionPolicy::Never, bytes).unwrap()); set.evict(0).unwrap(); assert_eq!(set.resident.usage().accounted_bytes(), bytes.len() as u64); assert_eq!(set.usage_counter().get(&hash), Some(&2)); @@ -966,8 +1063,8 @@ mod tests { let set = BlobSet::new_for_test(); let bytes = b"restored blob"; let hash = BlobHashWrapper::hash_from_bytes(bytes); - drop(set.insert(EvictionPolicy::Evictable, bytes).unwrap()); - drop(set.insert(EvictionPolicy::Evictable, bytes).unwrap()); + drop(set.insert(EvictionPolicy::Memory, bytes).unwrap()); + drop(set.insert(EvictionPolicy::Memory, bytes).unwrap()); set.evict(0).unwrap(); assert_eq!(set.resident.usage().accounted_bytes(), 0); @@ -981,13 +1078,48 @@ mod tests { assert_eq!(&*set.get(hash).unwrap(), bytes); // Releasing one restored owner must retain the other owner's pin. - set.free_ref(hash, EvictionPolicy::NeverEvict).unwrap(); + set.free_ref(hash, EvictionPolicy::Never).unwrap(); assert_eq!(set.usage_counter().get(&hash), Some(&1)); set.evict(0).unwrap(); assert_eq!(set.resident.usage().accounted_bytes(), bytes.len() as u64); - set.free_ref(hash, EvictionPolicy::NeverEvict).unwrap(); + set.free_ref(hash, EvictionPolicy::Never).unwrap(); set.evict(0).unwrap(); assert_eq!(set.resident.usage().accounted_bytes(), 0); assert!(matches!(set.pin(hash), Err(BlobError::MissingBlob(_)))); } + + proptest! { + #[test] + fn removing_memory_row_allows_shared_blob_disk_eviction( + bytes in vec(any::(), 1..128), + ) { + use crate::tiered::{BackingStore, MemoryObjectStore}; + + let storage = Arc::new(TieredStorage::empty( + BackingStore { + object_store: Box::new(MemoryObjectStore::default()), + budget: ByteBudget::unlimited(), + }, + Some(BackingStore { + object_store: Box::new(MemoryObjectStore::default()), + budget: ByteBudget::unlimited(), + }), + )); + let resident = Arc::new(ResidentObjects::new(ByteBudget::unlimited())); + let blobs = BlobSet::new(resident, storage.clone()); + let hash = BlobHashWrapper::hash_from_bytes(&bytes); + drop(blobs.insert(EvictionPolicy::Memory, &bytes).unwrap()); + drop(blobs.insert(EvictionPolicy::Disk, &bytes).unwrap()); + blobs.evict(0).unwrap(); + + // Memory protects the shared disk copy until that row is released. + prop_assert_eq!(storage.evict(0).unwrap(), 0); + blobs.free_ref(hash, EvictionPolicy::Memory).unwrap(); + + // The remaining Disk row permits remote eviction and must remain readable. + prop_assert_eq!(storage.evict(0).unwrap(), bytes.len() as u64); + let recovered = blobs.get(hash).unwrap(); + prop_assert_eq!(&*recovered, bytes.as_slice()); + } + } } diff --git a/crates/table/src/tiered/mod.rs b/crates/table/src/tiered/mod.rs index 22ebdd42e3a..2473fe9563d 100644 --- a/crates/table/src/tiered/mod.rs +++ b/crates/table/src/tiered/mod.rs @@ -32,8 +32,15 @@ pub use self::{ #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum EvictionPolicy { - Evictable, - NeverEvict, + /// Always keep resident in main memory. + /// + /// If a policy migration leaves redundant local disk copies, those can be + /// evicted. + Never, + /// Allow to evict from main memory to local disk. + Memory, + /// Allow to evict from local disk to remote storage. + Disk, } pub struct TieredStorageConfig { @@ -129,12 +136,15 @@ impl TieredDatabaseStorage { } } - /// Attempt to evict from the shared blob set and local storage. - pub fn trim(&self) -> Result<(), TrimError> { - self.blobs.trim()?; - self.store.trim()?; + /// Attempt to free space by reclaiming orphaned objects and evicting from + /// the shared blob set and local storage. + /// + /// Returns the total number of bytes freed. + pub fn trim(&self) -> Result { + let mut bytes_freed = self.blobs.trim()?; + bytes_freed += self.store.trim()?; - Ok(()) + Ok(bytes_freed) } /// Reclaim local disk storage occupied by orphaned objects. diff --git a/crates/table/src/tiered/page_manager.rs b/crates/table/src/tiered/page_manager.rs index f4bc25dae8e..197e4d14e81 100644 --- a/crates/table/src/tiered/page_manager.rs +++ b/crates/table/src/tiered/page_manager.rs @@ -461,7 +461,7 @@ impl PageManager { let inner = self .resident .reserve_page_with_permit(permit, PooledPage::new(page, self.pool.clone())); - self.redeem(ReservedPage { inner, metadata }, EvictionPolicy::Evictable) + self.redeem(ReservedPage { inner, metadata }, EvictionPolicy::Memory) } /// Take a loaded page out of its slot so a memory table can own it directly. @@ -611,10 +611,7 @@ impl PageManager { cached_eviction_policy, &eviction_policy, "eviction policy cannot be changed for resident pages" ); - // Avoid atomics contention if the page is not evictable. - if matches!(eviction_policy, EvictionPolicy::Evictable) { - self.resident.touch_page(&handle.frame); - } + self.resident.touch_page(&handle.frame); Ok(Some(handle.clone())) } @@ -754,8 +751,12 @@ impl PageManager { self.resident.evict_page(victim); } - pub(super) fn ensure_lower_tier_stored(&self, page: &PageHandle) -> Result { - self.storage.write(page.into()) + pub(super) fn ensure_lower_tier_stored( + &self, + page: &PageHandle, + eviction_policy: EvictionPolicy, + ) -> Result { + self.storage.write(page.into(), eviction_policy) } } diff --git a/crates/table/src/tiered/page_set.rs b/crates/table/src/tiered/page_set.rs index 8769665fe3b..b5e389fd56e 100644 --- a/crates/table/src/tiered/page_set.rs +++ b/crates/table/src/tiered/page_set.rs @@ -261,7 +261,7 @@ impl TieredPages { handle: page_handle, metadata, backing, - eviction_policy: _, + eviction_policy, } = &*slot else { continue; @@ -276,7 +276,7 @@ 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)?, + None => manager.ensure_lower_tier_stored(page_handle, *eviction_policy)?, }; *slot = PageSlot::NonResident { metadata: *metadata, @@ -370,11 +370,11 @@ impl PageSet { let old = std::mem::replace(&mut self.storage, PageStorage::Tiered(TieredPages::default())); self.storage = match old { PageStorage::Resident(resident) => { - assert_eq!(policy, EvictionPolicy::Evictable); + assert_eq!(policy, EvictionPolicy::Memory); PageStorage::Tiered(resident.into_tiered(&self.manager, self.fixed_row_size)) } PageStorage::Tiered(tiered) => { - assert_eq!(policy, EvictionPolicy::NeverEvict); + assert_eq!(policy, EvictionPolicy::Never); PageStorage::Resident(tiered.into_resident(&self.manager, self.fixed_row_size)) } }; @@ -422,11 +422,11 @@ impl PageSet { /// Create a fresh, empty page set. pub fn new(manager: Arc, eviction_policy: EvictionPolicy, fixed_row_size: Size) -> Self { let storage = match eviction_policy { - EvictionPolicy::NeverEvict => PageStorage::Resident(ResidentPages { + EvictionPolicy::Never => PageStorage::Resident(ResidentPages { pages: Pages::default(), permits: smallvec::SmallVec::new(), }), - EvictionPolicy::Evictable => PageStorage::Tiered(TieredPages::default()), + EvictionPolicy::Memory | EvictionPolicy::Disk => PageStorage::Tiered(TieredPages::default()), }; Self { eviction_policy, @@ -1475,7 +1475,7 @@ mod tests { PagePool::new_for_test(), Arc::new(TieredStorage::new_for_test()), ); - PageSet::new(Arc::new(manager), EvictionPolicy::Evictable, Size(8)) + PageSet::new(Arc::new(manager), EvictionPolicy::Memory, Size(8)) } #[test] @@ -1517,7 +1517,7 @@ mod tests { PagePool::new_for_test(), storage.clone(), )); - let mut pages = PageSet::new(manager, EvictionPolicy::Evictable, Size(8)); + let mut pages = PageSet::new(manager, EvictionPolicy::Memory, Size(8)); // Persist a clean version and remember its serialized disk footprint. let index = pages.allocate_new_page(Size(8)).unwrap(); @@ -1539,4 +1539,33 @@ mod tests { assert_eq!(storage.reclaim().unwrap(), stored_bytes); assert!(!storage.contains(key)); } + + #[test] + fn reads_refresh_page_recency() { + let budget = ByteBudget::new(ByteBudgetConfig { + tier: CacheTier::Memory, + low_water_bytes: 0, + soft_limit_bytes: 2 * PAGE_SIZE as u64, + hard_limit_bytes: 2 * PAGE_SIZE as u64, + }) + .unwrap(); + let manager = Arc::new(PageManager::new( + Arc::new(ResidentObjects::new(budget)), + PagePool::new_for_test(), + Arc::new(TieredStorage::new_for_test()), + )); + let mut pages = PageSet::new(manager, EvictionPolicy::Disk, Size(8)); + let hot = pages.allocate_new_page(Size(8)).unwrap(); + let cold = pages.allocate_new_page(Size(8)).unwrap(); + for _ in 0..2 { + drop(pages.get_page(hot).unwrap().unwrap()); + } + + pages.evict(PAGE_SIZE as u64).unwrap(); + assert!( + pages.storage.tiered().slots[hot.idx()].is_resident(), + "a repeatedly read Disk-policy page should outlive the unread page" + ); + assert!(!pages.storage.tiered().slots[cold.idx()].is_resident()); + } } diff --git a/crates/table/src/tiered/storage.rs b/crates/table/src/tiered/storage.rs index 82c70298600..85d50a0d875 100644 --- a/crates/table/src/tiered/storage.rs +++ b/crates/table/src/tiered/storage.rs @@ -18,7 +18,7 @@ use crate::{ tiered::{ error::ObjectStoreError, map::{BlobHashWrapper, ObjectKey, ObjectMap, PageHash}, - BlobHandle, BudgetPermit, ByteBudget, PageHandle, + BlobHandle, BudgetPermit, ByteBudget, EvictionPolicy, PageHandle, }, }; @@ -247,36 +247,78 @@ pub type RemoteBackingStore = BackingStore>; type SharedCatalogEntry = Arc; +/// Whether an owner requires the object to survive eviction to the remote tier. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DiskRetention { + Evictable, + Required, +} + +impl DiskRetention { + pub fn is_required(policy: EvictionPolicy) -> bool { + Self::from(policy) == Self::Required + } +} + +impl From for DiskRetention { + fn from(policy: EvictionPolicy) -> Self { + match policy { + // Objects may have been stored on disk before changing the cache + // policy of a table. It is ok to evict those to the remote tier. + EvictionPolicy::Never => Self::Evictable, + // If main memory eviction is allowed, the disk copy must stay. + EvictionPolicy::Memory => Self::Required, + // Object is explicitly evictable. + EvictionPolicy::Disk => Self::Evictable, + } + } +} + #[derive(Debug, Default)] enum ObjectOwnership { #[default] Unreferenced, Referenced { /// The number of owners of this object. + /// + /// Owners may not request pinning, so this number can be greater than + /// `total_pins`. The owner count is tracked so that we can detect the + /// last owner in [Self::release]. owners: NonZeroU64, + /// Sum of all live [DiskObject]s' pin counts. + total_pins: u64, }, } impl ObjectOwnership { - fn retain(&mut self) { + fn is_pinned(&self) -> bool { + matches!(self, Self::Referenced { total_pins: 1.., .. }) + } + + fn retain(&mut self, pins: u64) { *self = match *self { Self::Unreferenced => Self::Referenced { owners: NonZeroU64::MIN, + total_pins: pins, }, - Self::Referenced { owners } => Self::Referenced { + Self::Referenced { owners, total_pins } => Self::Referenced { owners: owners.checked_add(1).expect("owner count overflow"), + total_pins: total_pins.checked_add(pins).expect("pin count overflow"), }, }; } - fn release(&mut self) -> bool { - let Self::Referenced { owners } = *self else { - unreachable!("only a registered handle can release ownership") + fn release(&mut self, pins: u64) -> bool { + let Self::Referenced { owners, total_pins } = *self else { + unreachable!("only a registered handle can release pin counts") }; + assert!(total_pins >= pins); match owners.get() { 1 => { - // The last owner makes the object collectible. + // The last owner has released its pins, + // so the object becomes unreferenced. + assert_eq!(total_pins, pins); *self = Self::Unreferenced; true @@ -284,6 +326,7 @@ impl ObjectOwnership { x => { *self = Self::Referenced { owners: NonZeroU64::new(x - 1).unwrap(), + total_pins: total_pins.checked_sub(pins).expect("pin count underflow"), }; false @@ -306,12 +349,13 @@ struct ObjectState { /// Ownership of an object stored in the [LocalBackingStore]. /// -/// Tracks the backing lifetime across multiple owners. The final owner release -/// makes the object eligible for reclamation. +/// Tracks pins of multiple owners. When pins go to zero, the object can be +/// evicted to the [RemoteBackingStore]. #[derive(Debug)] pub struct DiskObject { key: ObjectKey, slot: SharedCatalogEntry, + pins: u64, // Shared with [TieredStorage], so the object can signal pending // reclamation. should_reclaim: Arc, @@ -321,16 +365,46 @@ impl DiskObject { pub fn key(&self) -> ObjectKey { self.key } + + pub fn pins(&self) -> u64 { + self.pins + } + + /// Prevent eviction of this object's local copy. + /// + /// This only modifies the catalog entry, it is the caller's responsibility + /// to actually write the object. + pub(crate) fn pin(&mut self) { + let pins = self.pins.checked_add(1).expect("pin count overflow"); + self.set_pins(pins); + } + + /// Decrement the pin count for this object. + pub(crate) fn unpin(&mut self) { + let pins = self.pins.checked_sub(1).expect("pin count underflow"); + self.set_pins(pins); + } + + /// Replace the pin count contribution of this object. + /// + /// The caller must ensure that the object is live. + pub(crate) fn set_pins(&mut self, pins: u64) { + let mut state = self.slot.state.lock(); + state.ownership.release(self.pins); + state.ownership.retain(pins); + self.pins = pins; + } } impl Clone for DiskObject { fn clone(&self) -> Self { let mut state = self.slot.state.lock(); - state.ownership.retain(); + state.ownership.retain(self.pins); Self { key: self.key, slot: self.slot.clone(), + pins: self.pins, should_reclaim: self.should_reclaim.clone(), } } @@ -339,7 +413,7 @@ impl Clone for DiskObject { impl Drop for DiskObject { fn drop(&mut self) { let mut state = self.slot.state.lock(); - if state.ownership.release() { + if state.ownership.release(self.pins) { self.should_reclaim.store(true, Ordering::Release); } } @@ -394,11 +468,16 @@ impl TieredStorage { maybe_slot.is_some_and(|slot| slot.state.lock().object.is_some()) } - pub fn write(&self, object: Object) -> Result { + pub fn write(&self, object: Object, retention: impl Into) -> Result { let size = object.size(); let (key, bytes) = object.into_kv(); assert_eq!(size, bytes.len() as u64); + let pins = match retention.into() { + DiskRetention::Evictable => 0, + DiskRetention::Required => 1, + }; + // Establish a [DiskObject] owning the object. // // The following locking protocol applies: @@ -408,7 +487,7 @@ impl TieredStorage { // - increment the slot's `registering` counter (lock-free) // - release the catalog lock // 2. Lock the entry slot and: - // - establish ownership + // - establish local pinning requirements // - decrement the `registering` counter // - release the entry slot // 3. Move the slot into the `DiskObject` owner @@ -416,6 +495,8 @@ impl TieredStorage { // Concurrent reclamation can't proceed during (1), and will skip the // slot before its lock can be acquired in (2). // Waiting for the slot lock doesn't require holding the catalog lock. + // Concurrent eviction could remove the object if it gets the slot lock + // first, but will skip it if we installed local pins in (2). let owner = { let slot = { let mut catalog = self.catalog.write(); @@ -427,7 +508,7 @@ impl TieredStorage { }; { let mut state = slot.state.lock(); - state.ownership.retain(); + state.ownership.retain(pins); // Relaxed ordering is sufficient as we hold the slot lock. let prev = slot.registering.fetch_sub(1, Ordering::Relaxed); @@ -437,6 +518,7 @@ impl TieredStorage { DiskObject { key, slot, + pins, should_reclaim: self.should_reclaim.clone(), } }; @@ -590,6 +672,10 @@ impl TieredStorage { let last_access_epoch = { // If the slot is locked, don't evict it. let state = slot.state.try_lock()?; + // Nor if the object is pinned. + if state.ownership.is_pinned() { + return None; + } // Filter out empty or non-resident slots. let entry = state.object.as_ref()?; entry.permit.as_ref()?; @@ -606,6 +692,10 @@ impl TieredStorage { let Some(mut state) = slot.state.try_lock() else { continue; }; + // Skip if the object got pinned meanwhile. + if state.ownership.is_pinned() { + continue; + } // Stop if we already reached our target. if self.local.budget.usage().accounted_bytes <= target_usage { break; diff --git a/crates/table/src/tiered/storage/tests.rs b/crates/table/src/tiered/storage/tests.rs index b0992e3332e..9fe27e78183 100644 --- a/crates/table/src/tiered/storage/tests.rs +++ b/crates/table/src/tiered/storage/tests.rs @@ -128,7 +128,7 @@ fn assert_restoration_after_removal_keeps_its_permit(overwrite: bool) { }); let storage = storage(local.clone(), Arc::default(), ByteBudget::unlimited()); let object_to_write = object(b"aaaa"); - let owner = storage.write(object_to_write).unwrap(); + let owner = storage.write(object_to_write, DiskRetention::Evictable).unwrap(); let key = owner.key(); let slot = storage.catalog.read().get(&key).unwrap().clone(); let reader_owner = owner.clone(); @@ -141,7 +141,7 @@ fn assert_restoration_after_removal_keeps_its_permit(overwrite: bool) { let reading = storage.clone(); let reader = thread::spawn(move || { if overwrite { - let _rewritten = reading.write(object(b"aaaa"))?; + let _rewritten = reading.write(object(b"aaaa"), DiskRetention::Evictable)?; } let bytes = reading.read(key); drop(reader_owner); @@ -154,7 +154,7 @@ fn assert_restoration_after_removal_keeps_its_permit(overwrite: bool) { // Unrelated keys can still be written while the eviction's I/O is paused. let object_to_write = object(b"bbbb"); - let other_owner = storage.write(object_to_write).unwrap(); + let other_owner = storage.write(object_to_write, DiskRetention::Evictable).unwrap(); let other_key = other_owner.key(); resume.send(()).unwrap(); @@ -187,7 +187,7 @@ fn concurrent_evictions_only_release_one_permit() { }); let storage = storage(local, <_>::default(), ByteBudget::unlimited()); let object_to_write = object(b"aaaa"); - let owner = storage.write(object_to_write).unwrap(); + let owner = storage.write(object_to_write, DiskRetention::Evictable).unwrap(); let key = owner.key(); let first_storage = storage.clone(); @@ -216,10 +216,10 @@ fn remote_read_can_evict_without_holding_its_slot() { let storage = storage(Arc::default(), Arc::default(), budget); let object_to_write = object(b"aaaa"); - let owner = storage.write(object_to_write).unwrap(); + let owner = storage.write(object_to_write, DiskRetention::Evictable).unwrap(); let key = owner.key(); let object_to_write = object(b"bbbb"); - let _other_owner = storage.write(object_to_write).unwrap(); + let _other_owner = storage.write(object_to_write, DiskRetention::Evictable).unwrap(); let (sender, receiver) = mpsc::sync_channel(1); let reading = storage.clone(); @@ -235,10 +235,10 @@ fn overwrites_preserve_the_slot_and_account_once() { let storage = storage(Arc::default(), Arc::default(), ByteBudget::unlimited()); let object_to_write = object(b"aaaa"); - let owner = storage.write(object_to_write).unwrap(); + let owner = storage.write(object_to_write, DiskRetention::Evictable).unwrap(); let key = owner.key(); let slot = storage.catalog.read().get(&key).unwrap().clone(); - let _rewritten = storage.write(object(b"aaaa")).unwrap(); + let _rewritten = storage.write(object(b"aaaa"), DiskRetention::Evictable).unwrap(); assert!(Arc::ptr_eq(&slot, storage.catalog.read().get(&key).unwrap())); assert_eq!(storage.local.budget.usage().accounted_bytes, 4); @@ -254,7 +254,7 @@ fn failed_initial_write_does_not_publish_the_object() { let storage = storage(local.clone(), Arc::default(), ByteBudget::unlimited()); let key = BlobHashWrapper::hash_from_bytes(b"aaaa").into(); - assert!(storage.write(object(b"aaaa")).is_err()); + assert!(storage.write(object(b"aaaa"), DiskRetention::Evictable).is_err()); assert!(!storage.contains(key)); assert!(matches!(storage.stat(key), Err(ObjectStoreError::UnknownObject(_)))); @@ -266,7 +266,7 @@ fn failed_initial_write_does_not_publish_the_object() { storage.reclaim().unwrap(); assert!(storage.catalog.read().is_empty()); local.fail_writes.store(false, Ordering::Relaxed); - let _rewritten = storage.write(object(b"aaaa")).unwrap(); + let _rewritten = storage.write(object(b"aaaa"), DiskRetention::Evictable).unwrap(); assert_eq!(storage.stat(key).unwrap().size, 4); assert_eq!(storage.local.budget.usage().accounted_bytes, 4); } @@ -280,7 +280,7 @@ fn failed_remote_write_preserves_local_bytes_and_permit() { let storage = storage(local.clone(), remote, ByteBudget::unlimited()); let object_to_write = object(b"aaaa"); - let owner = storage.write(object_to_write).unwrap(); + let owner = storage.write(object_to_write, DiskRetention::Evictable).unwrap(); let key = owner.key(); assert!(storage.evict(0).is_err()); @@ -295,7 +295,7 @@ fn eviction_does_nothing_when_target_is_met() { let storage = storage(local.clone(), Arc::default(), ByteBudget::unlimited()); let object_to_write = object(b"aaaa"); - let owner = storage.write(object_to_write).unwrap(); + let owner = storage.write(object_to_write, DiskRetention::Evictable).unwrap(); let key = owner.key(); assert_eq!(storage.evict(4).unwrap(), 0); @@ -311,7 +311,7 @@ fn failed_local_remove_preserves_permit() { let storage = storage(local.clone(), remote, ByteBudget::unlimited()); let object_to_write = object(b"aaaa"); - let owner = storage.write(object_to_write).unwrap(); + let owner = storage.write(object_to_write, DiskRetention::Evictable).unwrap(); let key = owner.key(); assert!(storage.evict(0).is_err()); @@ -321,5 +321,7 @@ fn failed_local_remove_preserves_permit() { } mod blobs; +mod model; +mod ownership; mod races; mod reclamation; diff --git a/crates/table/src/tiered/storage/tests/blobs.rs b/crates/table/src/tiered/storage/tests/blobs.rs index 101a83296b3..617fcea62ab 100644 --- a/crates/table/src/tiered/storage/tests/blobs.rs +++ b/crates/table/src/tiered/storage/tests/blobs.rs @@ -1,11 +1,11 @@ use super::*; -use crate::tiered::EvictionPolicy; use proptest::prelude::*; proptest! { #[test] fn resident_data_survives_a_failed_first_write( bytes in proptest::collection::vec(any::(), 1..128), + required in any::(), restored in any::(), ) { use crate::tiered::{blob_set::BlobMap, BlobSet, ResidentObjects}; @@ -14,7 +14,11 @@ proptest! { let storage = storage(local.clone(), Arc::default(), ByteBudget::unlimited()); let resident = Arc::new(ResidentObjects::new(ByteBudget::unlimited())); let hash = BlobHashWrapper::hash_from_bytes(&bytes); - let policy = EvictionPolicy::Evictable; + let policy = if required { + EvictionPolicy::Memory + } else { + EvictionPolicy::Disk + }; let blobs = if restored { let mut map = BlobMap::default(); map.insert_with_uses( @@ -22,7 +26,12 @@ proptest! { std::num::NonZeroUsize::MIN, bytes.clone().into(), ); - BlobSet::from_blob_map(resident, storage.clone(), map) + let blobs = BlobSet::from_blob_map(resident, storage.clone(), map); + // Snapshot restore installs the Memory row's requirement before trimming. + if required { + blobs.pin_disk(hash); + } + blobs } else { let blobs = BlobSet::new(resident, storage.clone()); drop(blobs.insert(policy, &bytes).unwrap()); @@ -42,10 +51,17 @@ proptest! { prop_assert_eq!(&*recovered, bytes.as_slice()); drop(recovered); - // The retry transfers ownership into persisted backing. + // The retry transfers ownership and the row's requirement into persisted backing. local.fail_writes.store(false, Ordering::Relaxed); prop_assert_eq!(blobs.evict(0).unwrap(), bytes.len() as u64); prop_assert_eq!(blobs.resident_bytes_used_by_blobs(), 0); + let slot = storage + .catalog + .read() + .get(&ObjectKey::from(hash)) + .unwrap() + .clone(); + prop_assert_eq!(slot.state.lock().ownership.is_pinned(), required); let recovered = blobs.get(hash).unwrap(); prop_assert_eq!(&*recovered, bytes.as_slice()); drop(recovered); @@ -56,6 +72,95 @@ proptest! { } } +proptest! { + #[test] + fn snapshot_restore_preserves_repeated_disk_requirements( + bytes in proptest::collection::vec(any::(), 1..128), + required_rows in 0u8..8, + ) { + use crate::tiered::{blob_set::BlobMap, BlobSet, ResidentObjects}; + + let storage = Arc::new(TieredStorage::new_for_test()); + let resident = Arc::new(ResidentObjects::new(ByteBudget::unlimited())); + let hash = BlobHashWrapper::hash_from_bytes(&bytes); + let uses = std::num::NonZeroUsize::new(usize::from(required_rows) + 1).unwrap(); + let mut restored = BlobMap::default(); + restored.insert_with_uses(&hash.into(), uses, bytes.clone().into()); + let blobs = BlobSet::from_blob_map(resident, storage.clone(), restored); + + // Restore one Memory requirement per row; the additional row has Disk policy. + for _ in 0..required_rows { + blobs.pin_disk(hash); + } + prop_assert!(!storage.contains(hash.into())); + blobs.evict(0).unwrap(); + let slot = storage + .catalog + .read() + .get(&ObjectKey::from(hash)) + .unwrap() + .clone(); + prop_assert_eq!(slot.state.lock().ownership.is_pinned(), required_rows > 0); + + // Faulting and evicting again must preserve all restored requirements. + let recovered = blobs.get(hash).unwrap(); + prop_assert_eq!(&*recovered, bytes.as_slice()); + drop(recovered); + blobs.evict(0).unwrap(); + for _ in 0..required_rows { + blobs.free_ref(hash, EvictionPolicy::Memory).unwrap(); + } + prop_assert!(!slot.state.lock().ownership.is_pinned()); + + // The final Disk row owns the backing until it too is released. + prop_assert_eq!(storage.reclaim().unwrap(), 0); + blobs.free_ref(hash, EvictionPolicy::Disk).unwrap(); + prop_assert_eq!(storage.reclaim().unwrap(), bytes.len() as u64); + prop_assert!(storage.catalog.read().is_empty()); + } +} + +#[test] +fn shared_disk_requirements_survive_fault_and_eviction() { + use crate::tiered::{BlobSet, EvictionPolicy, ResidentObjects}; + for policies in [ + [EvictionPolicy::Memory, EvictionPolicy::Disk], + [EvictionPolicy::Disk, EvictionPolicy::Memory], + ] { + let local = Arc::new(TestStore::default()); + let remote = Arc::new(TestStore::default()); + let storage = storage(local.clone(), remote.clone(), ByteBudget::unlimited()); + let blobs = BlobSet::new(Arc::new(ResidentObjects::new(ByteBudget::unlimited())), storage.clone()); + let hash = BlobHashWrapper::hash_from_bytes(b"shared"); + + // Insertion order cannot let an evictable row downgrade a local requirement. + for policy in policies { + drop(blobs.insert(policy, b"shared").unwrap()); + } + + blobs.evict(0).unwrap(); + assert_eq!(storage.evict(0).unwrap(), 0); + assert!(local.stat(hash.into()).unwrap().is_some()); + assert!(remote.stat(hash.into()).unwrap().is_none()); + + // Faulting and re-evicting must transfer the current requirement. + drop(blobs.get(hash).unwrap()); + blobs.evict(0).unwrap(); + assert_eq!(storage.evict(0).unwrap(), 0); + + // The remaining evictable row still needs the bytes after the local pin ends. + blobs.free_ref(hash, EvictionPolicy::Memory).unwrap(); + assert_eq!(storage.evict(0).unwrap(), 6); + assert_eq!(&*blobs.get(hash).unwrap(), b"shared"); + + // Releasing that final row makes the local copy collectible. + blobs.free_ref(hash, EvictionPolicy::Disk).unwrap(); + storage.reclaim().unwrap(); + assert!(!storage.contains(hash.into())); + assert!(local.stat(hash.into()).unwrap().is_none()); + } +} + #[test] fn dropping_one_set_preserves_anothers_backing() { use crate::tiered::{BlobSet, EvictionPolicy, ResidentObjects}; @@ -66,9 +171,9 @@ fn dropping_one_set_preserves_anothers_backing() { let hash = BlobHashWrapper::hash_from_bytes(b"shared"); // Give both sets independent backing owners for the same content. - drop(first.insert(EvictionPolicy::Evictable, b"shared").unwrap()); + drop(first.insert(EvictionPolicy::Disk, b"shared").unwrap()); first.evict(0).unwrap(); - drop(second.insert(EvictionPolicy::Evictable, b"shared").unwrap()); + drop(second.insert(EvictionPolicy::Memory, b"shared").unwrap()); second.evict(0).unwrap(); // Destroying a set must not invalidate another set's nonresident entry. diff --git a/crates/table/src/tiered/storage/tests/model.rs b/crates/table/src/tiered/storage/tests/model.rs new file mode 100644 index 00000000000..5b2d4e062b1 --- /dev/null +++ b/crates/table/src/tiered/storage/tests/model.rs @@ -0,0 +1,143 @@ +use super::*; +use proptest::prelude::*; + +#[derive(Clone, Debug)] +struct ModelOwner { + object: DiskObject, + expected_pins: u64, +} + +#[derive(Clone, Debug)] +enum OwnershipAction { + Write, + Clone(u8), + Pin(u8), + Unpin(u8), + Release(u8), + Reclaim, + Evict, + ReclaimWithFailedRemoval, +} + +fn ownership_action() -> impl Strategy { + prop_oneof![ + Just(OwnershipAction::Write), + any::().prop_map(OwnershipAction::Clone), + any::().prop_map(OwnershipAction::Pin), + any::().prop_map(OwnershipAction::Unpin), + any::().prop_map(OwnershipAction::Release), + Just(OwnershipAction::Reclaim), + Just(OwnershipAction::Evict), + Just(OwnershipAction::ReclaimWithFailedRemoval), + ] +} + +proptest! { + #[test] + fn ownership_actions_preserve_data_and_disk_accounting( + bytes in proptest::collection::vec(any::(), 1..64), + actions in proptest::collection::vec(ownership_action(), 1..96), + ) { + let local = Arc::new(TestStore::default()); + let remote = Arc::new(TestStore::default()); + let storage = storage(local.clone(), remote.clone(), ByteBudget::unlimited()); + let object_to_write = object(&bytes); + let first = storage + .write(object_to_write, DiskRetention::Evictable) + .unwrap(); + let key = first.key(); + + // The model tracks requirements per handle, independently of catalog state. + let mut owners = vec![ModelOwner { + object: first, + expected_pins: 0, + }]; + for action in actions { + match action { + OwnershipAction::Write => { + let object_to_write = object(&bytes); + let owner = storage + .write(object_to_write, DiskRetention::Evictable) + .unwrap(); + owners.push(ModelOwner { + object: owner, + expected_pins: 0, + }); + } + OwnershipAction::Clone(selector) if !owners.is_empty() => { + let index = usize::from(selector) % owners.len(); + owners.push(owners[index].clone()); + } + OwnershipAction::Pin(selector) if !owners.is_empty() => { + let index = usize::from(selector) % owners.len(); + + // Fulfil the caller's obligation to provide local or resident bytes. + let object_to_write = object(&bytes); + let resident = storage + .write(object_to_write, DiskRetention::Evictable) + .unwrap(); + owners[index].object.pin(); + owners[index].expected_pins += 1; + drop(resident); + } + OwnershipAction::Unpin(selector) if !owners.is_empty() => { + let index = usize::from(selector) % owners.len(); + if owners[index].expected_pins > 0 { + owners[index].object.unpin(); + owners[index].expected_pins -= 1; + } + } + OwnershipAction::Release(selector) if !owners.is_empty() => { + let index = usize::from(selector) % owners.len(); + owners.swap_remove(index); + } + OwnershipAction::Reclaim => { + storage.reclaim().unwrap(); + if owners.is_empty() { + prop_assert!(!storage.contains(key)); + prop_assert!(local.stat(key).unwrap().is_none()); + } + } + OwnershipAction::Evict => { + storage.evict(0).unwrap(); + if !owners.is_empty() && owners.iter().all(|owner| owner.expected_pins == 0) { + prop_assert!(local.stat(key).unwrap().is_none()); + prop_assert!(remote.stat(key).unwrap().is_some()); + } + } + OwnershipAction::ReclaimWithFailedRemoval => { + // Removal failures preserve both catalog visibility and byte accounting. + let existed = storage.contains(key); + let usage = storage.local.budget.usage().accounted_bytes; + local.fail_remove.store(true, Ordering::Relaxed); + let result = storage.reclaim(); + prop_assert_eq!(result.is_err(), existed && owners.is_empty()); + prop_assert_eq!(storage.local.budget.usage().accounted_bytes, usage); + prop_assert_eq!(storage.contains(key), existed); + local.fail_remove.store(false, Ordering::Relaxed); + } + _ => {} + } + + // A live owner preserves reachability; any local requirement preserves the file. + let local_present = local.stat(key).unwrap().is_some(); + if !owners.is_empty() { + prop_assert!(storage.contains(key)); + prop_assert!(local_present || remote.stat(key).unwrap().is_some()); + } + if owners.iter().any(|owner| owner.expected_pins > 0) { + prop_assert!(local_present); + } + + let expected_usage = if local_present { bytes.len() as u64 } else { 0 }; + prop_assert_eq!(storage.local.budget.usage().accounted_bytes, expected_usage); + } + + // Every sequence must leave no local reservation after its final release. + drop(owners); + storage.reclaim().unwrap(); + prop_assert!(!storage.contains(key)); + prop_assert!(local.stat(key).unwrap().is_none()); + prop_assert_eq!(storage.local.budget.usage().accounted_bytes, 0); + } +} diff --git a/crates/table/src/tiered/storage/tests/ownership.rs b/crates/table/src/tiered/storage/tests/ownership.rs new file mode 100644 index 00000000000..1fcb19699fa --- /dev/null +++ b/crates/table/src/tiered/storage/tests/ownership.rs @@ -0,0 +1,212 @@ +use super::*; +use proptest::prelude::*; + +proptest! { + #[test] + fn write_returns_readable_backing_with_requested_retention( + bytes in proptest::collection::vec(any::(), 1..128), + retention in prop_oneof![ + Just(DiskRetention::Evictable), + Just(DiskRetention::Required), + ], + ) { + let local = Arc::new(TestStore::default()); + let storage = storage(local.clone(), Arc::default(), ByteBudget::unlimited()); + let reference = storage.write(object(&bytes), retention).unwrap(); + let key = reference.key(); + + // Success publishes readable bytes together with their lifetime and retention. + prop_assert!(storage.contains(key)); + prop_assert_eq!( + reference.pins(), + u64::from(retention == DiskRetention::Required) + ); + prop_assert_eq!( + storage.local.budget.usage().accounted_bytes, + bytes.len() as u64 + ); + prop_assert_eq!(storage.reclaim().unwrap(), 0); + let recovered = storage.read(key).unwrap(); + prop_assert_eq!(recovered.as_ref(), bytes.as_slice()); + + drop(reference); + prop_assert_eq!(storage.reclaim().unwrap(), bytes.len() as u64); + prop_assert!(storage.catalog.read().is_empty()); + prop_assert_eq!(storage.local.budget.usage().accounted_bytes, 0); + } +} + +proptest! { + #[test] + fn local_pins_block_remote_eviction( + bytes in proptest::collection::vec(any::(), 1..128), + pinned_owner_count in 1u8..16, + ) { + // One object's exact capacity must also suffice for deduplicated writes. + let local = Arc::new(TestStore::default()); + let remote = Arc::new(TestStore::default()); + let size = bytes.len() as u64; + let budget = ByteBudget::new(ByteBudgetConfig { + tier: crate::tiered::metrics::CacheTier::Disk, + low_water_bytes: 0, + soft_limit_bytes: size, + hard_limit_bytes: size, + }) + .unwrap(); + let storage = storage(local.clone(), remote.clone(), budget); + let object_to_write = object(&bytes); + let pinned = storage + .write(object_to_write, DiskRetention::Required) + .unwrap(); + let object_to_write = object(&bytes); + let shared = storage + .write(object_to_write, DiskRetention::Evictable) + .unwrap(); + let key = pinned.key(); + let mut owners = (0..pinned_owner_count) + .map(|_| pinned.clone()) + .collect::>(); + drop(pinned); + + // Each remaining required owner independently blocks remote-only eviction. + for _ in 0..pinned_owner_count { + prop_assert_eq!(storage.evict(0).unwrap(), 0); + prop_assert!(local.stat(key).unwrap().is_some()); + prop_assert!(remote.stat(key).unwrap().is_none()); + owners.pop(); + } + + // The evictable owner preserves the bytes after the local requirement ends. + prop_assert_eq!(storage.evict(0).unwrap(), size); + prop_assert!(local.stat(key).unwrap().is_none()); + prop_assert!(remote.stat(key).unwrap().is_some()); + let restored = storage.read(key).unwrap(); + prop_assert_eq!(restored.as_ref(), bytes.as_slice()); + + // Local lifetime tracking must not delete a retained remote snapshot object. + drop(shared); + storage.reclaim().unwrap(); + prop_assert!(!storage.contains(key)); + prop_assert!(remote.stat(key).unwrap().is_some()); + } +} + +proptest! { + #[test] + fn retention_policy_applies_to_pages_and_blobs( + policy in prop_oneof![ + Just(EvictionPolicy::Never), + Just(EvictionPolicy::Memory), + Just(EvictionPolicy::Disk), + ], + is_page in any::(), + bytes in proptest::collection::vec(any::(), 1..128), + ) { + use crate::{ + page_pool::PagePool, + tiered::{PageManager, ResidentObjects}, + }; + use spacetimedb_sats::layout::Size; + + let local = Arc::new(TestStore::default()); + let remote = Arc::new(TestStore::default()); + let storage = storage(local.clone(), remote.clone(), ByteBudget::unlimited()); + + // The same retention conversion governs serialized page versions and blobs. + let object = if is_page { + let manager = PageManager::new( + Arc::new(ResidentObjects::new(ByteBudget::unlimited())), + PagePool::new_for_test(), + storage.clone(), + ); + let slot = manager.allocate(Size(8), policy).unwrap(); + let handle = slot.page().unwrap(); + Object::from(&handle) + } else { + object(&bytes) + }; + let object_to_write = object; + let owner = storage.write(object_to_write, policy).unwrap(); + let key = owner.key(); + let original = storage.read(key).unwrap(); + prop_assert_eq!(key.as_page_hash().is_some(), is_page); + + // Only Memory requires local backing. Never retains bytes in memory, so disk + // copies left by earlier policies may be evicted just like Disk backing. + let freed = storage.evict(0).unwrap(); + match policy { + EvictionPolicy::Memory => { + prop_assert_eq!(freed, 0); + prop_assert!(local.stat(key).unwrap().is_some()); + prop_assert!(remote.stat(key).unwrap().is_none()); + } + EvictionPolicy::Never | EvictionPolicy::Disk => { + prop_assert_eq!(freed, original.len() as u64); + prop_assert!(local.stat(key).unwrap().is_none()); + prop_assert!(remote.stat(key).unwrap().is_some()); + } + } + let recovered = storage.read(key).unwrap(); + prop_assert_eq!(recovered.as_ref(), original.as_ref()); + + // Reclamation still releases any local copy populated by the read above. + drop(owner); + storage.reclaim().unwrap(); + prop_assert!(local.stat(key).unwrap().is_none()); + prop_assert!(!storage.contains(key)); + prop_assert_eq!(storage.local.budget.usage().accounted_bytes, 0); + } +} + +proptest! { + #[test] + fn changing_pins_preserves_all_owner_contributions( + pins in 0u64..16, + extra_owners in 0u8..8, + ) { + let storage = TieredStorage::new_for_test(); + let mut owner = storage + .write(object(b"shared"), DiskRetention::Evictable) + .unwrap(); + let unpinned_clones = (0..extra_owners).map(|_| owner.clone()).collect::>(); + let slot = owner.slot.clone(); + let counts = || { + let state = slot.state.lock(); + match state.ownership { + ObjectOwnership::Referenced { owners, total_pins } => (owners.get(), total_pins), + ObjectOwnership::Unreferenced => (0, 0), + } + }; + let owners = 1 + u64::from(extra_owners); + + // Replacement must preserve ownership, including when this is the sole owner. + owner.set_pins(pins); + proptest::prop_assert_eq!(owner.pins(), pins); + proptest::prop_assert_eq!(counts(), (owners, pins)); + let mut pinned_clone = owner.clone(); + proptest::prop_assert_eq!(counts(), (owners + 1, pins * 2)); + + // Incremental adjustments use replacement without losing another handle's pins. + owner.pin(); + proptest::prop_assert_eq!(counts(), (owners + 1, pins * 2 + 1)); + owner.unpin(); + proptest::prop_assert_eq!(owner.pins(), pins); + proptest::prop_assert_eq!(counts(), (owners + 1, pins * 2)); + owner.set_pins(0); + proptest::prop_assert_eq!(owner.pins(), 0); + proptest::prop_assert_eq!(pinned_clone.pins(), pins); + proptest::prop_assert_eq!(counts(), (owners + 1, pins)); + pinned_clone.set_pins(0); + proptest::prop_assert_eq!(counts(), (owners + 1, 0)); + proptest::prop_assert!(!storage.should_reclaim.load(Ordering::Acquire)); + + // Only the final handle release may request reclamation. + drop(pinned_clone); + drop(unpinned_clones); + proptest::prop_assert_eq!(counts(), (1, 0)); + proptest::prop_assert!(!storage.should_reclaim.load(Ordering::Acquire)); + drop(owner); + proptest::prop_assert_eq!(counts(), (0, 0)); + proptest::prop_assert!(storage.should_reclaim.load(Ordering::Acquire)); + } +} diff --git a/crates/table/src/tiered/storage/tests/races.rs b/crates/table/src/tiered/storage/tests/races.rs index f333aeba344..b8ea35ab3f3 100644 --- a/crates/table/src/tiered/storage/tests/races.rs +++ b/crates/table/src/tiered/storage/tests/races.rs @@ -9,7 +9,7 @@ fn pending_writer_prevents_slot_reclamation() { // Pause registration before it can acquire ownership of an otherwise unowned slot. let writing = storage.clone(); - let writer = thread::spawn(move || writing.write(object(b"aaaa"))); + let writer = thread::spawn(move || writing.write(object(b"aaaa"), DiskRetention::Required)); wait_for_pending_writer(&slot); // Collection must skip the reservation without waiting for its object lock. @@ -29,6 +29,58 @@ fn pending_writer_prevents_slot_reclamation() { assert!(storage.catalog.read().is_empty()); } +#[test] +fn policy_change_during_write_controls_eviction() { + use crate::tiered::{BlobSet, ResidentObjects}; + + for require_memory in [false, true] { + let (pause, reached, resume) = pause(); + let local = Arc::new(TestStore { + after_write: Some(pause), + ..<_>::default() + }); + let storage = storage(local.clone(), Arc::default(), ByteBudget::unlimited()); + let resident = Arc::new(ResidentObjects::new(ByteBudget::unlimited())); + let blobs = Arc::new(BlobSet::new(resident, storage.clone())); + let hash = BlobHashWrapper::hash_from_bytes(b"shared"); + drop(blobs.insert(EvictionPolicy::Disk, b"shared").unwrap()); + + // Stop the first write while the blob's entry still owns only resident bytes. + let evicting = blobs.clone(); + let eviction = thread::spawn(move || evicting.evict(0)); + reached.recv_timeout(TIMEOUT).unwrap(); + + // Install the new requirement while I/O holds no blob catalog lock. + if require_memory { + // Never must cancel eviction even though writing has already started. + blobs.pin(hash).unwrap(); + } else { + // Memory must protect the completed disk copy before memory is released. + blobs.pin_disk(hash); + } + resume.send(()).unwrap(); + let freed = eviction.join().unwrap().unwrap(); + + if require_memory { + assert_eq!(freed, 0); + assert!(blobs.resident_bytes_used_by_blobs() >= 6); + // The unused write reference was released; its redundant copy is collectible. + assert_eq!(storage.reclaim().unwrap(), 6); + } else { + assert_eq!(freed, 6); + assert_eq!(blobs.resident_bytes_used_by_blobs(), 0); + assert_eq!(storage.evict(0).unwrap(), 0); + assert!(local.stat(hash.into()).unwrap().is_some()); + } + assert_eq!(&*blobs.get(hash).unwrap(), b"shared"); + + drop(blobs); + storage.reclaim().unwrap(); + assert!(storage.catalog.read().is_empty()); + assert_eq!(storage.local.budget.usage().accounted_bytes, 0); + } +} + #[test] fn write_during_reclamation_uses_replacement_slot() { let (pause, reached, resume) = pause(); @@ -38,7 +90,7 @@ fn write_during_reclamation_uses_replacement_slot() { }); let storage = storage(local.clone(), Arc::default(), ByteBudget::unlimited()); let object_to_write = object(b"aaaa"); - let owner = storage.write(object_to_write).unwrap(); + let owner = storage.write(object_to_write, DiskRetention::Evictable).unwrap(); let key = owner.key(); // Pause after the file disappears while collection still excludes new owners. @@ -52,7 +104,7 @@ fn write_during_reclamation_uses_replacement_slot() { let writing = storage.clone(); let writer = thread::spawn(move || { let object_to_write = object(b"aaaa"); - let owner = writing.write(object_to_write)?; + let owner = writing.write(object_to_write, DiskRetention::Required)?; Ok::<_, ObjectStoreError>(owner) }); @@ -71,7 +123,7 @@ fn write_during_reclamation_uses_replacement_slot() { #[test] fn pending_registration_protects_an_unlocked_slot() { let storage = TieredStorage::new_for_test(); - let garbage = storage.write(object(b"garbage")).unwrap(); + let garbage = storage.write(object(b"garbage"), DiskRetention::Evictable).unwrap(); drop(garbage); // Pause a writer immediately after catalog lookup, before it takes the slot lock. diff --git a/crates/table/src/tiered/storage/tests/reclamation.rs b/crates/table/src/tiered/storage/tests/reclamation.rs index 66e3438f705..870da8bc2bd 100644 --- a/crates/table/src/tiered/storage/tests/reclamation.rs +++ b/crates/table/src/tiered/storage/tests/reclamation.rs @@ -13,7 +13,7 @@ proptest! { // Failure returns no owner and publishes neither bytes nor a permit. local.fail_writes.store(true, Ordering::Relaxed); prop_assert!(storage - .write(object(&bytes)) + .write(object(&bytes), DiskRetention::Required) .is_err()); prop_assert!(!storage.contains(key)); prop_assert!(local.stat(key).unwrap().is_none()); @@ -26,7 +26,7 @@ proptest! { // Retrying establishes a fresh backing lifetime. local.fail_writes.store(false, Ordering::Relaxed); let reference = storage - .write(object(&bytes)) + .write(object(&bytes), DiskRetention::Evictable) .unwrap(); prop_assert!(storage.contains(key)); drop(reference); @@ -45,7 +45,7 @@ proptest! { let storage = TieredStorage::new_for_test(); let object_to_write = object(&bytes); let first = storage - .write(object_to_write) + .write(object_to_write, DiskRetention::Evictable) .unwrap(); let key = first.key(); let owners = (0..owner_count) @@ -54,7 +54,7 @@ proptest! { first.clone() } else { storage - .write(object(&bytes)) + .write(object(&bytes), DiskRetention::Evictable) .unwrap() } }) @@ -84,7 +84,7 @@ proptest! { let storage = storage(local.clone(), Arc::default(), ByteBudget::unlimited()); let object_to_write = object(&bytes); let owner = storage - .write(object_to_write) + .write(object_to_write, DiskRetention::Required) .unwrap(); let key = owner.key(); @@ -100,7 +100,7 @@ proptest! { // A new owner cancels pending deletion until it releases the object again. let revived = storage - .write(object(&bytes)) + .write(object(&bytes), DiskRetention::Evictable) .unwrap(); local.fail_remove.store(false, Ordering::Relaxed); prop_assert_eq!(storage.reclaim().unwrap(), 0); @@ -115,7 +115,7 @@ proptest! { #[test] fn busy_slots_are_retried_after_unlock() { let storage = Arc::new(TieredStorage::new_for_test()); - let owner = storage.write(object(b"aaaa")).unwrap(); + let owner = storage.write(object(b"aaaa"), DiskRetention::Required).unwrap(); let key = owner.key(); let slot = storage.catalog.read().get(&key).unwrap().clone(); drop(owner); @@ -147,7 +147,7 @@ fn full_disk_reclaims_unreferenced_objects() { }) .unwrap(); let storage = storage(Arc::default(), Arc::default(), budget); - let owner = storage.write(object(b"aaaa")).unwrap(); + let owner = storage.write(object(b"aaaa"), DiskRetention::Required).unwrap(); let old_key = owner.key(); drop(owner); @@ -155,7 +155,9 @@ fn full_disk_reclaims_unreferenced_objects() { let (sender, receiver) = mpsc::sync_channel(1); let writing = storage.clone(); let writer = thread::spawn(move || { - sender.send(writing.write(object(b"bbbb"))).unwrap(); + sender + .send(writing.write(object(b"bbbb"), DiskRetention::Required)) + .unwrap(); }); let owner = receiver.recv_timeout(TIMEOUT).unwrap().unwrap(); writer.join().unwrap();