Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 3 additions & 7 deletions crates/datastore/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use spacetimedb_sats::{AlgebraicType, AlgebraicValue};
use spacetimedb_schema::def::error::LibError;
#[cfg(feature = "durability")]
use spacetimedb_snapshot::SnapshotError;
use spacetimedb_table::tiered;
use spacetimedb_table::tiered::{self, EvictionError};
use spacetimedb_table::{
bflatn_to, read_column,
table::{self, ReadViaBsatnError, UniqueConstraintViolation},
Expand Down Expand Up @@ -52,10 +52,6 @@ pub enum DatastoreError {
}

impl DatastoreError {
pub(crate) fn is_resident_memory_limit(&self) -> bool {
self.resident_memory_limit().is_some()
}

pub fn resident_memory_limit(&self) -> Option<&tiered::BudgetExceeded> {
match self {
Self::Page(PageError::MemoryLimitExceeded(error))
Expand Down Expand Up @@ -137,10 +133,10 @@ pub enum TableError {

#[derive(Error, Debug)]
pub enum TrimTableError {
#[error(transparent)]
Pages(#[from] PageError),
#[error(transparent)]
Storage(#[from] tiered::TrimError),
#[error(transparent)]
Eviction(#[from] EvictionError),
}

#[derive(Error, Debug, PartialEq, Eq)]
Expand Down
69 changes: 6 additions & 63 deletions crates/datastore/src/locking_tx_datastore/committed_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ use spacetimedb_schema::{
use spacetimedb_table::{
blob_store::BlobHash,
indexes::{RowPointer, SquashedOffset},
table::{self, PreparedBlobRelease, PreparedEvictionPolicy, ReadEviction, RowRef, Table, TableAndIndex},
table::{PreparedBlobRelease, PreparedEvictionPolicy, RowRef, Table, TableAndIndex},
tiered::{BlobHandle, BlobSet, EvictionPolicy, PreparedCommit, TieredDatabaseStorage},
};
use std::{collections::BTreeMap, iter};
Expand Down Expand Up @@ -157,12 +157,6 @@ impl MemoryUsage for CommittedState {
}
}

impl ReadEviction for CommittedState {
fn evict_for_read(&self) -> std::result::Result<(), table::TableError> {
self.trim_resident()
}
}

impl StateView for CommittedState {
type Iter<'a> = TableScanIter<'a>;
type IterByColRange<'a, R: RangeBounds<AlgebraicValue>> = IterByColRangeTx<'a, R>;
Expand Down Expand Up @@ -464,20 +458,14 @@ impl CommittedState {

/// Returns an iterator doing a full table scan on `table_id`.
pub(super) fn table_scan<'a>(&'a self, table_id: TableId) -> Option<TableScanIter<'a>> {
Some(
self.get_table(table_id)?
.scan_rows(self.storage.blobs())
.with_read_eviction(self)
.err_into(),
)
Some(self.get_table(table_id)?.scan_rows(self.storage.blobs()).err_into())
}

/// Returns an index for `table_id` on `cols`, if any.
pub(super) fn get_index_by_cols(&self, table_id: TableId, cols: &ColList) -> Option<TableAndIndex<'_>> {
self.tables
.get(&table_id)?
.get_index_by_cols_with_table(self.storage.blobs(), cols)
.map(|index| index.with_read_eviction(self))
}

/// Returns the table associated with the given `index_id`, if any.
Expand All @@ -490,7 +478,6 @@ impl CommittedState {
self.tables
.get(&table_id)?
.get_index_by_id_with_table(self.storage.blobs(), index_id)
.map(|index| index.with_read_eviction(self))
}

// TODO(perf, deep-integration): Make this method `unsafe`. Add the following to the docs:
Expand All @@ -515,21 +502,11 @@ impl CommittedState {
.get_table(table_id)
.expect("Attempt to get COMMITTED_STATE row from table not present in tables.");
// TODO(perf, deep-integration): Use `get_row_ref_unchecked`.
Ok(self
.retry_read(|| Ok(table.get_row_ref(self.storage.blobs(), row_ptr)?))?
Ok(table
.get_row_ref(self.storage.blobs(), row_ptr)?
.expect("row pointer to be present"))
}

pub(super) fn retry_read<T>(&self, mut read: impl FnMut() -> Result<T>) -> Result<T> {
match read() {
Err(error) if error.is_resident_memory_limit() => {
self.trim_resident()?;
read()
}
result => result,
}
}

/// True if the transaction `(tx_data, ctx)` will be written to the commitlog,
/// and therefore consumes a value from `self.next_tx_offset`.
///
Expand Down Expand Up @@ -766,17 +743,7 @@ impl CommittedState {
view_instances: ViewInstanceTxState,
ctx: &ExecutionContext,
) -> Result<TxData> {
let preparation = self.prepare_merge(&tx_state).or_else(|error| {
if error.is_resident_memory_limit() {
// Preparation hit the memory limit.
// Try to evict resident pages and then prepare again.
self.trim_resident()?;
self.prepare_merge(&tx_state)
} else {
Err(error)
}
});
let prepared = match preparation {
let prepared = match self.prepare_merge(&tx_state) {
Ok(prepared) => prepared,
Err(error) => {
self.rollback(tx_state);
Expand Down Expand Up @@ -1226,35 +1193,11 @@ impl CommittedState {
.set(self.storage.blobs().bytes_used_by_blobs() as _);
}

/// Evict objects from the cache until the resident size is below the low watermark,
/// or no more objects can be evicted.
///
/// TODO: Use a database-scoped LRU eviction policy instead of evicting table by table.
pub(super) fn trim_resident(&self) -> std::result::Result<(), table::TableError> {
let pages = self.storage.pages();
let target = pages.resident_budget().low_water_bytes;
for table in self.tables.values() {
if pages.resident_usage().accounted_bytes() <= target {
return Ok(());
}
table.trim()?;
}
if pages.resident_usage().accounted_bytes() > target {
self.storage.blobs().trim()?;
}
Ok(())
}

/// Evict live objects when under budget pressure, and reclaim space used by
/// orphaned objects.
#[cfg(feature = "durability")]
pub(super) fn trim(&self) -> std::result::Result<(), crate::error::TrimTableError> {
for table in self.tables.values() {
table.trim()?;
}
self.storage.trim()?;

Ok(())
self.storage.trim().map(drop).map_err(Into::into)
}

/// Reclaim space used by orphaned objects.
Expand Down
45 changes: 9 additions & 36 deletions crates/datastore/src/locking_tx_datastore/mut_tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -617,7 +617,7 @@ pub struct MutTxId {
}

// The transaction-local blob map is inline to avoid an allocation when empty.
static_assert_size!(MutTxId, 624);
static_assert_size!(MutTxId, 544);

impl MutTxId {
/// Record that a view performs a table scan in this transaction's read set
Expand Down Expand Up @@ -742,10 +742,7 @@ impl MutTxId {
}

for ptr in deleted_table.iter() {
if let Some(row_ref) = self
.committed_state_write_lock
.retry_read(|| Ok(table.get_row_ref(blob_store, ptr)?))?
{
if let Some(row_ref) = table.get_row_ref(blob_store, ptr)? {
process_views(table_id, row_ref);
}
}
Expand All @@ -762,10 +759,7 @@ impl MutTxId {
}

let blob_store = &self.tx_state.blob_store;
for row_ref in inserted_table
.scan_rows(blob_store)
.with_read_eviction(&*self.committed_state_write_lock)
{
for row_ref in inserted_table.scan_rows(blob_store) {
process_views(table_id, row_ref?);
}
}
Expand Down Expand Up @@ -2318,10 +2312,7 @@ impl MutTxId {
.get_index_by_id_with_table(table_id, index_id)?;

// Find the index for the tx state, if any.
let tx_index = self
.tx_state
.get_index_by_id_with_table(table_id, index_id)
.map(|index| index.with_read_eviction(&*self.committed_state_write_lock));
let tx_index = self.tx_state.get_index_by_id_with_table(table_id, index_id);

Some((table_id, commit_index, tx_index))
}
Expand Down Expand Up @@ -2978,8 +2969,7 @@ impl MutTxId {
// See above. Once `TxState::get` is unsafe, justify with:
//
// Our invariants satisfy `TxState::get`.
self.committed_state_write_lock
.retry_read(|| Ok(self.tx_state.get(table_id, row_ptr)?))?,
self.tx_state.get(table_id, row_ptr)?,
),
SquashedOffset::COMMITTED_STATE => {
if self.tx_state.is_deleted(table_id, row_ptr) {
Expand Down Expand Up @@ -4042,21 +4032,8 @@ fn insert_physically_maybe_generate<'a, const GENERATE: bool>(
};

// 1. Insert the physical row.
let insert_physical = |table: &mut Table, blobs: &mut BlobSet| {
table
.insert_physically_bsatn(blobs, row)
.map(|(row, bytes)| (row.into_pinned_row(), bytes))
.map_err(DatastoreError::from)
};
let (tx_pinned_row, blob_bytes) = match insert_physical(tx_table, tx_blob_store) {
Err(error) if error.is_resident_memory_limit() => {
// The insertion hit the memory limit.
// Try to evict resident pages and insert again.
committed_state.trim_resident()?;
insert_physical(tx_table, tx_blob_store)?
}
result => result?,
};
let (tx_row_ref, blob_bytes) = tx_table.insert_physically_bsatn(tx_blob_store, row)?;
let tx_pinned_row = tx_row_ref.into_pinned_row();
// 2. Optionally: Detect, generate, write sequence values.
let (tx_parts, gen_cols) = if GENERATE {
// When `GENERATE` is enabled, we're instructed to deal with sequence value generation.
Expand Down Expand Up @@ -4661,9 +4638,7 @@ fn iter_by_col_range<'a, R: RangeBounds<AlgebraicValue>>(
// It's sufficient to check that the committed state has an index
// as index schema changes are applied immediately.
if let Some(commit_index) = committed_state.get_index_by_cols(table_id, &cols) {
let tx_index = tx_state
.get_index_by_cols(table_id, &cols)
.map(|index| index.with_read_eviction(committed_state));
let tx_index = tx_state.get_index_by_cols(table_id, &cols);
if let Ok(iter) =
MutTxId::index_scan_range_via_algebraic_value(tx_state, table_id, tx_index, commit_index, &range)
{
Expand Down Expand Up @@ -4709,9 +4684,7 @@ fn iter_by_col_eq<'a, 'r>(
// as index schema changes are applied immediately.
let cols = cols.into();
if let Some(commit_index) = committed_state.get_index_by_cols(table_id, &cols) {
let tx_index = tx_state
.get_index_by_cols(table_id, &cols)
.map(|index| index.with_read_eviction(committed_state));
let tx_index = tx_state.get_index_by_cols(table_id, &cols);
let key = commit_index.index().key_from_algebraic_value(val);
let iter = MutTxId::index_scan_point_inner(tx_state, table_id, tx_index, commit_index, &key);
Ok(ScanOrIndex::Index(iter))
Expand Down
Loading
Loading