Skip to main content

reddb_server/runtime/
impl_catalog_accessors.rs

1//! Runtime catalog / stats / maintenance accessors.
2//!
3//! Extracted verbatim from `impl_core.rs` (impl_core slice 8/10, issue #1629).
4//! Houses connection `acquire`, `checkpoint`, the remote-write assertion,
5//! `run_maintenance`, `scan_collection`, and the catalog /
6//! attention-summary / `stats` readers.
7use 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    // Transport admission already bounds wire sessions. Share connection IDs
23    // and rollback cleanup without imposing the embedded pool's separate cap.
24    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        // Issue #1245 — record the connection acquisition after releasing
55        // the pool lock so the lock hold time is unchanged.
56        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        // Local fsync always allowed — losing the lease shouldn't
68        // prevent us from durably persisting what's already in memory.
69        // The remote upload is the side-effect that risks clobbering a
70        // peer's state, so it's behind the lease gate.
71        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        // A copy is staged in durable batches so that other statements commit
92        // between them. A caller that already holds the publication lock (a
93        // checkpoint taken at the start of a statement) leaves them no gap:
94        // the staged copy of a 362,000-row table then held every reader and
95        // writer of the store for minutes, at about nine fsyncs per 512 rows,
96        // and began again after each restart. The checkpoint's own copy is
97        // the same wait and many times shorter.
98        let staged = if store.vault_publication_lock.is_owned_by_current_thread() {
99            None
100        } else {
101            self.try_reserve_query_buffer(staging_budget)
102        };
103        let (prepared, _reservation) = match staged {
104            Some(guard) => match store.prepare_paced_primary(staging_budget)? {
105                Some(prepared) => (Some(prepared), Some(guard)),
106                None => (None, None),
107            },
108            None => (None, None),
109        };
110        // Statements that would change rows wait outside from here on: one
111        // that waited inside, on the fence, kept its table's readers scanning.
112        let _admission = self.index_store_ref().admit_checkpoint();
113        let publication = store.vault_publication_lock.lock();
114        let btree_checkpoint = self.index_store_ref().paged_btree_checkpoint();
115        // Collections created since startup need the compact visibility
116        // inventory before their first resident-to-disk publication too.
117        self.prepare_paged_counts()?;
118        self.persist_probabilistic_snapshots()?;
119        let checkpoint_lsn = self.replication_commit_lsn();
120        self.inner
121            .db
122            .flush_local_after_runtime_snapshots(prepared.as_ref(), || {
123                let retired_btrees = btree_checkpoint.publish();
124                self.index_store_ref().hash.clear_paged_retired();
125                self.inner.probabilistic.replayed_names.lock().clear();
126                parking_lot::ReentrantMutexGuard::unlock_fair(publication);
127                drop(retired_btrees);
128                #[cfg(test)]
129                checkpoint_cut_test::after_data_cut();
130            })
131            .map_err(|err| {
132                // Issue #205 — local flush failure is a CheckpointFailed
133                // operator-grade event. The local-flush path also covers
134                // the WAL fsync we depend on, so a failure here doubles as
135                // the WalFsyncFailed signal for the runtime entry point.
136                let msg = err.to_string();
137                crate::telemetry::operator_event::OperatorEvent::CheckpointFailed {
138                    lsn: 0,
139                    error: msg.clone(),
140                }
141                .emit_global();
142                crate::telemetry::operator_event::OperatorEvent::WalFsyncFailed {
143                    path: "<flush_local_only>".to_string(),
144                    error: msg.clone(),
145                }
146                .emit_global();
147                RedDBError::Engine(msg)
148            })?;
149        self.inner
150            .checkpoint_projection_stats
151            .record_checkpoint(checkpoint_lsn, started.elapsed().as_millis() as u64);
152        Ok(())
153    }
154
155    /// Guard remote mutations on replication role and writer lease.
156    /// With a backend configured, replicas cannot publish and other nodes
157    /// require a `NotRequired` or `Held` lease state. Local checkpoints can
158    /// still finish when this guard returns `RedDBError::ReadOnly`.
159    pub(crate) fn assert_remote_write_allowed(&self, action: &str) -> RedDBResult<()> {
160        if self.inner.db.remote_backend.is_none() {
161            return Ok(());
162        }
163        if matches!(
164            self.inner.write_gate.role(),
165            crate::replication::ReplicationRole::Replica { .. }
166        ) {
167            return Err(RedDBError::ReadOnly(format!(
168                "replica cannot publish remote data — {action} blocked"
169            )));
170        }
171        match self.inner.write_gate.lease_state() {
172            crate::runtime::write_gate::LeaseGateState::NotHeld => {
173                self.inner.audit_log.record(
174                    action,
175                    "system",
176                    "remote_backend",
177                    "err: writer lease not held",
178                    crate::json::Value::Null,
179                );
180                Err(RedDBError::ReadOnly(format!(
181                    "writer lease not held — {action} blocked (serverless fence)"
182                )))
183            }
184            _ => Ok(()),
185        }
186    }
187
188    pub(super) fn publish_remote_snapshot(&self) -> RedDBResult<()> {
189        self.assert_remote_write_allowed("snapshot publication")?;
190        if let Some(lifecycle) = self.lease_lifecycle() {
191            let store = self.inner.db.store();
192            // Other snapshot entrypoints already hold this reentrant lock.
193            // Keep a consistent publication -> lease transition lock order.
194            let _publication = store.vault_publication_lock.lock();
195            if lifecycle.publish_snapshot(|| self.capture_serverless_snapshot())? {
196                return Ok(());
197            }
198        }
199        if self.inner.db.is_paged()
200            && self.inner.db.remote_backend.is_some()
201            && self.inner.db.remote_key.is_some()
202        {
203            // Native writers hold a lifetime file lock. Copy through the
204            // pager's own handle before handing the checkpoint to a backend.
205            let snapshot = self.capture_serverless_snapshot()?;
206            self.assert_remote_write_allowed("checkpoint upload")?;
207            return self
208                .inner
209                .db
210                .upload_checkpoint_to_remote_backend(snapshot.path())
211                .map_err(|err| RedDBError::Engine(err.to_string()));
212        }
213        self.inner
214            .db
215            .upload_to_remote_backend()
216            .map_err(|err| RedDBError::Engine(err.to_string()))
217    }
218
219    pub(crate) fn capture_serverless_snapshot(
220        &self,
221    ) -> RedDBResult<reddb_file::ServerlessWriterLeaseTempFile> {
222        use reddb_file::VfsFile;
223        use std::io::Write;
224        let store = self.inner.db.store();
225        let _publication = store.vault_publication_lock.lock();
226        self.checkpoint_local()?;
227        let snapshot = reddb_file::ServerlessWriterLeaseTempFile::new("snapshot-payload");
228        if let Some(pager) = store.pager() {
229            // Use the pager's own handle: Windows excludes reads through any
230            // second handle while the native writer owns the file lock.
231            pager
232                .with_file(|source| -> std::io::Result<()> {
233                    let mut output = std::fs::File::create(snapshot.path())?;
234                    source.seek(std::io::SeekFrom::Start(0))?;
235                    let mut buffer = [0u8; 65536];
236                    loop {
237                        let count = source.read(&mut buffer)?;
238                        if count == 0 {
239                            break;
240                        }
241                        output.write_all(&buffer[..count])?;
242                    }
243                    output.sync_all()
244                })
245                .map_err(|err| RedDBError::Internal(err.to_string()))?
246                .map_err(|err| RedDBError::Internal(err.to_string()))?;
247        } else {
248            let path = self.inner.db.path().ok_or_else(|| {
249                RedDBError::InvalidOperation(
250                    "serverless snapshots require persistent local storage".into(),
251                )
252            })?;
253            std::fs::copy(path, snapshot.path())
254                .map_err(|err| RedDBError::Internal(err.to_string()))?;
255        }
256        Ok(snapshot)
257    }
258
259    pub fn run_maintenance(&self) -> RedDBResult<()> {
260        self.inner
261            .db
262            .run_maintenance()
263            .map_err(|err| RedDBError::Internal(err.to_string()))
264    }
265
266    pub fn scan_collection(
267        &self,
268        collection: &str,
269        cursor: Option<ScanCursor>,
270        limit: usize,
271    ) -> RedDBResult<ScanPage> {
272        use reddb_rql::ast::PolicyAction;
273
274        self.check_collection_privilege(PolicyAction::Select, collection)?;
275        let store = self.inner.db.store();
276        let manager = store
277            .get_collection(collection)
278            .ok_or_else(|| RedDBError::NotFound(collection.to_string()))?;
279
280        let offset = cursor.map(|cursor| cursor.offset).unwrap_or(0);
281        let limit = limit.max(1);
282        let read_bytes = usize::try_from(self.memory_budget().resolved_bytes / 16)
283            .unwrap_or(usize::MAX)
284            .clamp(1, 16 * 1024 * 1024);
285        let (snapshot, _retention) = self.native_read_snapshot()?;
286        let _snapshot_guard = super::impl_core::CurrentSnapshotGuard::install(snapshot.clone());
287        let (total, items) = manager.try_page_in_id_order_where_at_snapshot(
288            Some(&snapshot),
289            offset,
290            limit,
291            read_bytes,
292            |entity| {
293                crate::runtime::rls_injection::entity_passes_rls_action(
294                    self,
295                    collection,
296                    PolicyAction::Select,
297                    entity,
298                )
299            },
300        )?;
301        let end = total.min(offset.saturating_add(limit));
302        let next = (end < total).then_some(ScanCursor { offset: end });
303
304        Ok(ScanPage {
305            collection: collection.to_string(),
306            items,
307            next,
308            total,
309        })
310    }
311
312    pub fn get_collection_entity(
313        &self,
314        collection: &str,
315        id: crate::storage::EntityId,
316    ) -> RedDBResult<Option<crate::storage::UnifiedEntity>> {
317        self.get_collection_entity_for_action(collection, id, reddb_rql::ast::PolicyAction::Select)
318    }
319
320    pub(crate) fn get_collection_entity_for_action(
321        &self,
322        collection: &str,
323        id: crate::storage::EntityId,
324        action: reddb_rql::ast::PolicyAction,
325    ) -> RedDBResult<Option<crate::storage::UnifiedEntity>> {
326        self.check_collection_privilege(action, collection)?;
327        let store = self.inner.db.store();
328        let Some(manager) = store.get_collection(collection) else {
329            return Ok(None);
330        };
331        let (snapshot, _retention) = self.native_read_snapshot()?;
332        let _snapshot_guard = super::impl_core::CurrentSnapshotGuard::install(snapshot.clone());
333        let read_bytes = usize::try_from(self.memory_budget().resolved_bytes / 16)
334            .unwrap_or(usize::MAX)
335            .clamp(1, 16 * 1024 * 1024);
336        let mut entity = manager.try_get(id, read_bytes)?.filter(|candidate| {
337            candidate.logical_id() == id
338                && super::impl_core::entity_visible_with_context(Some(&snapshot), candidate)
339        });
340        // Public IDs are logical identities. A direct physical lookup can
341        // return a superseded version or miss the version visible to a reader.
342        if entity.is_none() {
343            manager.try_for_each_entity(read_bytes, |candidate| {
344                if candidate.logical_id() == id
345                    && super::impl_core::entity_visible_with_context(Some(&snapshot), candidate)
346                    && entity.as_ref().is_none_or(|selected: &UnifiedEntity| {
347                        (candidate.xmin, candidate.id) > (selected.xmin, selected.id)
348                    })
349                {
350                    entity = Some(candidate.clone());
351                }
352                true
353            })?;
354        }
355        manager.restore_owned_row_schemas(entity.iter_mut());
356        Ok(entity.filter(|entity| {
357            crate::runtime::rls_injection::entity_passes_rls_action(
358                self, collection, action, entity,
359            )
360        }))
361    }
362
363    pub(crate) fn native_read_snapshot(
364        &self,
365    ) -> RedDBResult<(
366        super::impl_core::SnapshotContext,
367        crate::storage::transaction::snapshot::SnapshotRetentionGuard,
368    )> {
369        let state = &self.inner.transaction_state;
370        let manager = state.snapshot_manager();
371        if let Some(context) = super::impl_core::capture_current_snapshot()
372            .filter(|context| Arc::ptr_eq(&context.manager, &manager))
373        {
374            let (_, retention) = manager.retain_snapshot(context.snapshot.clone());
375            return Ok((context, retention));
376        }
377        let connection_id = super::impl_core::current_connection_id();
378        let store = self.inner.db.store();
379        let uses_vcs = self.vcs_has_versioned_collections()?;
380        let _publication = uses_vcs.then(|| store.vault_publication_lock.lock());
381        let (snapshot, retention) = state.retained_current_snapshot(connection_id);
382        let branch = if uses_vcs {
383            self.vcs_branch_read_view(&snapshot, None)?
384        } else {
385            None
386        };
387        let context = state.context(connection_id);
388        Ok((
389            super::impl_core::SnapshotContext {
390                branch,
391                snapshot,
392                manager,
393                own_xids: self.own_transaction_xids(),
394                requires_index_fallback: true,
395                hidden_writers_only: false,
396                serializable_reader: context
397                    .filter(|context| {
398                        context.isolation
399                            == crate::storage::transaction::IsolationLevel::Serializable
400                    })
401                    .map(|context| context.xid),
402            },
403            retention,
404        ))
405    }
406
407    pub fn catalog(&self) -> CatalogModelSnapshot {
408        self.inner.db.catalog_model_snapshot()
409    }
410
411    /// Fallible catalog for disk-resident databases. The decode workspace shares
412    /// query admission with concurrent reads and is released on every error.
413    pub fn try_catalog(&self) -> RedDBResult<CatalogModelSnapshot> {
414        if self
415            .inner
416            .db
417            .store()
418            .config()
419            .resident_memory_bytes_max
420            .is_none()
421        {
422            return Ok(self.catalog());
423        }
424        let read_bytes = usize::try_from(self.memory_budget().resolved_bytes / 16)
425            .unwrap_or(usize::MAX)
426            .clamp(1, 16 * 1024 * 1024);
427        let _scratch = self
428            .try_reserve_query_buffer(read_bytes * 2)
429            .ok_or_else(|| {
430                self.memory_accounting().record_admission_denied();
431                RedDBError::MaterializationLimitExceeded {
432                    executor: "catalog",
433                    limit: usize::try_from(self.memory_budget().resolved_bytes)
434                        .unwrap_or(usize::MAX),
435                    current: usize::try_from(self.memory_accounting().total_used_bytes())
436                        .unwrap_or(usize::MAX)
437                        .saturating_add(1),
438                }
439            })?;
440        Ok(self.inner.db.try_catalog_model_snapshot(read_bytes)?)
441    }
442
443    /// Fallible catalog inventory, optionally scoped to known collection
444    /// names. This keeps `red.collections` queries from decoding collection
445    /// payloads they do not project, and filtered ones from touching
446    /// unrelated collections at all.
447    pub(crate) fn try_catalog_for_collections(
448        &self,
449        collection_names: Option<&std::collections::HashSet<String>>,
450        observe_legacy_payloads: bool,
451    ) -> RedDBResult<CatalogModelSnapshot> {
452        if self
453            .inner
454            .db
455            .store()
456            .config()
457            .resident_memory_bytes_max
458            .is_none()
459        {
460            return Ok(self.inner.db.try_catalog_model_snapshot_for_collections(
461                collection_names,
462                observe_legacy_payloads,
463                usize::MAX,
464            )?);
465        }
466        let read_bytes = usize::try_from(self.memory_budget().resolved_bytes / 16)
467            .unwrap_or(usize::MAX)
468            .clamp(1, 16 * 1024 * 1024);
469        let _scratch = self
470            .try_reserve_query_buffer(read_bytes * 2)
471            .ok_or_else(|| {
472                self.memory_accounting().record_admission_denied();
473                RedDBError::MaterializationLimitExceeded {
474                    executor: "catalog",
475                    limit: usize::try_from(self.memory_budget().resolved_bytes)
476                        .unwrap_or(usize::MAX),
477                    current: usize::try_from(self.memory_accounting().total_used_bytes())
478                        .unwrap_or(usize::MAX)
479                        .saturating_add(1),
480                }
481            })?;
482        Ok(self.inner.db.try_catalog_model_snapshot_for_collections(
483            collection_names,
484            observe_legacy_payloads,
485            read_bytes,
486        )?)
487    }
488
489    pub fn catalog_consistency_report(&self) -> crate::catalog::CatalogConsistencyReport {
490        self.inner.db.catalog_consistency_report()
491    }
492
493    pub fn catalog_attention_summary(&self) -> CatalogAttentionSummary {
494        crate::catalog::attention_summary(&self.catalog())
495    }
496
497    pub fn collection_attention(&self) -> Vec<CollectionDescriptor> {
498        crate::catalog::collection_attention(&self.catalog())
499    }
500
501    pub fn index_attention(&self) -> Vec<CatalogIndexStatus> {
502        crate::catalog::index_attention(&self.catalog())
503    }
504
505    pub fn graph_projection_attention(&self) -> Vec<CatalogGraphProjectionStatus> {
506        crate::catalog::graph_projection_attention(&self.catalog())
507    }
508
509    pub fn analytics_job_attention(&self) -> Vec<CatalogAnalyticsJobStatus> {
510        crate::catalog::analytics_job_attention(&self.catalog())
511    }
512
513    pub fn stats(&self) -> RuntimeStats {
514        let pool = runtime_pool_lock(self);
515        RuntimeStats {
516            active_connections: pool.active,
517            idle_connections: pool.idle.len(),
518            total_checkouts: pool.total_checkouts,
519            paged_mode: self.inner.db.is_paged(),
520            started_at_unix_ms: self.inner.started_at_unix_ms,
521            store: self.inner.db.stats(),
522            system: SystemInfo::collect(),
523            result_blob_cache: self.inner.result_blob_cache.stats(),
524            kv: self.inner.kv_stats.snapshot(),
525            metrics_ingest: self.inner.metrics_ingest_stats.snapshot(),
526        }
527    }
528}
529
530#[cfg(test)]
531mod security_boundary_tests {
532    use super::*;
533    use crate::application::entity::{DeleteEntityInput, PatchEntityInput};
534    use crate::application::ports::RuntimeEntityPort;
535    use crate::auth::Role;
536    use crate::runtime::execution_context::{with_snapshot_bundle, SnapshotBundle};
537    use crate::storage::{EntityData, UnifiedEntity};
538    use reddb_types::Value;
539
540    fn text_field<'a>(entity: &'a UnifiedEntity, name: &str) -> Option<&'a str> {
541        let EntityData::Row(row) = &entity.data else {
542            return None;
543        };
544        let value = row
545            .named
546            .as_ref()
547            .and_then(|named| named.get(name))
548            .or_else(|| {
549                row.schema.as_ref().and_then(|schema| {
550                    schema
551                        .iter()
552                        .position(|column| column == name)
553                        .and_then(|index| row.columns.get(index))
554                })
555            })?;
556        match value {
557            Value::Text(value) => Some(value.as_ref()),
558            _ => None,
559        }
560    }
561
562    #[test]
563    fn typed_entity_boundary_filters_before_pagination_and_hides_foreign_ids() {
564        let runtime = RedDBRuntime::in_memory().expect("runtime");
565        runtime
566            .execute_query(
567                "CREATE TABLE docs (id INT, tenant_id TEXT, body TEXT) TENANT BY (tenant_id)",
568            )
569            .expect("tenant table");
570        runtime
571            .execute_query(
572                "INSERT INTO docs (id, tenant_id, body) VALUES \
573                 (1, 'acme', 'first'), (2, 'globex', 'hidden'), (3, 'acme', 'second')",
574            )
575            .expect("seed platform rows");
576
577        let unfiltered = runtime
578            .scan_collection("docs", None, 10)
579            .expect("platform scan");
580        let foreign_id = unfiltered
581            .items
582            .iter()
583            .find(|entity| text_field(entity, "tenant_id") == Some("globex"))
584            .map(|entity| entity.id)
585            .expect("foreign row");
586
587        let bundle = SnapshotBundle {
588            snapshot: None,
589            auth: Some(("alice".to_string(), Role::Write)),
590            auth_principal: Some(crate::auth::UserId::scoped("acme", "alice")),
591            tenant: Some("acme".to_string()),
592        };
593        with_snapshot_bundle(&bundle, || {
594            let first = runtime
595                .scan_collection("docs", None, 1)
596                .expect("first visible page");
597            assert_eq!(first.total, 2);
598            assert_eq!(first.items.len(), 1);
599            assert_eq!(text_field(&first.items[0], "tenant_id"), Some("acme"));
600            assert_eq!(first.next, Some(ScanCursor { offset: 1 }));
601
602            let second = runtime
603                .scan_collection("docs", first.next, 1)
604                .expect("second visible page");
605            assert_eq!(second.total, 2);
606            assert_eq!(second.items.len(), 1);
607            assert_eq!(text_field(&second.items[0], "tenant_id"), Some("acme"));
608            assert_eq!(second.next, None);
609
610            assert!(runtime
611                .get_collection_entity("docs", foreign_id)
612                .expect("typed get")
613                .is_none());
614            assert!(matches!(
615                runtime.patch_entity(PatchEntityInput {
616                    collection: "docs".to_string(),
617                    id: foreign_id,
618                    payload: crate::json::Value::Object(Default::default()),
619                    operations: Vec::new(),
620                }),
621                Err(crate::RedDBError::NotFound(_))
622            ));
623            let deleted = runtime
624                .delete_entity(DeleteEntityInput {
625                    collection: "docs".to_string(),
626                    id: foreign_id,
627                })
628                .expect("typed delete");
629            assert!(!deleted.deleted);
630        });
631
632        assert!(runtime.db().store().get("docs", foreign_id).is_some());
633    }
634
635    #[test]
636    fn scan_collection_pages_the_mvcc_view_across_rollback() {
637        let runtime = RedDBRuntime::in_memory().expect("runtime");
638        runtime
639            .execute_query("CREATE TABLE docs (id INT, body TEXT)")
640            .expect("table");
641        runtime
642            .execute_query("INSERT INTO docs (id, body) VALUES (1, 'kept')")
643            .expect("seed row");
644
645        runtime.execute_query("BEGIN").expect("begin");
646        runtime
647            .execute_query("DELETE FROM docs WHERE id = 1")
648            .expect("delete in transaction");
649        let deleted = runtime
650            .scan_collection("docs", None, 1)
651            .expect("scan own transaction");
652        assert_eq!(deleted.total, 0);
653        assert!(deleted.items.is_empty());
654
655        runtime.execute_query("ROLLBACK").expect("rollback");
656        let restored = runtime
657            .scan_collection("docs", None, 1)
658            .expect("scan after rollback");
659        assert_eq!(restored.total, 1);
660        assert_eq!(restored.items.len(), 1);
661        assert_eq!(text_field(&restored.items[0], "body"), Some("kept"));
662        assert_eq!(restored.next, None);
663    }
664
665    #[test]
666    fn typed_entity_boundary_uses_model_specific_rls_policies() {
667        let runtime = RedDBRuntime::in_memory().expect("runtime");
668        for query in [
669            "CREATE GRAPH links",
670            "INSERT INTO links NODE (label,node_type,visible) VALUES ('shown','Item',true)",
671            "INSERT INTO links NODE (label,node_type,visible) VALUES ('hidden','Item',false)",
672            "CREATE POLICY visible_nodes ON NODES OF links FOR SELECT USING (properties.visible=true)",
673            "ALTER TABLE links ENABLE ROW LEVEL SECURITY",
674            "CREATE DOCUMENT papers",
675            "INSERT INTO papers DOCUMENT VALUES ({name:'shown',visible:true})",
676            "INSERT INTO papers DOCUMENT VALUES ({name:'hidden',visible:false})",
677            "CREATE POLICY visible_documents ON DOCUMENTS OF papers FOR SELECT USING (visible=true)",
678            "ALTER TABLE papers ENABLE ROW LEVEL SECURITY",
679        ] {
680            runtime.execute_query(query).expect(query);
681        }
682
683        let bundle = SnapshotBundle {
684            snapshot: None,
685            auth: Some(("alice".to_string(), Role::Read)),
686            auth_principal: Some(crate::auth::UserId::platform("alice")),
687            tenant: None,
688        };
689        with_snapshot_bundle(&bundle, || {
690            let nodes = runtime
691                .scan_collection("links", None, 10)
692                .expect("typed graph scan");
693            assert_eq!(nodes.total, 1);
694            assert_eq!(nodes.items.len(), 1);
695
696            let documents = runtime
697                .scan_collection("papers", None, 10)
698                .expect("typed document scan");
699            assert_eq!(documents.total, 1);
700            assert_eq!(documents.items.len(), 1);
701        });
702    }
703}
704
705#[cfg(test)]
706mod checkpoint_cut_test {
707    use crate::{api::DurabilityMode, RedDBOptions, RedDBRuntime};
708    use std::{cell::RefCell, path::Path, sync::mpsc, sync::Arc, thread, time::Duration};
709
710    thread_local! {
711        static CUT: RefCell<Option<(mpsc::Sender<()>, mpsc::Receiver<()>)>> = const { RefCell::new(None) };
712    }
713
714    pub(super) fn after_data_cut() {
715        if let Some((ready, resume)) = CUT.take() {
716            ready.send(()).unwrap();
717            resume
718                .recv_timeout(Duration::from_secs(30))
719                .expect("resume metadata publication");
720        }
721    }
722
723    fn open(path: &Path) -> RedDBRuntime {
724        RedDBRuntime::with_options(
725            RedDBOptions::persistent(path)
726                .with_memory_budget(64 * 1024 * 1024)
727                .with_bounded_disk_residency(true)
728                .with_durability_mode(DurabilityMode::Strict),
729        )
730        .unwrap()
731    }
732
733    #[test]
734    fn completed_metadata_pass_preserves_post_snapshot_sql_and_sketch() {
735        const CHILD: &str = "REDDB_TEST_POST_SNAPSHOT_SQL_AND_SKETCH";
736        const INTERRUPT: &str = "REDDB_TEST_INTERRUPT_METADATA_PASS";
737        if let Some(path) = std::env::var_os(CHILD) {
738            let db = Arc::new(open(Path::new(&path)));
739            for sql in [
740                "CREATE TABLE late_rows (v INTEGER)",
741                "CREATE SKETCH late_counts",
742                "SKETCH ADD late_counts 'red' 3",
743            ] {
744                db.execute_query(sql).unwrap();
745            }
746            let (ready, cut) = mpsc::channel();
747            let (resume, proceed) = mpsc::channel();
748            let checkpoint = Arc::clone(&db);
749            let builder = thread::spawn(move || {
750                CUT.set(Some((ready, proceed)));
751                checkpoint.checkpoint().unwrap();
752            });
753            cut.recv_timeout(Duration::from_secs(60))
754                .expect("durable data cut");
755            assert_eq!(
756                db.execute_query("INSERT INTO late_rows (v) VALUES (42)")
757                    .unwrap()
758                    .affected_rows,
759                1
760            );
761            db.execute_query("SKETCH ADD late_counts 'red' 4").unwrap();
762            if let Ok(point) = std::env::var(INTERRUPT) {
763                std::env::set_var(point, "1");
764            }
765            resume.send(()).unwrap();
766            builder.join().unwrap();
767            std::process::exit(72);
768        }
769        for (interrupt, exit_code) in [
770            (None, 72),
771            (Some("REDDB_TEST_EXIT_BEFORE_CATALOG_ROOT_PUBLICATION"), 197),
772            (Some("REDDB_TEST_EXIT_AFTER_CATALOG_ROOT_PUBLICATION"), 198),
773        ] {
774            let directory = tempfile::tempdir().unwrap();
775            let path = directory.path().join("cut.rdb");
776            let mut child = std::process::Command::new(std::env::current_exe().unwrap());
777            child
778                .args(["--exact", "runtime::impl_catalog_accessors::checkpoint_cut_test::completed_metadata_pass_preserves_post_snapshot_sql_and_sketch", "--nocapture"])
779                .env(CHILD, &path).env_remove(INTERRUPT);
780            if let Some(point) = interrupt {
781                child.env(INTERRUPT, point);
782            }
783            let child = child.output().unwrap();
784            assert_eq!(
785                child.status.code(),
786                Some(exit_code),
787                "{}",
788                String::from_utf8_lossy(&child.stderr)
789            );
790            let db = open(&path);
791            let physical = db
792                .db()
793                .physical_metadata()
794                .expect("recover physical metadata");
795            assert!(physical
796                .superblock
797                .collection_roots
798                .contains_key("late_rows"));
799            if interrupt.is_none() {
800                let header = db
801                    .db()
802                    .store()
803                    .physical_file_header()
804                    .expect("physical header");
805                assert_eq!(header.sequence, physical.superblock.sequence);
806            }
807            let rows = db
808                .execute_query("SELECT v FROM late_rows")
809                .unwrap()
810                .result
811                .records;
812            assert_eq!(rows.len(), 1);
813            assert_eq!(rows[0].get("v"), Some(&reddb_types::Value::Integer(42)));
814            let counts = db.execute_query("SKETCH COUNT late_counts 'red'").unwrap();
815            assert_eq!(
816                counts.result.records[0]
817                    .get("estimate")
818                    .unwrap()
819                    .display_string(),
820                "7"
821            );
822        }
823    }
824}