GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Load database before enforcing memory budget (#6658) · clockworklabs/SpacetimeDB@d0413bd

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • crates
    • datastore/src/locking_tx_datastore
      • datastore.rs
    • engine/src
      • relational_db.rs
    • table/src/tiered
      • budget.rs
      • mem.rs
      • mod.rs
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎crates/datastore/src/locking_tx_datastore/datastore.rs‎

Copy file name to clipboardExpand all lines: crates/datastore/src/locking_tx_datastore/datastore.rs
+24-2Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,23 @@ impl MemoryUsage for Locking {
8383
}
8484

8585
impl Locking {
86+
/// Ignore the resident memory limit while reconstructing committed data.
87+
///
88+
/// The caller must keep exclusive access while the synchronous operation
89+
/// runs, then trim storage before serving new transactions.
90+
pub fn with_resident_hard_limit_suspended<R>(&self, operation: impl FnOnce() -> R) -> R {
91+
// Release the state lock before recovery acquires it for writing.
92+
let storage = self.committed_state.read().storage.clone();
93+
storage.with_resident_hard_limit_suspended(operation)
94+
}
95+
96+
/// Trim the resident and local caches to their low watermarks, as far as possible.
97+
/// Required-in-memory data may keep usage above the limit without an error.
98+
#[cfg(feature = "durability")]
99+
pub fn trim(&self) -> Result<()> {
100+
Ok(self.committed_state.read().trim()?)
101+
}
102+
86103
#[cfg(feature = "metrics")]
87104
pub fn update_data_size_metrics(&self) {
88105
let state = self.committed_state.read();
@@ -184,6 +201,10 @@ impl Locking {
184201
/// after replaying the suffix of the commitlog.
185202
#[cfg(feature = "durability")]
186203
pub fn restore_from_snapshot(snapshot: ReconstructedSnapshot, config: TieredStorageConfig) -> Result<Self> {
204+
// Full database recovery defers eviction until replay, rebuilding, and
205+
// system-table migration have all completed. Preserve immediate trimming
206+
// for direct snapshot API callers.
207+
let trim_after_restore = !config.resident_budget.is_hard_limit_suspended();
187208
let ReconstructedSnapshot {
188209
database_identity,
189210
tx_offset,
@@ -243,8 +264,9 @@ impl Locking {
243264
// The next TX offset after restoring from a snapshot is one greater than the snapshotted offset.
244265
committed_state.next_tx_offset = tx_offset + 1;
245266

246-
// Free memory + disk storage to budget.
247-
committed_state.trim()?;
267+
if trim_after_restore {
268+
committed_state.trim()?;
269+
}
248270

249271
Ok(datastore)
250272
}
Collapse file

‎crates/engine/src/relational_db.rs‎

Copy file name to clipboardExpand all lines: crates/engine/src/relational_db.rs
+38-1Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,30 @@ impl RelationalDB {
287287
history: impl durability::History<TxData = Txdata>,
288288
persistence: Persistence,
289289
metrics_recorder_queue: Option<MetricsRecorderQueue>,
290+
) -> Result<(Self, ConnectedClients), DBError> {
291+
// Persisted transactions must be recoverable even if the memory limit
292+
// was lowered below the size of required-in-memory data. Keep startup
293+
// migrations and reads in the same scope so they cannot block recovery.
294+
let budget = persistence.table_storage.resident_budget.clone();
295+
let (db, connected_clients) = budget.with_hard_limit_suspended(|| {
296+
Self::open_recovering(
297+
database_identity,
298+
owner_identity,
299+
history,
300+
persistence,
301+
metrics_recorder_queue,
302+
)
303+
})?;
304+
db.trim_after_recovery();
305+
Ok((db, connected_clients))
306+
}
307+
308+
fn open_recovering(
309+
database_identity: Identity,
310+
owner_identity: Identity,
311+
history: impl durability::History<TxData = Txdata>,
312+
persistence: Persistence,
313+
metrics_recorder_queue: Option<MetricsRecorderQueue>,
290314
) -> Result<(Self, ConnectedClients), DBError> {
291315
log::trace!("[{database_identity}] DATABASE: OPEN");
292316

@@ -369,6 +393,17 @@ impl RelationalDB {
369393
Ok((db, connected_clients))
370394
}
371395

396+
fn trim_after_recovery(&self) {
397+
// Recovery is complete and the allocation limit is enforced again.
398+
// Failed eviction must leave the reconstructed database available.
399+
if let Err(error) = self.inner.trim() {
400+
log::warn!(
401+
"[{}] cache eviction after recovery failed: {error:#}",
402+
self.database_identity
403+
);
404+
}
405+
}
406+
372407
/// Shut down the database, without dropping it.
373408
///
374409
/// If the database is in-memory only, this does nothing.
@@ -760,7 +795,9 @@ impl RelationalDB {
760795
where
761796
T: durability::History<TxData = Txdata>,
762797
{
763-
apply_history(&self.inner, self.database_identity, history)?;
798+
self.inner
799+
.with_resident_hard_limit_suspended(|| apply_history(&self.inner, self.database_identity, history))?;
800+
self.trim_after_recovery();
764801
Ok(self)
765802
}
766803

Collapse file

‎crates/table/src/tiered/budget.rs‎

Copy file name to clipboardExpand all lines: crates/table/src/tiered/budget.rs
+76-21Lines changed: 76 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
use spacetimedb_memory_usage::MemoryUsage;
22

33
use super::metrics::{CacheTier, Metrics};
4-
use std::sync::{Arc, Mutex};
4+
use parking_lot::Mutex;
5+
use std::sync::Arc;
56

67
#[derive(Debug, thiserror::Error, PartialEq)]
78
#[error("memory limit exceeded")]
@@ -31,7 +32,10 @@ impl ByteBudget {
3132

3233
pub fn new(config: ByteBudgetConfig) -> Result<Self, ConfigError> {
3334
config.validate_then(|config| Self {
34-
state: Arc::new(Mutex::new(ByteBudgetState { accounted_bytes: 0 })),
35+
state: Arc::new(Mutex::new(ByteBudgetState {
36+
accounted_bytes: 0,
37+
hard_limit_suspensions: 0,
38+
})),
3539
config,
3640
metrics: Default::default(),
3741
})
@@ -51,41 +55,86 @@ impl ByteBudget {
5155

5256
pub fn usage(&self) -> ByteBudgetUsage {
5357
ByteBudgetUsage {
54-
accounted_bytes: self.state.lock().unwrap().accounted_bytes,
58+
accounted_bytes: self.state.lock().accounted_bytes,
5559
}
5660
}
5761

5862
pub fn acquire(&self, bytes: u64) -> Result<BudgetPermit, BudgetExceeded> {
59-
let mut state = self.state.lock().unwrap();
63+
self.acquire_with_exemption(bytes, false)
64+
}
65+
66+
/// Charge an allocation, applying the same exemption policy to system
67+
/// allocations and recovery. Accounting overflow is always rejected.
68+
pub(super) fn acquire_with_exemption(
69+
&self,
70+
bytes: u64,
71+
allocation_exempt: bool,
72+
) -> Result<BudgetPermit, BudgetExceeded> {
73+
let mut state = self.state.lock();
6074
if let Some(accounted_bytes) = state.accounted_bytes.checked_add(bytes)
61-
&& accounted_bytes <= self.config.hard_limit_bytes
75+
&& (allocation_exempt
76+
|| state.hard_limit_suspensions > 0
77+
|| accounted_bytes <= self.config.hard_limit_bytes)
6278
{
6379
state.accounted_bytes = accounted_bytes;
6480
Ok(BudgetPermit {
6581
state: self.state.clone(),
6682
bytes,
6783
})
6884
} else {
69-
self.metrics.budget_rejected(self.config.tier);
70-
Err(BudgetExceeded {
85+
let error = BudgetExceeded {
7186
requested_bytes: bytes,
7287
accounted_bytes: state.accounted_bytes,
7388
hard_limit_bytes: self.config.hard_limit_bytes,
74-
})
89+
};
90+
// Metrics callbacks may inspect this budget or unwind. Neither
91+
// should happen while the accounting lock is held.
92+
drop(state);
93+
self.metrics.budget_rejected(self.config.tier);
94+
Err(error)
7595
}
7696
}
7797

78-
pub(super) fn force_acquire(&self, bytes: u64) -> BudgetPermit {
79-
let mut state = self.state.lock().unwrap();
80-
state.accounted_bytes = state
81-
.accounted_bytes
82-
.checked_add(bytes)
83-
.expect("accounted bytes overflow");
84-
BudgetPermit {
98+
/// Run a synchronous recovery operation with the hard limit suspended.
99+
///
100+
/// Acquisitions still count toward usage, including those from budget clones.
101+
/// The suspension ends before this call returns or unwinds. The caller must
102+
/// exclude ordinary database access for the duration of the operation.
103+
pub fn with_hard_limit_suspended<R>(&self, operation: impl FnOnce() -> R) -> R {
104+
let _suspension = self.suspend_hard_limit();
105+
operation()
106+
}
107+
108+
fn suspend_hard_limit(&self) -> HardLimitSuspension {
109+
let mut state = self.state.lock();
110+
state.hard_limit_suspensions = state
111+
.hard_limit_suspensions
112+
.checked_add(1)
113+
.expect("hard limit suspensions overflow");
114+
HardLimitSuspension {
85115
state: self.state.clone(),
86-
bytes,
87116
}
88117
}
118+
119+
pub fn is_hard_limit_suspended(&self) -> bool {
120+
self.state.lock().hard_limit_suspensions > 0
121+
}
122+
}
123+
124+
/// Keeps the shared budget's hard limit suspended until dropped.
125+
#[derive(Debug)]
126+
struct HardLimitSuspension {
127+
state: Arc<Mutex<ByteBudgetState>>,
128+
}
129+
130+
impl Drop for HardLimitSuspension {
131+
fn drop(&mut self) {
132+
let mut state = self.state.lock();
133+
state.hard_limit_suspensions = state
134+
.hard_limit_suspensions
135+
.checked_sub(1)
136+
.expect("hard limit suspensions underflow");
137+
}
89138
}
90139

91140
impl TryFrom<ByteBudgetConfig> for ByteBudget {
@@ -133,6 +182,7 @@ impl ByteBudgetConfig {
133182
#[derive(Debug)]
134183
pub struct ByteBudgetState {
135184
accounted_bytes: u64,
185+
hard_limit_suspensions: u32,
136186
}
137187

138188
impl ByteBudgetUsage {
@@ -149,7 +199,7 @@ pub struct BudgetPermit {
149199

150200
impl Drop for BudgetPermit {
151201
fn drop(&mut self) {
152-
let mut state = self.state.lock().unwrap();
202+
let mut state = self.state.lock();
153203
state.accounted_bytes = state
154204
.accounted_bytes
155205
.checked_sub(self.bytes)
@@ -242,6 +292,11 @@ mod tests {
242292

243293
let error = budget.acquire(requested_bytes).unwrap_err();
244294

295+
prop_assert_eq!(error.accounted_bytes, accounted_bytes);
296+
prop_assert_eq!(budget.usage().accounted_bytes(), accounted_bytes);
297+
298+
// Suspending the limit must not suspend accounting overflow checks.
299+
let error = budget.with_hard_limit_suspended(|| budget.acquire(requested_bytes).unwrap_err());
245300
prop_assert_eq!(error.accounted_bytes, accounted_bytes);
246301
prop_assert_eq!(budget.usage().accounted_bytes(), accounted_bytes);
247302
drop(permit);
@@ -297,7 +352,7 @@ mod tests {
297352
}
298353

299354
#[test]
300-
fn force_acquire_can_exceed_hard_limit(
355+
fn exempt_acquisition_can_exceed_hard_limit(
301356
hard_limit_bytes in 0_u64..1_000_000,
302357
excess_bytes in 1_u64..1_000_000,
303358
) {
@@ -307,12 +362,12 @@ mod tests {
307362
soft_limit_bytes: hard_limit_bytes,
308363
hard_limit_bytes,
309364
}).unwrap();
310-
let forced_bytes = hard_limit_bytes + excess_bytes;
365+
let exempt_bytes = hard_limit_bytes + excess_bytes;
311366

312-
let permit = budget.force_acquire(forced_bytes);
367+
let permit = budget.acquire_with_exemption(exempt_bytes, true).unwrap();
313368

314369
prop_assert!(budget.usage().accounted_bytes() > hard_limit_bytes);
315-
prop_assert_eq!(budget.usage().accounted_bytes(), forced_bytes);
370+
prop_assert_eq!(budget.usage().accounted_bytes(), exempt_bytes);
316371
drop(permit);
317372
prop_assert_eq!(budget.usage().accounted_bytes(), 0);
318373
}
Collapse file

‎crates/table/src/tiered/mem.rs‎

Copy file name to clipboardExpand all lines: crates/table/src/tiered/mem.rs
+4-9Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -186,20 +186,15 @@ impl ResidentObjects {
186186
}
187187

188188
fn acquire(&self, bytes: u64, memory_limit_exempt: bool) -> Result<BudgetPermit, BudgetExceeded> {
189-
if memory_limit_exempt {
190-
// Exempt allocations still count toward the database's resident usage.
191-
Ok(self.budget.force_acquire(bytes))
192-
} else {
193-
self.budget.acquire(bytes)
194-
}
189+
self.budget.acquire_with_exemption(bytes, memory_limit_exempt)
195190
}
196191

197192
pub(super) fn acquire_resident_page(&self, memory_limit_exempt: bool) -> Result<BudgetPermit, BudgetExceeded> {
198193
self.acquire(PAGE_SIZE as u64, memory_limit_exempt)
199194
}
200195

201196
pub(super) fn restored_page_permit(&self) -> BudgetPermit {
202-
self.budget.force_acquire(PAGE_SIZE as u64)
197+
self.acquire(PAGE_SIZE as u64, true).expect("accounted bytes overflow")
203198
}
204199

205200
pub fn new(budget: ByteBudget) -> Self {
@@ -349,7 +344,7 @@ impl ResidentObjects {
349344
}
350345

351346
pub(super) fn register_page_unchecked(&self, pool: PagePool, page: Box<Page>) -> Arc<PageFrame> {
352-
let permit = self.budget.force_acquire(PAGE_SIZE as u64);
347+
let permit = self.restored_page_permit();
353348
let reservation = self.reserve_page_with_permit(permit, PooledPage::new(page, pool));
354349
self.redeem_page(reservation)
355350
}
@@ -364,7 +359,7 @@ impl ResidentObjects {
364359
}
365360

366361
pub(super) fn register_blob_unchecked(&self, blob: Box<[u8]>) -> Arc<BlobFrame> {
367-
let permit = self.budget.force_acquire(blob.len() as u64);
362+
let permit = self.acquire(blob.len() as u64, true).expect("accounted bytes overflow");
368363
let reservation = self.reserve_blob_with_permit(permit, blob);
369364
self.redeem_blob(reservation)
370365
}
Collapse file

‎crates/table/src/tiered/mod.rs‎

Copy file name to clipboardExpand all lines: crates/table/src/tiered/mod.rs
+5Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,11 @@ impl TieredDatabaseStorage {
157157
self.cache.metrics()
158158
}
159159

160+
/// Run synchronous recovery with the resident memory limit suspended.
161+
pub fn with_resident_hard_limit_suspended<R>(&self, operation: impl FnOnce() -> R) -> R {
162+
self.cache.budget().with_hard_limit_suspended(operation)
163+
}
164+
160165
pub fn pages(&self) -> &Arc<PageManager> {
161166
&self.pages
162167
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.