1use super::*;
8
9fn runtime_pool_lock(runtime: &RedDBRuntime) -> std::sync::MutexGuard<'_, PoolState> {
10 runtime
11 .inner
12 .pool
13 .lock()
14 .unwrap_or_else(|poisoned| poisoned.into_inner())
15}
16
17impl RedDBRuntime {
18 pub fn acquire(&self) -> RedDBResult<RuntimeConnection> {
19 self.acquire_connection(true)
20 }
21
22 pub(crate) fn acquire_wire_connection(&self) -> RedDBResult<RuntimeConnection> {
25 self.acquire_connection(false)
26 }
27
28 fn acquire_connection(&self, uses_pool_slot: bool) -> RedDBResult<RuntimeConnection> {
29 let mut pool = self
30 .inner
31 .pool
32 .lock()
33 .map_err(|e| RedDBError::Internal(format!("connection pool lock poisoned: {e}")))?;
34 if uses_pool_slot && pool.pooled_active >= self.inner.pool_config.max_connections {
35 return Err(RedDBError::Internal(
36 "connection pool exhausted".to_string(),
37 ));
38 }
39
40 let id = if let Some(id) = pool.idle.pop() {
41 id
42 } else {
43 let id = pool.next_id;
44 pool.next_id += 1;
45 id
46 };
47 pool.active += 1;
48 if uses_pool_slot {
49 pool.pooled_active += 1;
50 }
51 pool.total_checkouts += 1;
52 drop(pool);
53
54 self.inner.node_load_telemetry.record_connect();
57
58 Ok(RuntimeConnection {
59 background_tasks: self.background_tasks.clone(),
60 id,
61 uses_pool_slot,
62 inner: Arc::clone(&self.inner),
63 })
64 }
65
66 pub fn checkpoint(&self) -> RedDBResult<()> {
67 self.checkpoint_local()?;
72 if let Err(err) = self.assert_remote_write_allowed("checkpoint") {
73 tracing::warn!(
74 target: "reddb::serverless::lease",
75 error = %err,
76 "checkpoint: skipping remote upload — lease not held"
77 );
78 return Ok(());
79 }
80 self.publish_remote_snapshot()
81 }
82
83 pub(super) fn checkpoint_local(&self) -> RedDBResult<()> {
84 let started = std::time::Instant::now();
85 self.seal_hypertable_chunks_for_checkpoint(
86 self.inner.checkpoint_columnar_emission_budget_chunks,
87 )?;
88 let store = self.inner.db.store();
89 let staging_budget =
90 (self.memory_accounting().budget().resolved_bytes / 16).min(32 * 1024 * 1024) as usize;
91 let (prepared, _reservation) = match self.try_reserve_query_buffer(staging_budget) {
92 Some(guard) => match store.prepare_paced_primary(staging_budget)? {
93 Some(prepared) => (Some(prepared), Some(guard)),
94 None => (None, None),
95 },
96 None => (None, None),
97 };
98 let publication = store.vault_publication_lock.lock();
99 let btree_checkpoint = self.index_store_ref().paged_btree_checkpoint();
100 self.prepare_paged_counts()?;
103 self.persist_probabilistic_snapshots()?;
104 let checkpoint_lsn = self.replication_commit_lsn();
105 self.inner
106 .db
107 .flush_local_after_runtime_snapshots(prepared.as_ref(), || {
108 let retired_btrees = btree_checkpoint.publish();
109 self.index_store_ref().hash.clear_paged_retired();
110 self.inner.probabilistic.replayed_names.lock().clear();
111 parking_lot::ReentrantMutexGuard::unlock_fair(publication);
112 drop(retired_btrees);
113 #[cfg(test)]
114 checkpoint_cut_test::after_data_cut();
115 })
116 .map_err(|err| {
117 let msg = err.to_string();
122 crate::telemetry::operator_event::OperatorEvent::CheckpointFailed {
123 lsn: 0,
124 error: msg.clone(),
125 }
126 .emit_global();
127 crate::telemetry::operator_event::OperatorEvent::WalFsyncFailed {
128 path: "<flush_local_only>".to_string(),
129 error: msg.clone(),
130 }
131 .emit_global();
132 RedDBError::Engine(msg)
133 })?;
134 self.inner
135 .checkpoint_projection_stats
136 .record_checkpoint(checkpoint_lsn, started.elapsed().as_millis() as u64);
137 Ok(())
138 }
139
140 pub(crate) fn assert_remote_write_allowed(&self, action: &str) -> RedDBResult<()> {
145 if self.inner.db.remote_backend.is_none() {
146 return Ok(());
147 }
148 if matches!(
149 self.inner.write_gate.role(),
150 crate::replication::ReplicationRole::Replica { .. }
151 ) {
152 return Err(RedDBError::ReadOnly(format!(
153 "replica cannot publish remote data — {action} blocked"
154 )));
155 }
156 match self.inner.write_gate.lease_state() {
157 crate::runtime::write_gate::LeaseGateState::NotHeld => {
158 self.inner.audit_log.record(
159 action,
160 "system",
161 "remote_backend",
162 "err: writer lease not held",
163 crate::json::Value::Null,
164 );
165 Err(RedDBError::ReadOnly(format!(
166 "writer lease not held — {action} blocked (serverless fence)"
167 )))
168 }
169 _ => Ok(()),
170 }
171 }
172
173 pub(super) fn publish_remote_snapshot(&self) -> RedDBResult<()> {
174 self.assert_remote_write_allowed("snapshot publication")?;
175 if let Some(lifecycle) = self.lease_lifecycle() {
176 let store = self.inner.db.store();
177 let _publication = store.vault_publication_lock.lock();
180 if lifecycle.publish_snapshot(|| self.capture_serverless_snapshot())? {
181 return Ok(());
182 }
183 }
184 if self.inner.db.is_paged()
185 && self.inner.db.remote_backend.is_some()
186 && self.inner.db.remote_key.is_some()
187 {
188 let snapshot = self.capture_serverless_snapshot()?;
191 self.assert_remote_write_allowed("checkpoint upload")?;
192 return self
193 .inner
194 .db
195 .upload_checkpoint_to_remote_backend(snapshot.path())
196 .map_err(|err| RedDBError::Engine(err.to_string()));
197 }
198 self.inner
199 .db
200 .upload_to_remote_backend()
201 .map_err(|err| RedDBError::Engine(err.to_string()))
202 }
203
204 pub(crate) fn capture_serverless_snapshot(
205 &self,
206 ) -> RedDBResult<reddb_file::ServerlessWriterLeaseTempFile> {
207 use reddb_file::VfsFile;
208 use std::io::Write;
209 let store = self.inner.db.store();
210 let _publication = store.vault_publication_lock.lock();
211 self.checkpoint_local()?;
212 let snapshot = reddb_file::ServerlessWriterLeaseTempFile::new("snapshot-payload");
213 if let Some(pager) = store.pager() {
214 pager
217 .with_file(|source| -> std::io::Result<()> {
218 let mut output = std::fs::File::create(snapshot.path())?;
219 source.seek(std::io::SeekFrom::Start(0))?;
220 let mut buffer = [0u8; 65536];
221 loop {
222 let count = source.read(&mut buffer)?;
223 if count == 0 {
224 break;
225 }
226 output.write_all(&buffer[..count])?;
227 }
228 output.sync_all()
229 })
230 .map_err(|err| RedDBError::Internal(err.to_string()))?
231 .map_err(|err| RedDBError::Internal(err.to_string()))?;
232 } else {
233 let path = self.inner.db.path().ok_or_else(|| {
234 RedDBError::InvalidOperation(
235 "serverless snapshots require persistent local storage".into(),
236 )
237 })?;
238 std::fs::copy(path, snapshot.path())
239 .map_err(|err| RedDBError::Internal(err.to_string()))?;
240 }
241 Ok(snapshot)
242 }
243
244 pub fn run_maintenance(&self) -> RedDBResult<()> {
245 self.inner
246 .db
247 .run_maintenance()
248 .map_err(|err| RedDBError::Internal(err.to_string()))
249 }
250
251 pub fn scan_collection(
252 &self,
253 collection: &str,
254 cursor: Option<ScanCursor>,
255 limit: usize,
256 ) -> RedDBResult<ScanPage> {
257 use reddb_rql::ast::PolicyAction;
258
259 self.check_collection_privilege(PolicyAction::Select, collection)?;
260 let store = self.inner.db.store();
261 let manager = store
262 .get_collection(collection)
263 .ok_or_else(|| RedDBError::NotFound(collection.to_string()))?;
264
265 let offset = cursor.map(|cursor| cursor.offset).unwrap_or(0);
266 let limit = limit.max(1);
267 let read_bytes = usize::try_from(self.memory_budget().resolved_bytes / 16)
268 .unwrap_or(usize::MAX)
269 .clamp(1, 16 * 1024 * 1024);
270 let (snapshot, _retention) = self.native_read_snapshot()?;
271 let _snapshot_guard = super::impl_core::CurrentSnapshotGuard::install(snapshot.clone());
272 let (total, items) = manager.try_page_in_id_order_where_at_snapshot(
273 Some(&snapshot),
274 offset,
275 limit,
276 read_bytes,
277 |entity| {
278 crate::runtime::rls_injection::entity_passes_rls_action(
279 self,
280 collection,
281 PolicyAction::Select,
282 entity,
283 )
284 },
285 )?;
286 let end = total.min(offset.saturating_add(limit));
287 let next = (end < total).then_some(ScanCursor { offset: end });
288
289 Ok(ScanPage {
290 collection: collection.to_string(),
291 items,
292 next,
293 total,
294 })
295 }
296
297 pub fn get_collection_entity(
298 &self,
299 collection: &str,
300 id: crate::storage::EntityId,
301 ) -> RedDBResult<Option<crate::storage::UnifiedEntity>> {
302 self.get_collection_entity_for_action(collection, id, reddb_rql::ast::PolicyAction::Select)
303 }
304
305 pub(crate) fn get_collection_entity_for_action(
306 &self,
307 collection: &str,
308 id: crate::storage::EntityId,
309 action: reddb_rql::ast::PolicyAction,
310 ) -> RedDBResult<Option<crate::storage::UnifiedEntity>> {
311 self.check_collection_privilege(action, collection)?;
312 let store = self.inner.db.store();
313 let Some(manager) = store.get_collection(collection) else {
314 return Ok(None);
315 };
316 let (snapshot, _retention) = self.native_read_snapshot()?;
317 let _snapshot_guard = super::impl_core::CurrentSnapshotGuard::install(snapshot.clone());
318 let read_bytes = usize::try_from(self.memory_budget().resolved_bytes / 16)
319 .unwrap_or(usize::MAX)
320 .clamp(1, 16 * 1024 * 1024);
321 let mut entity = manager.try_get(id, read_bytes)?.filter(|candidate| {
322 candidate.logical_id() == id
323 && super::impl_core::entity_visible_with_context(Some(&snapshot), candidate)
324 });
325 if entity.is_none() {
328 manager.try_for_each_entity(read_bytes, |candidate| {
329 if candidate.logical_id() == id
330 && super::impl_core::entity_visible_with_context(Some(&snapshot), candidate)
331 && entity.as_ref().is_none_or(|selected: &UnifiedEntity| {
332 (candidate.xmin, candidate.id) > (selected.xmin, selected.id)
333 })
334 {
335 entity = Some(candidate.clone());
336 }
337 true
338 })?;
339 }
340 manager.restore_owned_row_schemas(entity.iter_mut());
341 Ok(entity.filter(|entity| {
342 crate::runtime::rls_injection::entity_passes_rls_action(
343 self, collection, action, entity,
344 )
345 }))
346 }
347
348 pub(crate) fn native_read_snapshot(
349 &self,
350 ) -> RedDBResult<(
351 super::impl_core::SnapshotContext,
352 crate::storage::transaction::snapshot::SnapshotRetentionGuard,
353 )> {
354 let state = &self.inner.transaction_state;
355 let manager = state.snapshot_manager();
356 if let Some(context) = super::impl_core::capture_current_snapshot()
357 .filter(|context| Arc::ptr_eq(&context.manager, &manager))
358 {
359 let (_, retention) = manager.retain_snapshot(context.snapshot.clone());
360 return Ok((context, retention));
361 }
362 let connection_id = super::impl_core::current_connection_id();
363 let store = self.inner.db.store();
364 let uses_vcs = self.vcs_has_versioned_collections()?;
365 let _publication = uses_vcs.then(|| store.vault_publication_lock.lock());
366 let (snapshot, retention) = state.retained_current_snapshot(connection_id);
367 let branch = if uses_vcs {
368 self.vcs_branch_read_view(&snapshot, None)?
369 } else {
370 None
371 };
372 let context = state.context(connection_id);
373 Ok((
374 super::impl_core::SnapshotContext {
375 branch,
376 snapshot,
377 manager,
378 own_xids: self.own_transaction_xids(),
379 requires_index_fallback: true,
380 hidden_writers_only: false,
381 serializable_reader: context
382 .filter(|context| {
383 context.isolation
384 == crate::storage::transaction::IsolationLevel::Serializable
385 })
386 .map(|context| context.xid),
387 },
388 retention,
389 ))
390 }
391
392 pub fn catalog(&self) -> CatalogModelSnapshot {
393 self.inner.db.catalog_model_snapshot()
394 }
395
396 pub fn try_catalog(&self) -> RedDBResult<CatalogModelSnapshot> {
399 if self
400 .inner
401 .db
402 .store()
403 .config()
404 .resident_memory_bytes_max
405 .is_none()
406 {
407 return Ok(self.catalog());
408 }
409 let read_bytes = usize::try_from(self.memory_budget().resolved_bytes / 16)
410 .unwrap_or(usize::MAX)
411 .clamp(1, 16 * 1024 * 1024);
412 let _scratch = self
413 .try_reserve_query_buffer(read_bytes * 2)
414 .ok_or_else(|| {
415 self.memory_accounting().record_admission_denied();
416 RedDBError::MaterializationLimitExceeded {
417 executor: "catalog",
418 limit: usize::try_from(self.memory_budget().resolved_bytes)
419 .unwrap_or(usize::MAX),
420 current: usize::try_from(self.memory_accounting().total_used_bytes())
421 .unwrap_or(usize::MAX)
422 .saturating_add(1),
423 }
424 })?;
425 Ok(self.inner.db.try_catalog_model_snapshot(read_bytes)?)
426 }
427
428 pub(crate) fn try_catalog_for_collections(
433 &self,
434 collection_names: Option<&std::collections::HashSet<String>>,
435 observe_legacy_payloads: bool,
436 ) -> RedDBResult<CatalogModelSnapshot> {
437 if self
438 .inner
439 .db
440 .store()
441 .config()
442 .resident_memory_bytes_max
443 .is_none()
444 {
445 return Ok(self.inner.db.try_catalog_model_snapshot_for_collections(
446 collection_names,
447 observe_legacy_payloads,
448 usize::MAX,
449 )?);
450 }
451 let read_bytes = usize::try_from(self.memory_budget().resolved_bytes / 16)
452 .unwrap_or(usize::MAX)
453 .clamp(1, 16 * 1024 * 1024);
454 let _scratch = self
455 .try_reserve_query_buffer(read_bytes * 2)
456 .ok_or_else(|| {
457 self.memory_accounting().record_admission_denied();
458 RedDBError::MaterializationLimitExceeded {
459 executor: "catalog",
460 limit: usize::try_from(self.memory_budget().resolved_bytes)
461 .unwrap_or(usize::MAX),
462 current: usize::try_from(self.memory_accounting().total_used_bytes())
463 .unwrap_or(usize::MAX)
464 .saturating_add(1),
465 }
466 })?;
467 Ok(self.inner.db.try_catalog_model_snapshot_for_collections(
468 collection_names,
469 observe_legacy_payloads,
470 read_bytes,
471 )?)
472 }
473
474 pub fn catalog_consistency_report(&self) -> crate::catalog::CatalogConsistencyReport {
475 self.inner.db.catalog_consistency_report()
476 }
477
478 pub fn catalog_attention_summary(&self) -> CatalogAttentionSummary {
479 crate::catalog::attention_summary(&self.catalog())
480 }
481
482 pub fn collection_attention(&self) -> Vec<CollectionDescriptor> {
483 crate::catalog::collection_attention(&self.catalog())
484 }
485
486 pub fn index_attention(&self) -> Vec<CatalogIndexStatus> {
487 crate::catalog::index_attention(&self.catalog())
488 }
489
490 pub fn graph_projection_attention(&self) -> Vec<CatalogGraphProjectionStatus> {
491 crate::catalog::graph_projection_attention(&self.catalog())
492 }
493
494 pub fn analytics_job_attention(&self) -> Vec<CatalogAnalyticsJobStatus> {
495 crate::catalog::analytics_job_attention(&self.catalog())
496 }
497
498 pub fn stats(&self) -> RuntimeStats {
499 let pool = runtime_pool_lock(self);
500 RuntimeStats {
501 active_connections: pool.active,
502 idle_connections: pool.idle.len(),
503 total_checkouts: pool.total_checkouts,
504 paged_mode: self.inner.db.is_paged(),
505 started_at_unix_ms: self.inner.started_at_unix_ms,
506 store: self.inner.db.stats(),
507 system: SystemInfo::collect(),
508 result_blob_cache: self.inner.result_blob_cache.stats(),
509 kv: self.inner.kv_stats.snapshot(),
510 metrics_ingest: self.inner.metrics_ingest_stats.snapshot(),
511 }
512 }
513}
514
515#[cfg(test)]
516mod security_boundary_tests {
517 use super::*;
518 use crate::application::entity::{DeleteEntityInput, PatchEntityInput};
519 use crate::application::ports::RuntimeEntityPort;
520 use crate::auth::Role;
521 use crate::runtime::execution_context::{with_snapshot_bundle, SnapshotBundle};
522 use crate::storage::{EntityData, UnifiedEntity};
523 use reddb_types::Value;
524
525 fn text_field<'a>(entity: &'a UnifiedEntity, name: &str) -> Option<&'a str> {
526 let EntityData::Row(row) = &entity.data else {
527 return None;
528 };
529 let value = row
530 .named
531 .as_ref()
532 .and_then(|named| named.get(name))
533 .or_else(|| {
534 row.schema.as_ref().and_then(|schema| {
535 schema
536 .iter()
537 .position(|column| column == name)
538 .and_then(|index| row.columns.get(index))
539 })
540 })?;
541 match value {
542 Value::Text(value) => Some(value.as_ref()),
543 _ => None,
544 }
545 }
546
547 #[test]
548 fn typed_entity_boundary_filters_before_pagination_and_hides_foreign_ids() {
549 let runtime = RedDBRuntime::in_memory().expect("runtime");
550 runtime
551 .execute_query(
552 "CREATE TABLE docs (id INT, tenant_id TEXT, body TEXT) TENANT BY (tenant_id)",
553 )
554 .expect("tenant table");
555 runtime
556 .execute_query(
557 "INSERT INTO docs (id, tenant_id, body) VALUES \
558 (1, 'acme', 'first'), (2, 'globex', 'hidden'), (3, 'acme', 'second')",
559 )
560 .expect("seed platform rows");
561
562 let unfiltered = runtime
563 .scan_collection("docs", None, 10)
564 .expect("platform scan");
565 let foreign_id = unfiltered
566 .items
567 .iter()
568 .find(|entity| text_field(entity, "tenant_id") == Some("globex"))
569 .map(|entity| entity.id)
570 .expect("foreign row");
571
572 let bundle = SnapshotBundle {
573 snapshot: None,
574 auth: Some(("alice".to_string(), Role::Write)),
575 auth_principal: Some(crate::auth::UserId::scoped("acme", "alice")),
576 tenant: Some("acme".to_string()),
577 };
578 with_snapshot_bundle(&bundle, || {
579 let first = runtime
580 .scan_collection("docs", None, 1)
581 .expect("first visible page");
582 assert_eq!(first.total, 2);
583 assert_eq!(first.items.len(), 1);
584 assert_eq!(text_field(&first.items[0], "tenant_id"), Some("acme"));
585 assert_eq!(first.next, Some(ScanCursor { offset: 1 }));
586
587 let second = runtime
588 .scan_collection("docs", first.next, 1)
589 .expect("second visible page");
590 assert_eq!(second.total, 2);
591 assert_eq!(second.items.len(), 1);
592 assert_eq!(text_field(&second.items[0], "tenant_id"), Some("acme"));
593 assert_eq!(second.next, None);
594
595 assert!(runtime
596 .get_collection_entity("docs", foreign_id)
597 .expect("typed get")
598 .is_none());
599 assert!(matches!(
600 runtime.patch_entity(PatchEntityInput {
601 collection: "docs".to_string(),
602 id: foreign_id,
603 payload: crate::json::Value::Object(Default::default()),
604 operations: Vec::new(),
605 }),
606 Err(crate::RedDBError::NotFound(_))
607 ));
608 let deleted = runtime
609 .delete_entity(DeleteEntityInput {
610 collection: "docs".to_string(),
611 id: foreign_id,
612 })
613 .expect("typed delete");
614 assert!(!deleted.deleted);
615 });
616
617 assert!(runtime.db().store().get("docs", foreign_id).is_some());
618 }
619
620 #[test]
621 fn scan_collection_pages_the_mvcc_view_across_rollback() {
622 let runtime = RedDBRuntime::in_memory().expect("runtime");
623 runtime
624 .execute_query("CREATE TABLE docs (id INT, body TEXT)")
625 .expect("table");
626 runtime
627 .execute_query("INSERT INTO docs (id, body) VALUES (1, 'kept')")
628 .expect("seed row");
629
630 runtime.execute_query("BEGIN").expect("begin");
631 runtime
632 .execute_query("DELETE FROM docs WHERE id = 1")
633 .expect("delete in transaction");
634 let deleted = runtime
635 .scan_collection("docs", None, 1)
636 .expect("scan own transaction");
637 assert_eq!(deleted.total, 0);
638 assert!(deleted.items.is_empty());
639
640 runtime.execute_query("ROLLBACK").expect("rollback");
641 let restored = runtime
642 .scan_collection("docs", None, 1)
643 .expect("scan after rollback");
644 assert_eq!(restored.total, 1);
645 assert_eq!(restored.items.len(), 1);
646 assert_eq!(text_field(&restored.items[0], "body"), Some("kept"));
647 assert_eq!(restored.next, None);
648 }
649
650 #[test]
651 fn typed_entity_boundary_uses_model_specific_rls_policies() {
652 let runtime = RedDBRuntime::in_memory().expect("runtime");
653 for query in [
654 "CREATE GRAPH links",
655 "INSERT INTO links NODE (label,node_type,visible) VALUES ('shown','Item',true)",
656 "INSERT INTO links NODE (label,node_type,visible) VALUES ('hidden','Item',false)",
657 "CREATE POLICY visible_nodes ON NODES OF links FOR SELECT USING (properties.visible=true)",
658 "ALTER TABLE links ENABLE ROW LEVEL SECURITY",
659 "CREATE DOCUMENT papers",
660 "INSERT INTO papers DOCUMENT VALUES ({name:'shown',visible:true})",
661 "INSERT INTO papers DOCUMENT VALUES ({name:'hidden',visible:false})",
662 "CREATE POLICY visible_documents ON DOCUMENTS OF papers FOR SELECT USING (visible=true)",
663 "ALTER TABLE papers ENABLE ROW LEVEL SECURITY",
664 ] {
665 runtime.execute_query(query).expect(query);
666 }
667
668 let bundle = SnapshotBundle {
669 snapshot: None,
670 auth: Some(("alice".to_string(), Role::Read)),
671 auth_principal: Some(crate::auth::UserId::platform("alice")),
672 tenant: None,
673 };
674 with_snapshot_bundle(&bundle, || {
675 let nodes = runtime
676 .scan_collection("links", None, 10)
677 .expect("typed graph scan");
678 assert_eq!(nodes.total, 1);
679 assert_eq!(nodes.items.len(), 1);
680
681 let documents = runtime
682 .scan_collection("papers", None, 10)
683 .expect("typed document scan");
684 assert_eq!(documents.total, 1);
685 assert_eq!(documents.items.len(), 1);
686 });
687 }
688}
689
690#[cfg(test)]
691mod checkpoint_cut_test {
692 use crate::{api::DurabilityMode, RedDBOptions, RedDBRuntime};
693 use std::{cell::RefCell, path::Path, sync::mpsc, sync::Arc, thread, time::Duration};
694
695 thread_local! {
696 static CUT: RefCell<Option<(mpsc::Sender<()>, mpsc::Receiver<()>)>> = const { RefCell::new(None) };
697 }
698
699 pub(super) fn after_data_cut() {
700 if let Some((ready, resume)) = CUT.take() {
701 ready.send(()).unwrap();
702 resume
703 .recv_timeout(Duration::from_secs(30))
704 .expect("resume metadata publication");
705 }
706 }
707
708 fn open(path: &Path) -> RedDBRuntime {
709 RedDBRuntime::with_options(
710 RedDBOptions::persistent(path)
711 .with_memory_budget(64 * 1024 * 1024)
712 .with_bounded_disk_residency(true)
713 .with_durability_mode(DurabilityMode::Strict),
714 )
715 .unwrap()
716 }
717
718 #[test]
719 fn completed_metadata_pass_preserves_post_snapshot_sql_and_sketch() {
720 const CHILD: &str = "REDDB_TEST_POST_SNAPSHOT_SQL_AND_SKETCH";
721 const INTERRUPT: &str = "REDDB_TEST_INTERRUPT_METADATA_PASS";
722 if let Some(path) = std::env::var_os(CHILD) {
723 let db = Arc::new(open(Path::new(&path)));
724 for sql in [
725 "CREATE TABLE late_rows (v INTEGER)",
726 "CREATE SKETCH late_counts",
727 "SKETCH ADD late_counts 'red' 3",
728 ] {
729 db.execute_query(sql).unwrap();
730 }
731 let (ready, cut) = mpsc::channel();
732 let (resume, proceed) = mpsc::channel();
733 let checkpoint = Arc::clone(&db);
734 let builder = thread::spawn(move || {
735 CUT.set(Some((ready, proceed)));
736 checkpoint.checkpoint().unwrap();
737 });
738 cut.recv_timeout(Duration::from_secs(60))
739 .expect("durable data cut");
740 assert_eq!(
741 db.execute_query("INSERT INTO late_rows (v) VALUES (42)")
742 .unwrap()
743 .affected_rows,
744 1
745 );
746 db.execute_query("SKETCH ADD late_counts 'red' 4").unwrap();
747 if let Ok(point) = std::env::var(INTERRUPT) {
748 std::env::set_var(point, "1");
749 }
750 resume.send(()).unwrap();
751 builder.join().unwrap();
752 std::process::exit(72);
753 }
754 for (interrupt, exit_code) in [
755 (None, 72),
756 (Some("REDDB_TEST_EXIT_BEFORE_CATALOG_ROOT_PUBLICATION"), 197),
757 (Some("REDDB_TEST_EXIT_AFTER_CATALOG_ROOT_PUBLICATION"), 198),
758 ] {
759 let directory = tempfile::tempdir().unwrap();
760 let path = directory.path().join("cut.rdb");
761 let mut child = std::process::Command::new(std::env::current_exe().unwrap());
762 child
763 .args(["--exact", "runtime::impl_catalog_accessors::checkpoint_cut_test::completed_metadata_pass_preserves_post_snapshot_sql_and_sketch", "--nocapture"])
764 .env(CHILD, &path).env_remove(INTERRUPT);
765 if let Some(point) = interrupt {
766 child.env(INTERRUPT, point);
767 }
768 let child = child.output().unwrap();
769 assert_eq!(
770 child.status.code(),
771 Some(exit_code),
772 "{}",
773 String::from_utf8_lossy(&child.stderr)
774 );
775 let db = open(&path);
776 let physical = db
777 .db()
778 .physical_metadata()
779 .expect("recover physical metadata");
780 assert!(physical
781 .superblock
782 .collection_roots
783 .contains_key("late_rows"));
784 if interrupt.is_none() {
785 let header = db
786 .db()
787 .store()
788 .physical_file_header()
789 .expect("physical header");
790 assert_eq!(header.sequence, physical.superblock.sequence);
791 }
792 let rows = db
793 .execute_query("SELECT v FROM late_rows")
794 .unwrap()
795 .result
796 .records;
797 assert_eq!(rows.len(), 1);
798 assert_eq!(rows[0].get("v"), Some(&reddb_types::Value::Integer(42)));
799 let counts = db.execute_query("SKETCH COUNT late_counts 'red'").unwrap();
800 assert_eq!(
801 counts.result.records[0]
802 .get("estimate")
803 .unwrap()
804 .display_string(),
805 "7"
806 );
807 }
808 }
809}