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