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