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