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