1use std::cell::RefCell;
2use std::collections::HashSet;
3use std::rc::Rc;
4use std::sync::Arc;
5
6use super::execution_context::capture_current_snapshot;
7use super::impl_core::{
8 collections_referenced, current_auth_identity, current_connection_id, current_tenant,
9 has_with_prefix, intent_lock_modes_for, peek_top_level_as_of_with_table,
10 query_has_volatile_builtin, query_is_ask_statement, ConfigSnapshotGuard, CurrentSnapshotGuard,
11 KvStoreGuard, SecretStoreGuard, SnapshotContext, TxLocalTenantGuard,
12};
13use super::{RedDBRuntime, RuntimeQueryResult, RuntimeResultCacheEntry};
14use crate::api::{RedDBError, RedDBResult};
15use crate::auth::Role;
16use crate::storage::transaction::snapshot::{Snapshot, SnapshotRetentionGuard, Xid};
17use reddb_rql::ast::QueryExpr;
18use reddb_rql::modes::{detect_mode, parse_multi, QueryMode};
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub(crate) enum Privilege {
31 Read,
34 Write,
38 Admin,
41 None,
45}
46
47impl Privilege {
48 pub(crate) fn is_satisfied_by(self, role: Role) -> bool {
52 match self {
53 Self::None => true,
54 Self::Read => role.can_read(),
55 Self::Write => role.can_write(),
56 Self::Admin => role.can_admin(),
57 }
58 }
59}
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub(crate) enum LockIntent {
68 None,
71 Shared,
74 Exclusive,
79}
80
81pub(crate) trait ReadFrame {
94 fn effective_scope(&self) -> Option<&str>;
98
99 fn identity(&self) -> Option<(&str, Role)>;
103
104 fn auth_principal(&self) -> Option<&crate::auth::UserId> {
106 None
107 }
108
109 fn snapshot(&self) -> &Snapshot;
114
115 fn snapshot_context(&self, runtime: &RedDBRuntime) -> SnapshotContext {
117 SnapshotContext {
118 branch: None,
119 snapshot: self.snapshot().clone(),
120 manager: runtime.inner.transaction_state.snapshot_manager(),
121 own_xids: HashSet::new(),
122 requires_index_fallback: true,
123 hidden_writers_only: false,
124 serializable_reader: None,
125 }
126 }
127
128 fn as_of_floor(&self) -> Option<Xid>;
133
134 fn cache_key(&self) -> &str;
137
138 fn should_cache_result(&self) -> bool;
152
153 fn required_privilege(&self) -> Privilege;
162
163 fn lock_intent(&self) -> LockIntent;
172
173 fn visible_collections(&self) -> Option<&std::collections::HashSet<String>>;
186}
187
188pub(crate) fn statement_is_write(query: &str) -> bool {
197 statement_kind(query) == "write"
198}
199
200fn statement_kind(query: &str) -> &'static str {
201 let trimmed = query.trim_start();
202 let trimmed = if let Some(rest) = trimmed.strip_prefix("--") {
205 rest.split_once('\n')
206 .map(|(_, r)| r)
207 .unwrap_or("")
208 .trim_start()
209 } else {
210 trimmed
211 };
212 let mut tokens = trimmed.split(|c: char| c.is_whitespace() || c == '(' || c == ';');
213 let first = tokens.next().unwrap_or("");
214 let second = tokens.next().unwrap_or("");
215 if first.eq_ignore_ascii_case("KV") {
216 if second.eq_ignore_ascii_case("GET")
217 || second.eq_ignore_ascii_case("LIST")
218 || second.eq_ignore_ascii_case("WATCH")
219 {
220 return "read";
221 }
222 return "write";
223 }
224 if first.eq_ignore_ascii_case("VAULT") {
225 if second.eq_ignore_ascii_case("GET")
226 || second.eq_ignore_ascii_case("REVEAL")
227 || second.eq_ignore_ascii_case("UNSEAL")
228 || second.eq_ignore_ascii_case("LIST")
229 || second.eq_ignore_ascii_case("WATCH")
230 || second.eq_ignore_ascii_case("HISTORY")
231 {
232 return "read";
233 }
234 return "write";
235 }
236 let mut buf = [0u8; 16];
238 let bytes = first.as_bytes();
239 let n = bytes.len().min(buf.len());
240 for i in 0..n {
241 buf[i] = bytes[i].to_ascii_uppercase();
242 }
243 match &buf[..n] {
244 b"SELECT" | b"WITH" | b"SHOW" | b"EXPLAIN" | b"DESCRIBE" | b"DESC" | b"RANK"
245 | b"APPROX" | b"APPROXIMATE" | b"ZRANK" | b"ZRANGE" | b"LIST" | b"WATCH" | b"GET"
246 | b"HISTORY" | b"REVEAL" | b"UNSEAL" => "read",
247 b"INSERT" | b"UPDATE" | b"DELETE" | b"UPSERT" | b"MERGE" | b"COPY" | b"TRUNCATE" => "write",
248 b"CREATE" | b"ALTER" | b"DROP" | b"PROMOTE" | b"REINDEX" | b"VACUUM" | b"ANALYZE" => "ddl",
249 b"GRANT" | b"REVOKE" => "admin",
250 b"BEGIN" | b"START" | b"COMMIT" | b"ROLLBACK" | b"SAVEPOINT" | b"RELEASE" | b"END"
251 | b"SET" | b"RESET" | b"PREPARE" | b"EXECUTE" | b"DEALLOCATE" | b"USE" => "control",
252 b"PUT" | b"INCR" | b"DECR" | b"ADD" | b"ROTATE" | b"PURGE" | b"INVALIDATE" => "write",
253 b"SCRUB" => "uncached",
254 _ => "unknown",
255 }
256}
257
258fn statement_uses_result_cache(query: &str) -> bool {
259 !matches!(
260 statement_kind(query),
261 "write" | "ddl" | "admin" | "control" | "uncached"
262 ) && !super::red_schema::is_computed_stats_query(query)
263}
264
265fn reject_unresolvable_as_of(expr: &QueryExpr) -> RedDBResult<()> {
277 let QueryExpr::Table(table) = expr else {
278 return Ok(());
279 };
280 if table.as_of.is_none() {
281 return Ok(());
282 }
283 Err(RedDBError::InvalidOperation(
284 "AS OF cannot be resolved from a pre-parsed expression — \
285 execute the statement text (execute_query / execute_prepared_query / \
286 execute_query_with_params) so the historical snapshot is resolved"
287 .to_string(),
288 ))
289}
290
291fn classify_privilege(query: &str) -> Privilege {
292 match statement_kind(query) {
293 "read" => Privilege::Read,
294 "write" => Privilege::Write,
295 "ddl" => Privilege::Write,
301 "admin" => Privilege::Admin,
302 _ => Privilege::None,
303 }
304}
305
306fn classify_lock_intent(query: &str) -> LockIntent {
307 match statement_kind(query) {
308 "read" => LockIntent::Shared,
309 "write" | "ddl" => LockIntent::Exclusive,
310 _ => LockIntent::None,
311 }
312}
313
314pub(super) struct StatementExecutionFrame {
315 branch: Option<Arc<reddb_engine::transaction::read::BranchReadView>>,
316 tx_local_tenant: Option<Option<String>>,
317 snapshot: Snapshot,
318 snapshot_retention: RefCell<Option<SnapshotRetentionGuard>>,
319 own_xids: HashSet<Xid>,
320 serializable_reader: Option<Xid>,
321 cache_key: String,
322 cache_data_epoch: Option<u64>,
323 cache_revision: u64,
324 is_volatile_query: bool,
325 cache_safe: bool,
326 effective_scope: Option<String>,
331 identity: Option<(String, Role)>,
334 auth_principal: Option<crate::auth::UserId>,
335 as_of_floor: Option<Xid>,
338 requires_index_fallback: bool,
341 hidden_writers_only: bool,
342 required_privilege: Privilege,
346 lock_intent: LockIntent,
349 visible_collections: Option<HashSet<String>>,
356 row_arena: Rc<RefCell<super::query_exec::RowBufferArena>>,
364}
365
366pub(super) struct StatementFrameGuards {
367 _tx_local_guard: TxLocalTenantGuard,
368 _config_snapshot_guard: ConfigSnapshotGuard,
369 _secret_store_guard: SecretStoreGuard,
370 _kv_store_guard: KvStoreGuard,
371 _snapshot_guard: CurrentSnapshotGuard,
372}
373
374pub(super) struct PreparedStatement {
375 pub(super) expr: QueryExpr,
376 pub(super) mode: QueryMode,
377}
378
379#[derive(Clone, Copy)]
388pub(super) enum StatementIdentity<'a> {
389 Text(&'a str),
391 UncachedText(&'a str),
394 Expr(&'a QueryExpr),
406}
407
408impl<'a> StatementIdentity<'a> {
409 fn text(&self) -> &'a str {
413 match self {
414 Self::Text(query) | Self::UncachedText(query) => query,
415 Self::Expr(_) => "",
416 }
417 }
418}
419
420impl StatementExecutionFrame {
421 pub(super) fn build(
422 runtime: &RedDBRuntime,
423 identity_source: StatementIdentity<'_>,
424 ) -> RedDBResult<Self> {
425 let query = identity_source.text();
426 let uses_result_cache = matches!(identity_source, StatementIdentity::Text(query) if statement_uses_result_cache(query));
427 let (cache_data_epoch, cache_revision) = match identity_source {
428 StatementIdentity::Text(_) if uses_result_cache => runtime.result_cache_snapshot(),
429 StatementIdentity::Text(_)
430 | StatementIdentity::UncachedText(_)
431 | StatementIdentity::Expr(_) => (None, 0),
432 };
433 if let StatementIdentity::Expr(expr) = identity_source {
434 reject_unresolvable_as_of(expr)?;
435 }
436 let conn_id = current_connection_id();
437 let tx_local_tenant = runtime.inner.transaction_state.local_tenant(conn_id);
438 let tx_context = runtime.inner.transaction_state.context(conn_id);
439 let mut own_xids = own_transaction_xids(tx_context.as_ref());
440 let graph_insert_xid = runtime.graph_insert_xid();
441 if let Some(xid) = graph_insert_xid {
442 own_xids.insert(xid);
443 }
444 let serializable_reader = tx_context
445 .as_ref()
446 .filter(|ctx| {
447 ctx.isolation == crate::storage::transaction::IsolationLevel::Serializable
448 })
449 .map(|ctx| ctx.xid);
450 let (snapshot, as_of_floor, snapshot_retention, branch) = {
451 let store = runtime.db().store();
452 let uses_vcs = runtime.vcs_has_versioned_collections()?;
453 let _publication = uses_vcs.then(|| store.vault_publication_lock.lock());
454 let (snapshot, as_of_floor, retention) =
455 runtime.statement_snapshot(query, identity_source)?;
456 let as_of = peek_top_level_as_of_with_table(query).map(|(spec, _)| spec);
457 let branch = if uses_vcs {
458 runtime.vcs_branch_read_view(&snapshot, as_of.as_ref())?
459 } else {
460 None
461 };
462 (snapshot, as_of_floor, retention, branch)
463 };
464 if as_of_floor.is_some() {
465 own_xids.clear();
466 }
467 let hidden_writers_only = !(as_of_floor.is_some()
471 || tx_context.is_some()
472 || graph_insert_xid.is_some()
473 || branch.is_some())
474 && runtime
475 .snapshot_manager()
476 .snapshot_hides_real_writers(&snapshot);
477 let requires_index_fallback = as_of_floor.is_some()
478 || tx_context.is_some()
479 || graph_insert_xid.is_some()
480 || branch.is_some()
481 || hidden_writers_only;
482 let (cache_key, is_volatile_query) = match identity_source {
483 StatementIdentity::Text(_) if uses_result_cache => (
484 result_cache_key(query),
485 query_has_volatile_builtin(query) || query_is_ask_statement(query),
486 ),
487 StatementIdentity::Text(_)
492 | StatementIdentity::UncachedText(_)
493 | StatementIdentity::Expr(_) => (String::new(), true),
494 };
495 let cache_safe = as_of_floor.is_none()
498 && branch.is_none()
499 && graph_insert_xid.is_none()
500 && runtime.result_cache_safe(conn_id);
501 let effective_scope = current_tenant();
506 let identity = current_auth_identity();
507
508 let required_privilege = classify_privilege(query);
516 let lock_intent = classify_lock_intent(query);
517
518 let visible_collections = match (runtime.inner.auth_store.read().clone(), identity.as_ref())
524 {
525 (Some(store), Some((principal, role))) => {
526 let collections = runtime.inner.db.store().list_collections();
527 Some(store.visible_collections_for_scope(
528 effective_scope.as_deref(),
529 *role,
530 principal,
531 &collections,
532 ))
533 }
534 _ => None,
535 };
536
537 Ok(Self {
538 branch,
539 tx_local_tenant,
540 snapshot,
541 snapshot_retention: RefCell::new(Some(snapshot_retention)),
542 own_xids,
543 serializable_reader,
544 cache_key,
545 cache_data_epoch,
546 cache_revision,
547 is_volatile_query,
548 cache_safe,
549 effective_scope,
550 identity,
551 auth_principal: super::execution_context::current_auth_principal(),
552 as_of_floor,
553 requires_index_fallback,
554 hidden_writers_only,
555 required_privilege,
556 lock_intent,
557 visible_collections,
558 row_arena: Rc::new(RefCell::new(super::query_exec::RowBufferArena::new())),
559 })
560 }
561
562 pub(super) fn row_arena(&self) -> Rc<RefCell<super::query_exec::RowBufferArena>> {
567 Rc::clone(&self.row_arena)
568 }
569
570 pub(super) fn install(&self, runtime: &RedDBRuntime) -> StatementFrameGuards {
571 StatementFrameGuards {
572 _tx_local_guard: TxLocalTenantGuard::install(self.tx_local_tenant.clone()),
573 _config_snapshot_guard: ConfigSnapshotGuard::install(
574 Arc::clone(&runtime.inner.db),
575 runtime.inner.auth_store.read().clone(),
576 ),
577 _secret_store_guard: SecretStoreGuard::install(runtime),
578 _kv_store_guard: KvStoreGuard::install(runtime.inner.auth_store.read().clone()),
579 _snapshot_guard: CurrentSnapshotGuard::install(SnapshotContext {
580 branch: self.branch.clone(),
581 snapshot: self.snapshot.clone(),
582 manager: runtime.inner.transaction_state.snapshot_manager(),
583 own_xids: self.own_xids.clone(),
584 requires_index_fallback: self.requires_index_fallback,
585 hidden_writers_only: self.hidden_writers_only,
586 serializable_reader: self.serializable_reader,
587 }),
588 }
589 }
590
591 pub(super) fn cache_key(&self) -> &str {
592 &self.cache_key
593 }
594
595 pub(super) fn can_read_result_cache(&self) -> bool {
596 <Self as ReadFrame>::should_cache_result(self)
599 }
600
601 pub(super) fn should_write_result_cache(&self, result: &RuntimeQueryResult) -> bool {
602 <Self as ReadFrame>::should_cache_result(self)
607 && result.statement_type == "select"
608 && result.engine != "vault"
609 && result.engine != "runtime-rank"
610 && result.statement != "queue_group_read"
615 && result.engine != "runtime-scrub"
620 && result.result.pre_serialized_json.is_none()
621 && (is_graph_tvf_engine(result.engine) || result.result.records.len() <= 5)
625 }
626
627 pub(super) fn read_result_cache(&self, runtime: &RedDBRuntime) -> Option<RuntimeQueryResult> {
628 if runtime.resource_limits().read_execution_limits_enabled() {
629 return None;
630 }
631 if self.can_read_result_cache() {
632 runtime
633 .get_result_cache_entry(self.cache_key(), self.cache_data_epoch)
634 .map(|mut result| {
635 if let Some(vector) = result.result.stats.vector.as_mut() {
636 vector.cache_hit = true;
637 }
638 result
639 })
640 } else {
641 None
642 }
643 }
644
645 pub(super) fn write_result_cache(
646 &self,
647 runtime: &RedDBRuntime,
648 result: &RuntimeQueryResult,
649 scopes: HashSet<String>,
650 ) {
651 if self.should_write_result_cache(result) {
652 runtime.put_result_cache_entry(
653 self.cache_key(),
654 RuntimeResultCacheEntry {
655 result: result.clone(),
656 cached_at: std::time::Instant::now(),
657 scopes,
658 data_epoch: self.cache_data_epoch.unwrap_or(0),
659 },
660 self.cache_data_epoch,
661 self.cache_revision,
662 );
663 }
664 }
665
666 pub(super) fn prepare_cte(&self, query: &str) -> RedDBResult<Option<QueryExpr>> {
667 if !has_with_prefix(query) {
676 return Ok(None);
677 }
678 let parsed =
679 reddb_rql::parser::parse(query).map_err(|err| RedDBError::Query(err.to_string()))?;
680 if parsed.with_clause.is_some() {
681 let rewritten = crate::storage::query::executors::inline_ctes(parsed)
682 .map_err(|err| RedDBError::Query(err.to_string()))?;
683 return Ok(Some(rewritten));
684 }
685 Ok(None)
689 }
690
691 pub(super) fn prepare_statement(
692 &self,
693 runtime: &RedDBRuntime,
694 query: &str,
695 ) -> RedDBResult<PreparedStatement> {
696 let mode = detect_mode(query);
697 if matches!(mode, QueryMode::Unknown) {
698 return Err(RedDBError::Query("unable to detect query mode".to_string()));
699 }
700
701 let first_word = query
712 .trim()
713 .split_ascii_whitespace()
714 .next()
715 .unwrap_or("")
716 .to_ascii_uppercase();
717 let is_insert = first_word == "INSERT";
718 let bypass_plan_cache = is_insert || self.is_volatile_query;
724
725 let (cache_key, prescan_binds) = if bypass_plan_cache {
731 (String::new(), Vec::new())
732 } else {
733 crate::storage::query::planner::cache_key::normalize_and_extract(query)
734 };
735
736 let expr = if bypass_plan_cache {
737 parse_multi(query).map_err(|err| RedDBError::Query(err.to_string()))?
739 } else {
740 let hit = {
747 let plan_cache = runtime.inner.query_cache.read();
748 plan_cache.peek(&cache_key).map(|cached| {
749 let parameter_count = cached.parameter_count;
750 let optimized = cached.plan.optimized.clone();
751 let exact_query = cached.exact_query.clone();
752 (parameter_count, optimized, exact_query)
753 })
754 };
755
756 if let Some((parameter_count, optimized, exact_query)) = hit {
757 if parameter_count > 0 {
758 let shape_binds = prescan_binds.clone();
760 if let Some(bound) =
761 crate::storage::query::planner::shape::bind_parameterized_query(
762 &optimized,
763 &shape_binds,
764 parameter_count,
765 )
766 {
767 bound
768 } else {
769 parse_multi(query).map_err(|err| RedDBError::Query(err.to_string()))?
772 }
773 } else {
774 if exact_query.as_deref() == Some(query) {
780 optimized
781 } else {
782 parse_multi(query).map_err(|err| RedDBError::Query(err.to_string()))?
783 }
784 }
785 } else {
786 let parsed =
788 parse_multi(query).map_err(|err| RedDBError::Query(err.to_string()))?;
789 let (cached_expr, parameter_count) = if let Some(prepared) =
790 crate::storage::query::planner::shape::parameterize_query_expr(&parsed)
791 {
792 (prepared.shape, prepared.parameter_count)
793 } else {
794 (parsed.clone(), 0)
795 };
796 {
797 let mut pc = runtime.inner.query_cache.write();
798 let plan = crate::storage::query::planner::QueryPlan::new(
799 parsed.clone(),
800 cached_expr,
801 Default::default(),
802 );
803 pc.insert(
804 cache_key.clone(),
805 crate::storage::query::planner::CachedPlan::new(plan)
806 .with_shape_key(cache_key.clone())
807 .with_exact_query(query.to_string())
808 .with_parameter_count(parameter_count),
809 );
810 }
811 parsed
812 }
813 };
814
815 let expr = runtime.rewrite_view_refs(expr);
820
821 Ok(PreparedStatement { expr, mode })
822 }
823
824 pub(super) fn check_query_privilege(
825 &self,
826 runtime: &RedDBRuntime,
827 expr: &QueryExpr,
828 ) -> RedDBResult<()> {
829 if let Some((username, role)) = <Self as ReadFrame>::identity(self) {
839 let needed = <Self as ReadFrame>::required_privilege(self);
840 if !needed.is_satisfied_by(role) {
841 if matches!(needed, Privilege::Admin) && runtime.inner.auth_store.read().is_none() {
850 crate::telemetry::operator_event::OperatorEvent::AuthBypass {
851 principal: username.to_string(),
852 resource: format!("statement requiring {needed:?}"),
853 detail: format!(
854 "auth_store not wired; coarse gate is sole defence (role={role:?})"
855 ),
856 }
857 .emit_global();
858 }
859 return Err(RedDBError::Query(format!(
860 "permission denied: principal=`{username}` role=`{role:?}` lacks {needed:?} privilege"
861 )));
862 }
863 }
864 runtime
865 .check_query_privilege(expr)
866 .map_err(|err| RedDBError::Query(format!("permission denied: {err}")))
867 }
868
869 pub(super) fn prepare_dispatch(
870 &self,
871 runtime: &RedDBRuntime,
872 expr: &QueryExpr,
873 ) -> RedDBResult<Option<crate::runtime::locking::LockerGuard>> {
874 runtime.validate_model_operations_before_auth(expr)?;
875 self.check_query_privilege(runtime, expr)?;
876 self.release_snapshot_for_maintenance(expr);
877 self.acquire_intent_locks(runtime, expr)
878 }
879
880 pub(super) fn release_snapshot_for_maintenance(&self, expr: &QueryExpr) {
881 if matches!(
882 expr,
883 QueryExpr::MaintenanceCommand(reddb_rql::ast::MaintenanceCommand::Vacuum { .. })
884 ) {
885 self.snapshot_retention.borrow_mut().take();
890 }
891 }
892
893 pub(super) fn acquire_intent_locks(
894 &self,
895 runtime: &RedDBRuntime,
896 expr: &QueryExpr,
897 ) -> RedDBResult<Option<crate::runtime::locking::LockerGuard>> {
898 use crate::runtime::lock_manager::LockMode;
899 use crate::runtime::locking::{LockerGuard, Resource};
900
901 if !runtime.config_bool("concurrency.locking.enabled", true) {
902 return Ok(None);
903 }
904 if matches!(<Self as ReadFrame>::lock_intent(self), LockIntent::None) {
909 return Ok(None);
910 }
911 let Some((global_mode, coll_mode)) = intent_lock_modes_for(expr) else {
912 return Ok(None);
913 };
914 let acquire = |guard: &mut LockerGuard, resource: Resource, mode: LockMode| {
917 guard.acquire(resource.clone(), mode).map_err(|err| {
918 RedDBError::Query(format!(
919 "could not acquire {mode:?} lock on {resource:?}: {err}; retry the statement"
920 ))
921 })
922 };
923 let mut guard = LockerGuard::new(runtime.inner.lock_manager.clone());
924 acquire(&mut guard, Resource::Global, global_mode)?;
925 if coll_mode == LockMode::Exclusive {
930 acquire(&mut guard, Resource::Catalog, LockMode::Exclusive)?;
931 }
932 for collection in collections_referenced(expr) {
933 acquire(&mut guard, Resource::Collection(collection), coll_mode)?;
934 }
935 Ok(Some(guard))
936 }
937}
938
939impl ReadFrame for StatementExecutionFrame {
940 fn snapshot_context(&self, runtime: &RedDBRuntime) -> SnapshotContext {
941 SnapshotContext {
942 branch: self.branch.clone(),
943 snapshot: self.snapshot.clone(),
944 manager: runtime.inner.transaction_state.snapshot_manager(),
945 own_xids: self.own_xids.clone(),
946 requires_index_fallback: self.requires_index_fallback,
947 hidden_writers_only: self.hidden_writers_only,
948 serializable_reader: self.serializable_reader,
949 }
950 }
951
952 fn effective_scope(&self) -> Option<&str> {
953 self.effective_scope.as_deref()
954 }
955
956 fn identity(&self) -> Option<(&str, Role)> {
957 self.identity.as_ref().map(|(u, r)| (u.as_str(), *r))
958 }
959 fn auth_principal(&self) -> Option<&crate::auth::UserId> {
960 self.auth_principal.as_ref()
961 }
962
963 fn snapshot(&self) -> &Snapshot {
964 &self.snapshot
965 }
966
967 fn as_of_floor(&self) -> Option<Xid> {
968 self.as_of_floor
969 }
970
971 fn cache_key(&self) -> &str {
972 &self.cache_key
973 }
974
975 fn should_cache_result(&self) -> bool {
976 !self.is_volatile_query && self.cache_safe
977 }
978
979 fn required_privilege(&self) -> Privilege {
980 self.required_privilege
981 }
982
983 fn lock_intent(&self) -> LockIntent {
984 self.lock_intent
985 }
986
987 fn visible_collections(&self) -> Option<&HashSet<String>> {
988 self.visible_collections.as_ref()
989 }
990}
991
992pub struct EffectiveScope {
1006 pub(crate) captured_snapshot: Option<SnapshotContext>,
1007 pub(crate) tenant: Option<String>,
1008 pub(crate) identity: Option<(String, Role)>,
1009 pub(crate) auth_principal: Option<crate::auth::UserId>,
1010 pub(crate) snapshot: Snapshot,
1011 pub(crate) visible_collections: Option<HashSet<String>>,
1012}
1013
1014impl EffectiveScope {
1015 pub fn has_capability(&self, _capability: &str) -> bool {
1025 false
1026 }
1027}
1028
1029impl ReadFrame for EffectiveScope {
1030 fn snapshot_context(&self, runtime: &RedDBRuntime) -> SnapshotContext {
1031 self.captured_snapshot
1032 .clone()
1033 .unwrap_or_else(|| SnapshotContext {
1034 branch: None,
1035 snapshot: self.snapshot.clone(),
1036 manager: runtime.inner.transaction_state.snapshot_manager(),
1037 own_xids: HashSet::new(),
1038 requires_index_fallback: true,
1039 hidden_writers_only: false,
1040 serializable_reader: None,
1041 })
1042 }
1043
1044 fn effective_scope(&self) -> Option<&str> {
1045 self.tenant.as_deref()
1046 }
1047 fn identity(&self) -> Option<(&str, Role)> {
1048 self.identity.as_ref().map(|(u, r)| (u.as_str(), *r))
1049 }
1050 fn auth_principal(&self) -> Option<&crate::auth::UserId> {
1051 self.auth_principal.as_ref()
1052 }
1053 fn snapshot(&self) -> &Snapshot {
1054 &self.snapshot
1055 }
1056 fn as_of_floor(&self) -> Option<Xid> {
1057 None
1058 }
1059 fn cache_key(&self) -> &str {
1060 ""
1061 }
1062 fn should_cache_result(&self) -> bool {
1063 false
1064 }
1065 fn required_privilege(&self) -> Privilege {
1066 Privilege::Read
1067 }
1068 fn lock_intent(&self) -> LockIntent {
1069 LockIntent::Shared
1070 }
1071 fn visible_collections(&self) -> Option<&HashSet<String>> {
1072 self.visible_collections.as_ref()
1073 }
1074}
1075
1076fn own_transaction_xids(
1077 ctx: Option<&crate::storage::transaction::snapshot::TxnContext>,
1078) -> HashSet<Xid> {
1079 let mut set = HashSet::new();
1080 if let Some(ctx) = ctx {
1081 set.insert(ctx.xid);
1082 for (_, sub) in &ctx.savepoints {
1083 set.insert(*sub);
1084 }
1085 for sub in &ctx.released_sub_xids {
1086 set.insert(*sub);
1087 }
1088 }
1089 set
1090}
1091
1092impl RedDBRuntime {
1093 pub(crate) fn ai_scope(&self) -> EffectiveScope {
1099 let tenant = super::impl_core::current_tenant();
1100 let identity = super::impl_core::current_auth_identity();
1101 let auth_principal = super::execution_context::current_auth_principal();
1102 let captured_snapshot = super::execution_context::capture_current_snapshot();
1103 let snapshot = captured_snapshot.as_ref().map_or_else(
1104 || self.current_snapshot(),
1105 |context| context.snapshot.clone(),
1106 );
1107 let visible_collections = match (self.inner.auth_store.read().clone(), identity.as_ref()) {
1108 (Some(store), Some((principal, role))) => {
1109 let collections = self.inner.db.store().list_collections();
1110 Some(store.visible_collections_for_scope(
1111 tenant.as_deref(),
1112 *role,
1113 principal,
1114 &collections,
1115 ))
1116 }
1117 _ => None,
1118 };
1119 EffectiveScope {
1120 captured_snapshot,
1121 tenant,
1122 identity,
1123 auth_principal,
1124 snapshot,
1125 visible_collections,
1126 }
1127 }
1128}
1129
1130#[cfg(test)]
1134pub(crate) mod test_support {
1135 use super::{LockIntent, Privilege, ReadFrame};
1136 use crate::auth::Role;
1137 use crate::storage::transaction::snapshot::{Snapshot, Xid};
1138 use std::collections::HashSet;
1139
1140 pub(crate) struct FakeReadFrame {
1144 pub tenant: Option<String>,
1145 pub identity: Option<(String, Role)>,
1146 pub snapshot: Snapshot,
1147 pub visible: Option<HashSet<String>>,
1148 }
1149
1150 impl FakeReadFrame {
1151 pub(crate) fn without_scope() -> Self {
1152 Self {
1153 tenant: None,
1154 identity: None,
1155 snapshot: Snapshot {
1156 xid: 0,
1157 in_progress: HashSet::new(),
1158 },
1159 visible: None,
1160 }
1161 }
1162
1163 pub(crate) fn with_visible(visible: HashSet<String>) -> Self {
1164 Self {
1165 tenant: Some("acme".to_string()),
1166 identity: Some(("alice".to_string(), Role::Read)),
1167 snapshot: Snapshot {
1168 xid: 0,
1169 in_progress: HashSet::new(),
1170 },
1171 visible: Some(visible),
1172 }
1173 }
1174 }
1175
1176 impl ReadFrame for FakeReadFrame {
1177 fn effective_scope(&self) -> Option<&str> {
1178 self.tenant.as_deref()
1179 }
1180 fn identity(&self) -> Option<(&str, Role)> {
1181 self.identity.as_ref().map(|(u, r)| (u.as_str(), *r))
1182 }
1183 fn snapshot(&self) -> &Snapshot {
1184 &self.snapshot
1185 }
1186 fn as_of_floor(&self) -> Option<Xid> {
1187 None
1188 }
1189 fn cache_key(&self) -> &str {
1190 ""
1191 }
1192 fn should_cache_result(&self) -> bool {
1193 false
1194 }
1195 fn required_privilege(&self) -> Privilege {
1196 Privilege::Read
1197 }
1198 fn lock_intent(&self) -> LockIntent {
1199 LockIntent::Shared
1200 }
1201 fn visible_collections(&self) -> Option<&HashSet<String>> {
1202 self.visible.as_ref()
1203 }
1204 }
1205}
1206
1207impl RedDBRuntime {
1208 fn statement_snapshot(
1238 &self,
1239 query: &str,
1240 identity: StatementIdentity<'_>,
1241 ) -> RedDBResult<(Snapshot, Option<Xid>, SnapshotRetentionGuard)> {
1242 match peek_top_level_as_of_with_table(query) {
1243 Some((spec, Some(table))) => {
1244 if !table.starts_with("red_")
1245 && !table.starts_with("red.")
1246 && !self.vcs_is_versioned(&table)?
1247 {
1248 return Err(RedDBError::InvalidConfig(format!(
1249 "AS OF requires a versioned collection — \
1250 `{table}` has not opted in. \
1251 Call vcs.set_versioned(\"{table}\", true) first."
1252 )));
1253 }
1254 let snapshot = self.vcs_resolve_snapshot(spec)?;
1255 let xid = snapshot.xid;
1256 let (snapshot, retention) = self.snapshot_manager().retain_snapshot(snapshot);
1257 Ok((snapshot, Some(xid), retention))
1258 }
1259 Some((spec, None)) => {
1260 let snapshot = self.vcs_resolve_snapshot(spec)?;
1261 let xid = snapshot.xid;
1262 let (snapshot, retention) = self.snapshot_manager().retain_snapshot(snapshot);
1263 Ok((snapshot, Some(xid), retention))
1264 }
1265 None => match (identity, capture_current_snapshot()) {
1266 (StatementIdentity::Expr(_), Some(outer)) => {
1267 let (snapshot, retention) =
1268 self.snapshot_manager().retain_snapshot(outer.snapshot);
1269 Ok((snapshot, None, retention))
1270 }
1271 _ => {
1272 let (snapshot, retention) = self
1273 .inner
1274 .transaction_state
1275 .retained_current_snapshot(current_connection_id());
1276 Ok((snapshot, None, retention))
1277 }
1278 },
1279 }
1280 }
1281
1282 fn result_cache_safe(&self, conn_id: u64) -> bool {
1283 let has_unsafe_xids = self
1284 .inner
1285 .transaction_state
1286 .snapshot_manager()
1287 .has_cache_unsafe_active_xids();
1288 let in_own_tx = self.inner.transaction_state.in_transaction(conn_id);
1289 !has_unsafe_xids && !in_own_tx
1290 }
1291}
1292
1293fn is_graph_tvf_engine(engine: &str) -> bool {
1298 matches!(engine, "runtime-graph-tvf" | "runtime-graph-tvf-inline")
1299}
1300
1301fn result_cache_key(query: &str) -> String {
1302 let tenant = current_tenant().unwrap_or_default();
1303 let auth = current_auth_identity()
1304 .map(|(user, role)| format!("{}|{:?}", user, role))
1305 .unwrap_or_default();
1306 if tenant.is_empty() && auth.is_empty() {
1307 query.to_string()
1308 } else {
1309 format!("{query}\u{001e}{tenant}\u{001e}{auth}")
1310 }
1311}
1312
1313#[cfg(test)]
1314mod tests {
1315 use super::*;
1316 use crate::api::RedDBOptions;
1317 use crate::runtime::impl_core::{
1318 clear_current_auth_identity, clear_current_tenant, set_current_auth_identity,
1319 set_current_tenant,
1320 };
1321 use crate::runtime::RedDBRuntime;
1322
1323 fn fresh_runtime() -> RedDBRuntime {
1324 RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("in-memory runtime")
1325 }
1326
1327 enum HeldFrame {
1328 Ordinary,
1329 Nested,
1330 Historical,
1331 }
1332
1333 fn verify_frame_survives_vacuum(delete: bool, kind: HeldFrame) {
1334 use crate::runtime::mvcc::{clear_current_connection_id, set_current_connection_id};
1335
1336 reset_thread_locals();
1337 clear_current_connection_id();
1338 let runtime = fresh_runtime();
1339 let execute = |connection, sql: &str| {
1340 set_current_connection_id(connection);
1341 let result = runtime.execute_query(sql);
1342 clear_current_connection_id();
1343 result.expect("valid frame retention fixture statement")
1344 };
1345 execute(1, "CREATE TABLE frame_rows (id TEXT, n INTEGER)");
1346 execute(1, "INSERT INTO frame_rows (id, n) VALUES ('row', 1)");
1347 let historical_xid = runtime.current_snapshot().xid;
1348 if matches!(kind, HeldFrame::Historical) {
1349 runtime
1350 .vcs_set_versioned("frame_rows", true)
1351 .expect("enable historical reads");
1352 }
1353 execute(2, "BEGIN");
1354 let query = if matches!(kind, HeldFrame::Historical) {
1355 format!("SELECT id, n FROM frame_rows AS OF SNAPSHOT {historical_xid}")
1356 } else {
1357 "SELECT id, n FROM frame_rows".to_string()
1358 };
1359 let frame = StatementExecutionFrame::build(&runtime, StatementIdentity::Text(&query))
1360 .expect("frame captures its snapshot");
1361 let frame = if matches!(kind, HeldFrame::Nested) {
1362 let guards = frame.install(&runtime);
1363 let expr = QueryExpr::Table(reddb_rql::ast::TableQuery::new("frame_rows"));
1364 let nested = StatementExecutionFrame::build(&runtime, StatementIdentity::Expr(&expr))
1365 .expect("nested frame inherits the protected snapshot");
1366 drop(guards);
1367 drop(frame);
1368 nested
1369 } else {
1370 frame
1371 };
1372 execute(
1375 2,
1376 if delete {
1377 "DELETE FROM frame_rows WHERE id = 'row'"
1378 } else {
1379 "UPDATE frame_rows SET n = 2 WHERE id = 'row'"
1380 },
1381 );
1382 execute(2, "COMMIT");
1383 execute(1, "VACUUM frame_rows");
1384 {
1385 let _guards = frame.install(&runtime);
1386 let records = super::super::record_search::scan_runtime_table_source_records_limited(
1387 &runtime.db(),
1388 "frame_rows",
1389 None,
1390 )
1391 .expect("captured frame scan succeeds after vacuum");
1392 assert_eq!(
1393 records.len(),
1394 1,
1395 "vacuum reclaimed an active frame's visible row"
1396 );
1397 assert_eq!(
1398 records[0]
1399 .get("n")
1400 .expect("selected value exists")
1401 .to_string(),
1402 "1"
1403 );
1404 }
1405 drop(frame);
1406 execute(1, "VACUUM frame_rows");
1407 let physical = runtime
1408 .db()
1409 .store()
1410 .get_collection("frame_rows")
1411 .expect("fixture collection exists")
1412 .query_all(|_| true)
1413 .len();
1414 assert_eq!(
1415 physical,
1416 usize::from(!delete),
1417 "completed frame leaked its retention pin"
1418 );
1419 clear_current_connection_id();
1420 }
1421
1422 #[test]
1423 fn autocommit_frame_retains_update_until_scan_completes() {
1424 verify_frame_survives_vacuum(false, HeldFrame::Ordinary);
1425 }
1426
1427 #[test]
1428 fn autocommit_frame_retains_delete_until_scan_completes() {
1429 verify_frame_survives_vacuum(true, HeldFrame::Ordinary);
1430 }
1431
1432 #[test]
1433 fn nested_frame_retains_history_after_parent_frame_drops() {
1434 verify_frame_survives_vacuum(false, HeldFrame::Nested);
1435 }
1436
1437 #[test]
1438 fn historical_frame_retains_history_until_scan_completes() {
1439 verify_frame_survives_vacuum(true, HeldFrame::Historical);
1440 }
1441
1442 fn reset_thread_locals() {
1445 clear_current_tenant();
1446 clear_current_auth_identity();
1447 }
1448
1449 #[test]
1450 fn autocommit_select_takes_live_snapshot() {
1451 reset_thread_locals();
1452 let rt = fresh_runtime();
1453 let frame = StatementExecutionFrame::build(&rt, StatementIdentity::Text("SELECT 1"))
1454 .expect("frame builds for SELECT 1");
1455
1456 let f: &dyn ReadFrame = &frame;
1459 assert!(f.as_of_floor().is_none(), "live read has no AS OF floor");
1460 assert_eq!(f.snapshot().xid, rt.snapshot_manager().peek_next_xid() - 1);
1461 assert!(!f.snapshot().sees(rt.snapshot_manager().peek_next_xid(), 0));
1462 }
1463
1464 #[test]
1465 fn autocommit_snapshot_does_not_lose_rows_after_index_publication() {
1466 reset_thread_locals();
1467 let rt = fresh_runtime();
1468 rt.execute_query("CREATE TABLE frame_index_race (id INT PRIMARY KEY, status TEXT)")
1469 .expect("create fixture");
1470 rt.execute_query("INSERT INTO frame_index_race (id, status) VALUES (1, 'old'), (2, 'old')")
1471 .expect("insert fixture");
1472 rt.execute_query("CREATE INDEX frame_status_hash ON frame_index_race (status) USING HASH")
1473 .expect("create index");
1474 let sql = "SELECT id FROM frame_index_race WHERE status = 'old'";
1475 let frame = StatementExecutionFrame::build(&rt, StatementIdentity::Text(sql))
1476 .expect("capture autocommit snapshot");
1477 rt.execute_query("UPDATE frame_index_race SET status = 'new' WHERE id = 1")
1478 .expect("publish changed index entry");
1479 let reddb_rql::ast::QueryExpr::Table(query) =
1480 reddb_rql::modes::parse_multi(sql).expect("parse")
1481 else {
1482 panic!("expected table query");
1483 };
1484 let _guards = frame.install(&rt);
1485 let records =
1486 super::super::query_exec::table::execute_runtime_canonical_table_query_indexed(
1487 &rt.db(),
1488 &query,
1489 Some(rt.index_store_ref()),
1490 )
1491 .expect("read captured snapshot");
1492 let mut ids = records
1493 .iter()
1494 .map(|record| record.get("id").expect("id").to_string())
1495 .collect::<Vec<_>>();
1496 ids.sort();
1497 assert_eq!(
1498 ids,
1499 ["1", "2"],
1500 "current index omitted a visible historical row"
1501 );
1502 }
1503
1504 #[test]
1505 fn captured_dml_snapshot_finds_rows_after_index_publication() {
1506 reset_thread_locals();
1507 let rt = fresh_runtime();
1508 rt.execute_query("CREATE TABLE frame_dml_race (id INT PRIMARY KEY, status TEXT)")
1509 .expect("create fixture");
1510 rt.execute_query("INSERT INTO frame_dml_race (id, status) VALUES (1, 'old'), (2, 'old')")
1511 .expect("insert fixture");
1512 rt.execute_query("CREATE INDEX frame_dml_status ON frame_dml_race (status) USING HASH")
1513 .expect("create index");
1514 let sql = "DELETE FROM frame_dml_race WHERE status = 'old'";
1515 let frame = StatementExecutionFrame::build(&rt, StatementIdentity::Text(sql))
1516 .expect("capture DML snapshot");
1517 rt.execute_query("UPDATE frame_dml_race SET status = 'new' WHERE id = 1")
1518 .expect("publish new indexed value");
1519 let reddb_rql::ast::QueryExpr::Table(query) =
1520 reddb_rql::modes::parse_multi("SELECT id FROM frame_dml_race WHERE status = 'old'")
1521 .expect("parse filter")
1522 else {
1523 panic!("expected table query")
1524 };
1525 let filter = reddb_rql::sql_lowering::effective_table_filter(&query).expect("filter");
1526 let _guards = frame.install(&rt);
1527 let ids = super::super::dml_target_scan::DmlTargetScan::new(
1528 &rt,
1529 "frame_dml_race",
1530 Some(&filter),
1531 None,
1532 )
1533 .find_target_ids()
1534 .expect("find DML targets");
1535 assert_eq!(
1536 ids.len(),
1537 2,
1538 "DML target scan must discover both snapshot-visible rows"
1539 );
1540 }
1541
1542 #[test]
1543 fn captured_snapshot_survives_indexed_update_and_delete_for_range_queries() {
1544 reset_thread_locals();
1545 let rt = fresh_runtime();
1546 rt.execute_query("CREATE TABLE frame_range_race (id INT PRIMARY KEY, score INT)")
1547 .expect("create fixture");
1548 rt.execute_query("INSERT INTO frame_range_race (id, score) VALUES (1, 10), (2, 20)")
1549 .expect("insert fixture");
1550 rt.execute_query("CREATE INDEX frame_score_range ON frame_range_race (score)")
1551 .expect("create index");
1552 let sql = "SELECT id FROM frame_range_race WHERE score >= 10 AND score <= 20 ORDER BY id";
1553 let frame = StatementExecutionFrame::build(&rt, StatementIdentity::Text(sql))
1554 .expect("capture read snapshot");
1555 rt.execute_query("UPDATE frame_range_race SET score = 99 WHERE id = 1")
1556 .expect("update row");
1557 rt.execute_query("DELETE FROM frame_range_race WHERE id = 2")
1558 .expect("delete row");
1559 let reddb_rql::ast::QueryExpr::Table(query) =
1560 reddb_rql::modes::parse_multi(sql).expect("parse")
1561 else {
1562 panic!("expected table query");
1563 };
1564 let _guards = frame.install(&rt);
1565 let records =
1566 super::super::query_exec::table::execute_runtime_canonical_table_query_indexed(
1567 &rt.db(),
1568 &query,
1569 Some(rt.index_store_ref()),
1570 )
1571 .expect("read captured snapshot");
1572 let ids = records
1573 .iter()
1574 .map(|record| record.get("id").expect("id").to_string())
1575 .collect::<Vec<_>>();
1576 assert_eq!(ids, ["1", "2"]);
1577 }
1578
1579 #[test]
1580 fn dml_target_scan_does_not_retry_inside_stored_function_budget() {
1581 use std::sync::atomic::{AtomicUsize, Ordering};
1582 use std::sync::Arc;
1583 reset_thread_locals();
1584 let rt = fresh_runtime();
1585 rt.execute_query("CREATE TABLE dml_budget_guard (id INT, status TEXT)")
1586 .expect("create fixture");
1587 rt.execute_query("INSERT INTO dml_budget_guard (id, status) VALUES (1, 'old')")
1588 .expect("insert fixture");
1589 rt.execute_query("CREATE INDEX dml_budget_status ON dml_budget_guard (status) USING HASH")
1590 .expect("create index");
1591 let frame = StatementExecutionFrame::build(
1592 &rt,
1593 StatementIdentity::Text("DELETE FROM dml_budget_guard WHERE status = 'old'"),
1594 )
1595 .expect("capture snapshot");
1596 let reddb_rql::ast::QueryExpr::Table(query) =
1597 reddb_rql::modes::parse_multi("SELECT id FROM dml_budget_guard WHERE status = 'old'")
1598 .expect("parse filter")
1599 else {
1600 panic!("expected table query")
1601 };
1602 let filter = reddb_rql::sql_lowering::effective_table_filter(&query).expect("filter");
1603 let calls = Arc::new(AtomicUsize::new(0));
1604 let observed = Arc::clone(&calls);
1605 *rt.index_store_ref().mutation_hook.lock() = Some(Arc::new(move |collection, phase| {
1606 if collection == "dml_budget_guard"
1607 && phase == super::super::index_store::MutationTestPhase::DmlIndexLookupStarted
1608 {
1609 observed.fetch_add(1, Ordering::SeqCst);
1610 }
1611 }));
1612 let _budget = super::super::function_budget::Scope::enter(1_000, 10_000)
1613 .expect("stored function budget");
1614 let _guards = frame.install(&rt);
1615 let ids = super::super::dml_target_scan::DmlTargetScan::new(
1616 &rt,
1617 "dml_budget_guard",
1618 Some(&filter),
1619 None,
1620 )
1621 .find_target_ids()
1622 .expect("find DML targets");
1623 assert_eq!(ids.len(), 1);
1624 assert_eq!(
1625 calls.load(Ordering::SeqCst),
1626 0,
1627 "bounded stored functions must not retry indexed discovery"
1628 );
1629 *rt.index_store_ref().mutation_hook.lock() = None;
1630 }
1631
1632 #[test]
1633 fn dml_target_selection_preserves_snapshot_when_publication_races() {
1634 use std::sync::{mpsc, Arc, Mutex};
1635 use std::time::Duration;
1636 reset_thread_locals();
1637 let rt = fresh_runtime();
1638 rt.execute_query("CREATE TABLE dml_lookup_race (id INT PRIMARY KEY, status TEXT)")
1639 .expect("create fixture");
1640 rt.execute_query("INSERT INTO dml_lookup_race (id, status) VALUES (1, 'old'), (2, 'old')")
1641 .expect("insert fixture");
1642 rt.execute_query("CREATE INDEX dml_lookup_status ON dml_lookup_race (status) USING HASH")
1643 .expect("create index");
1644 let frame = StatementExecutionFrame::build(
1645 &rt,
1646 StatementIdentity::Text("DELETE FROM dml_lookup_race WHERE status = 'old'"),
1647 )
1648 .expect("capture snapshot");
1649 let reddb_rql::ast::QueryExpr::Table(query) =
1650 reddb_rql::modes::parse_multi("SELECT id FROM dml_lookup_race WHERE status = 'old'")
1651 .expect("parse filter")
1652 else {
1653 panic!("expected table query")
1654 };
1655 let filter = reddb_rql::sql_lowering::effective_table_filter(&query).expect("filter");
1656 let (started_tx, started_rx) = mpsc::channel();
1657 let (published_tx, published_rx) = mpsc::channel();
1658 let published_rx = Mutex::new(published_rx);
1659 let first = std::sync::atomic::AtomicBool::new(true);
1660 *rt.index_store_ref().mutation_hook.lock() = Some(Arc::new(move |collection, phase| {
1661 if collection == "dml_lookup_race"
1662 && phase == super::super::index_store::MutationTestPhase::DmlTargetSelectionStarted
1663 && first.swap(false, std::sync::atomic::Ordering::SeqCst)
1664 {
1665 started_tx.send(()).expect("notify writer");
1666 published_rx
1667 .lock()
1668 .unwrap()
1669 .recv_timeout(Duration::from_secs(10))
1670 .expect("writer published");
1671 }
1672 }));
1673 std::thread::scope(|scope| {
1674 let writer_rt = &rt;
1675 let writer = scope.spawn(move || {
1676 started_rx
1677 .recv_timeout(Duration::from_secs(10))
1678 .expect("lookup started");
1679 writer_rt
1680 .execute_query("UPDATE dml_lookup_race SET status = 'new' WHERE id = 1")
1681 .expect("publish update");
1682 published_tx.send(()).expect("release lookup");
1683 });
1684 let limits = super::super::resource_limits::ResourceLimits {
1685 max_query_duration: Some(Duration::from_secs(30)),
1686 ..Default::default()
1687 };
1688 let slots = std::sync::atomic::AtomicU64::new(0);
1689 let _budget = super::super::query_budget::Scope::enter(&limits, &slots)
1690 .expect("query deadline scope");
1691 let _guards = frame.install(&rt);
1692 let ids = super::super::dml_target_scan::DmlTargetScan::new(
1693 &rt,
1694 "dml_lookup_race",
1695 Some(&filter),
1696 None,
1697 )
1698 .find_target_ids()
1699 .expect("find DML targets");
1700 writer.join().expect("writer thread");
1701 assert_eq!(
1702 ids.len(),
1703 2,
1704 "racing publication must not omit a snapshot-visible row"
1705 );
1706 });
1707 *rt.index_store_ref().mutation_hook.lock() = None;
1708 }
1709
1710 #[test]
1711 fn replica_replay_preserves_snapshots_across_insert_update_and_delete() {
1712 use crate::replication::cdc::{change_record_from_entity, ChangeOperation};
1713 use crate::replication::logical::{ApplyMode, LogicalChangeApplier};
1714 reset_thread_locals();
1715 let source = fresh_runtime();
1716 let replica = fresh_runtime();
1717 for rt in [&source, &replica] {
1718 rt.execute_query("CREATE TABLE replica_snapshot (id INT, status TEXT)")
1719 .expect("schema");
1720 }
1721 replica
1722 .execute_query(
1723 "CREATE INDEX replica_snapshot_status ON replica_snapshot (status) USING HASH",
1724 )
1725 .expect("index");
1726 let sql = "SELECT id FROM replica_snapshot WHERE status = 'old'";
1727 let capture = || {
1728 StatementExecutionFrame::build(&replica, StatementIdentity::Text(sql)).expect("capture")
1729 };
1730 let read = |frame: &StatementExecutionFrame| {
1731 let reddb_rql::ast::QueryExpr::Table(query) =
1732 reddb_rql::modes::parse_multi(sql).expect("parse")
1733 else {
1734 panic!("table")
1735 };
1736 let _guards = frame.install(&replica);
1737 super::super::query_exec::table::execute_runtime_canonical_table_query_indexed(
1738 &replica.db(),
1739 &query,
1740 Some(replica.index_store_ref()),
1741 )
1742 .expect("snapshot read")
1743 .len()
1744 };
1745 let empty = capture();
1746 source
1747 .execute_query("INSERT INTO replica_snapshot (id, status) VALUES (1, 'old')")
1748 .expect("insert");
1749 let applier = LogicalChangeApplier::new(0);
1750 let replay = |lsn, op| {
1751 let entity = source
1752 .db()
1753 .store()
1754 .get_collection("replica_snapshot")
1755 .unwrap()
1756 .query_all(|entity| entity.xmax == 0)
1757 .pop()
1758 .unwrap();
1759 applier
1760 .apply(
1761 &replica.db(),
1762 &change_record_from_entity(
1763 lsn,
1764 1,
1765 op,
1766 "replica_snapshot",
1767 "table",
1768 &entity,
1769 12,
1770 None,
1771 ),
1772 ApplyMode::Replica,
1773 )
1774 .expect("replay");
1775 };
1776 replay(1, ChangeOperation::Insert);
1777 assert_eq!(
1778 read(&empty),
1779 0,
1780 "replay must not backdate an insert into an earlier snapshot"
1781 );
1782 let inserted = capture();
1783 source
1784 .execute_query("UPDATE replica_snapshot SET status = 'new' WHERE id = 1")
1785 .expect("update");
1786 replay(2, ChangeOperation::Update);
1787 assert_eq!(read(&inserted), 1, "old version remains visible");
1788 assert_eq!(read(&capture()), 0, "fresh snapshot uses the updated index");
1789 let all_sql = "SELECT id FROM replica_snapshot";
1791 let before_delete =
1792 StatementExecutionFrame::build(&replica, StatementIdentity::Text(all_sql)).unwrap();
1793 replay(3, ChangeOperation::Delete);
1794 let reddb_rql::ast::QueryExpr::Table(query) =
1795 reddb_rql::modes::parse_multi(all_sql).unwrap()
1796 else {
1797 panic!("table")
1798 };
1799 {
1800 let _guards = before_delete.install(&replica);
1801 assert_eq!(
1802 super::super::query_exec::table::execute_runtime_canonical_table_query_indexed(
1803 &replica.db(),
1804 &query,
1805 Some(replica.index_store_ref())
1806 )
1807 .unwrap()
1808 .len(),
1809 1
1810 );
1811 }
1812 assert_eq!(
1813 replica.execute_query(all_sql).unwrap().result.records.len(),
1814 0
1815 );
1816 }
1817
1818 #[test]
1819 fn autocommit_index_reads_keep_old_rows_while_another_transaction_is_open() {
1820 use crate::runtime::mvcc::{clear_current_connection_id, set_current_connection_id};
1821 reset_thread_locals();
1822 let rt = fresh_runtime();
1823 let execute = |connection, sql: &str| {
1824 set_current_connection_id(connection);
1825 let result = rt.execute_query(sql);
1826 clear_current_connection_id();
1827 result.expect("statement")
1828 };
1829 execute(1, "CREATE TABLE active_writer_rows (id INT, status TEXT)");
1830 execute(
1831 1,
1832 "INSERT INTO active_writer_rows (id, status) VALUES (1, 'old')",
1833 );
1834 execute(
1835 1,
1836 "CREATE INDEX active_writer_status ON active_writer_rows (status) USING HASH",
1837 );
1838 execute(2, "BEGIN");
1839 execute(
1840 2,
1841 "UPDATE active_writer_rows SET status = 'new' WHERE id = 1",
1842 );
1843 assert_eq!(
1844 execute(1, "SELECT id FROM active_writer_rows WHERE status = 'old'")
1845 .result
1846 .records
1847 .len(),
1848 1
1849 );
1850 assert_eq!(
1851 execute(1, "SELECT id FROM active_writer_rows WHERE status = 'new'")
1852 .result
1853 .records
1854 .len(),
1855 0
1856 );
1857 execute(2, "ROLLBACK");
1858 assert_eq!(
1859 execute(1, "SELECT id FROM active_writer_rows WHERE status = 'old'")
1860 .result
1861 .records
1862 .len(),
1863 1
1864 );
1865 }
1866
1867 #[test]
1868 fn frame_captures_identity_and_scope() {
1869 reset_thread_locals();
1870 set_current_tenant("acme".to_string());
1871 set_current_auth_identity("alice".to_string(), Role::Write);
1872
1873 let rt = fresh_runtime();
1874 let frame = StatementExecutionFrame::build(&rt, StatementIdentity::Text("SELECT 1"))
1875 .expect("frame builds");
1876 let f: &dyn ReadFrame = &frame;
1877
1878 assert_eq!(f.effective_scope(), Some("acme"));
1879 let id = f.identity().expect("identity captured");
1880 assert_eq!(id.0, "alice");
1881 assert!(matches!(id.1, Role::Write));
1882
1883 assert!(
1886 f.cache_key().contains("acme") && f.cache_key().contains("alice"),
1887 "cache key folds in scope + identity, got {:?}",
1888 f.cache_key()
1889 );
1890
1891 reset_thread_locals();
1892 }
1893
1894 #[test]
1895 fn as_of_rejects_non_versioned_user_collection() {
1896 reset_thread_locals();
1897 let rt = fresh_runtime();
1898
1899 let err = match StatementExecutionFrame::build(
1903 &rt,
1904 StatementIdentity::Text("SELECT * FROM not_versioned AS OF COMMIT 'deadbeef'"),
1905 ) {
1906 Err(e) => e,
1907 Ok(_) => panic!("AS OF on non-versioned user collection rejected"),
1908 };
1909
1910 let msg = format!("{err}");
1911 assert!(
1912 msg.contains("AS OF requires a versioned collection"),
1913 "expected AS OF rejection, got: {msg}"
1914 );
1915 }
1916
1917 #[test]
1929 fn select_path_routes_through_frame_cache_key() {
1930 reset_thread_locals();
1931 set_current_tenant("acme".to_string());
1932 set_current_auth_identity("alice".to_string(), Role::Read);
1933
1934 let rt = fresh_runtime();
1935 let result = rt
1936 .execute_query("SELECT 1")
1937 .expect("SELECT 1 executes under tenant=acme/identity=alice");
1938 assert_eq!(result.statement_type, "select");
1939
1940 let cache = rt.inner.result_blob_entries.read();
1946 let any_keyed_with_scope = cache
1947 .0
1948 .keys()
1949 .any(|k| k.contains("acme") && k.contains("alice"));
1950 assert!(
1951 any_keyed_with_scope,
1952 "expected at least one result-cache key carrying tenant+identity, \
1953 got keys: {:?}",
1954 cache.0.keys().collect::<Vec<_>>()
1955 );
1956
1957 reset_thread_locals();
1958 }
1959
1960 #[test]
1972 fn volatile_select_does_not_populate_result_cache() {
1973 reset_thread_locals();
1974 let rt = fresh_runtime();
1975
1976 let frame = StatementExecutionFrame::build(
1980 &rt,
1981 StatementIdentity::Text("SELECT pg_advisory_unlock(1)"),
1982 )
1983 .expect("frame");
1984 let f: &dyn ReadFrame = &frame;
1985 assert!(
1986 !f.should_cache_result(),
1987 "volatile builtin must disable result-cache safety"
1988 );
1989
1990 let _ = rt
1995 .execute_query("SELECT pg_advisory_unlock(1)")
1996 .expect("volatile SELECT executes");
1997 let cache = rt.inner.result_blob_entries.read();
1998 let key = result_cache_key("SELECT pg_advisory_unlock(1)");
1999 assert!(
2000 !cache.0.contains_key(&key),
2001 "volatile SELECT must not populate result cache, found key {key:?} in {:?}",
2002 cache.0.keys().collect::<Vec<_>>()
2003 );
2004
2005 reset_thread_locals();
2006 }
2007
2008 #[test]
2009 fn result_cache_populates_blob_path() {
2010 reset_thread_locals();
2011 let rt = fresh_runtime();
2012 let result = rt.execute_query("SELECT 1").expect("SELECT 1 executes");
2013 assert_eq!(result.statement_type, "select");
2014
2015 let key = result_cache_key("SELECT 1");
2016 rt.inner.result_blob_entries.write().5 = Some(std::time::Instant::now());
2017 rt.promote_volatile_result_cache_entry();
2018 assert!(
2019 rt.inner
2020 .result_blob_cache
2021 .get("runtime.result_cache", &key)
2022 .is_some(),
2023 "blob backend should stamp the Blob Cache path"
2024 );
2025 assert!(rt.inner.result_blob_entries.read().0.contains_key(&key));
2026 }
2027
2028 #[test]
2029 fn blob_cache_backend_keeps_volatile_select_out_of_blob_path() {
2030 reset_thread_locals();
2031 let rt = fresh_runtime();
2032 let _ = rt
2033 .execute_query("SELECT pg_advisory_unlock(1)")
2034 .expect("volatile SELECT executes");
2035 let key = result_cache_key("SELECT pg_advisory_unlock(1)");
2036 assert!(
2037 rt.inner
2038 .result_blob_cache
2039 .get("runtime.result_cache", &key)
2040 .is_none(),
2041 "volatile SELECT must not populate blob result cache"
2042 );
2043 assert!(!rt.inner.result_blob_entries.read().0.contains_key(&key));
2044 }
2045
2046 #[test]
2047 fn as_of_on_red_collection_records_floor() {
2048 reset_thread_locals();
2049 let rt = fresh_runtime();
2050
2051 let frame = StatementExecutionFrame::build(
2054 &rt,
2055 StatementIdentity::Text("SELECT * FROM red.vcs.commits AS OF SNAPSHOT 1"),
2056 )
2057 .expect("AS OF SNAPSHOT 1 on red.vcs.commits resolves");
2058
2059 let f: &dyn ReadFrame = &frame;
2060 assert_eq!(
2061 f.as_of_floor(),
2062 Some(1),
2063 "AS OF SNAPSHOT 1 records xid=1 as the floor"
2064 );
2065 assert_eq!(f.snapshot().xid, 1);
2066 assert!(
2067 f.snapshot().in_progress.is_empty(),
2068 "historical reads have no in-progress set"
2069 );
2070 }
2071
2072 #[test]
2078 fn frame_classifies_privilege_and_lock_intent_from_prefix() {
2079 reset_thread_locals();
2080 let rt = fresh_runtime();
2081
2082 let cases = [
2083 ("SELECT 1", Privilege::Read, LockIntent::Shared),
2084 ("LIST KV settings", Privilege::Read, LockIntent::Shared),
2085 (
2086 "KV GET settings.feature",
2087 Privilege::Read,
2088 LockIntent::Shared,
2089 ),
2090 ("VAULT LIST secrets", Privilege::Read, LockIntent::Shared),
2091 (
2092 "INSERT INTO t (id) VALUES (1)",
2093 Privilege::Write,
2094 LockIntent::Exclusive,
2095 ),
2096 (
2097 "KV PUT settings.feature = 'on'",
2098 Privilege::Write,
2099 LockIntent::Exclusive,
2100 ),
2101 (
2102 "VAULT PUT secrets.api = 'x'",
2103 Privilege::Write,
2104 LockIntent::Exclusive,
2105 ),
2106 (
2107 "UPDATE t SET x = 1 WHERE id = 1",
2108 Privilege::Write,
2109 LockIntent::Exclusive,
2110 ),
2111 (
2112 "DELETE FROM t WHERE id = 1",
2113 Privilege::Write,
2114 LockIntent::Exclusive,
2115 ),
2116 (
2117 "CREATE TABLE foo (id INT)",
2118 Privilege::Write,
2119 LockIntent::Exclusive,
2120 ),
2121 ("BEGIN", Privilege::None, LockIntent::None),
2122 ("COMMIT", Privilege::None, LockIntent::None),
2123 ("SET timezone = 'UTC'", Privilege::None, LockIntent::None),
2124 ];
2125
2126 for (q, want_priv, want_lock) in cases {
2127 let frame = StatementExecutionFrame::build(&rt, StatementIdentity::Text(q))
2128 .unwrap_or_else(|e| panic!("frame builds for {q:?}: {e}"));
2129 let f: &dyn ReadFrame = &frame;
2130 assert_eq!(f.required_privilege(), want_priv, "privilege for {q:?}");
2131 assert_eq!(f.lock_intent(), want_lock, "lock intent for {q:?}");
2132 }
2133 }
2134
2135 #[test]
2152 fn insert_under_read_role_denied_via_frame_privilege() {
2153 reset_thread_locals();
2154 set_current_auth_identity("alice".to_string(), Role::Read);
2155
2156 let rt = fresh_runtime();
2157 let frame = StatementExecutionFrame::build(
2163 &rt,
2164 StatementIdentity::Text("INSERT INTO t (id) VALUES (1)"),
2165 )
2166 .expect("frame builds for INSERT");
2167 let f: &dyn ReadFrame = &frame;
2168 assert_eq!(
2169 f.required_privilege(),
2170 Privilege::Write,
2171 "INSERT classified as Write"
2172 );
2173 let id = f.identity().expect("identity captured");
2174 assert!(
2175 !f.required_privilege().is_satisfied_by(id.1),
2176 "Role::Read does not satisfy Privilege::Write — frame must deny"
2177 );
2178
2179 use reddb_rql::ast::{QueryExpr, TableQuery};
2185 let expr = QueryExpr::Table(TableQuery::new("t"));
2186 let err = frame
2187 .check_query_privilege(&rt, &expr)
2188 .expect_err("denied via frame's coarse privilege gate");
2189 let msg = format!("{err}");
2190 assert!(
2191 msg.contains("permission denied") && msg.contains("Write"),
2192 "expected frame-level Write deny, got: {msg}"
2193 );
2194
2195 reset_thread_locals();
2196 }
2197
2198 #[test]
2211 fn large_select_through_frame_arena_returns_all_rows_in_order() {
2212 reset_thread_locals();
2213 let rt = fresh_runtime();
2214 rt.execute_query("CREATE TABLE big (id INT)")
2215 .expect("create table");
2216
2217 const N: usize = 2_500;
2220 for start in (0..N).step_by(250) {
2221 let end = (start + 250).min(N);
2222 let values = (start..end)
2223 .map(|i| format!("({i})"))
2224 .collect::<Vec<_>>()
2225 .join(", ");
2226 rt.execute_query(&format!("INSERT INTO big (id) VALUES {values}"))
2227 .unwrap_or_else(|err| panic!("insert rows {start}..{end}: {err:?}"));
2228 }
2229
2230 let result = rt
2231 .execute_query("SELECT id FROM big ORDER BY id")
2232 .expect("large SELECT executes through the frame arena path");
2233 assert_eq!(result.statement_type, "select");
2234 assert_eq!(
2235 result.result.records.len(),
2236 N,
2237 "every inserted row streams back through the arena-backed channel"
2238 );
2239 for (i, record) in result.result.records.iter().enumerate() {
2240 assert_eq!(
2241 record.get("id"),
2242 Some(&reddb_types::Value::Integer(i as i64)),
2243 "row {i} is byte-identical to the per-request-allocation baseline"
2244 );
2245 }
2246
2247 reset_thread_locals();
2248 }
2249
2250 #[test]
2264 fn parameterized_transport_adapters_delegate_binding_to_runtime() {
2265 let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
2266 let adapters = [
2267 ("src/server/handlers_query.rs", "QueryRequestExecutor"),
2268 ("src/rpc_stdio.rs", "QueryRequestExecutor"),
2269 ("src/wire/redwire/session.rs", "QueryRequestExecutor"),
2270 ("src/wire/postgres/server.rs", "QueryRequestExecutor"),
2271 ("src/grpc.rs", "QueryRequestExecutor"),
2272 ];
2273
2274 for (relative, delegation) in adapters {
2275 let path = manifest_dir.join(relative);
2276 let text = std::fs::read_to_string(&path)
2277 .unwrap_or_else(|err| panic!("read {}: {err}", path.display()));
2278 assert!(
2279 text.contains(delegation),
2280 "{relative} should delegate parameterized query execution through {delegation}"
2281 );
2282 assert!(
2283 !text.contains("user_params::bind"),
2284 "{relative} must not bind SQL params in the transport adapter"
2285 );
2286 }
2287
2288 let seam = std::fs::read_to_string(manifest_dir.join("src/runtime/query_request.rs"))
2291 .expect("read src/runtime/query_request.rs");
2292 assert!(
2293 seam.contains("execute_query_with_params"),
2294 "the Request module must execute text SQL through the runtime entrypoint"
2295 );
2296 }
2297
2298 #[test]
2308 fn control_statement_skips_intent_locks_via_frame() {
2309 reset_thread_locals();
2310 let rt = fresh_runtime();
2311
2312 let frame = StatementExecutionFrame::build(&rt, StatementIdentity::Text("BEGIN"))
2313 .expect("frame builds for BEGIN");
2314 let f: &dyn ReadFrame = &frame;
2315 assert_eq!(f.lock_intent(), LockIntent::None);
2316
2317 use reddb_rql::ast::{QueryExpr, TableQuery};
2322 let expr = QueryExpr::Table(TableQuery::new("t"));
2323 let guard = frame
2324 .acquire_intent_locks(&rt, &expr)
2325 .expect("no lock is attempted");
2326 assert!(
2327 guard.is_none(),
2328 "BEGIN frame's lock_intent=None must short-circuit lock acquisition"
2329 );
2330 }
2331
2332 #[test]
2339 fn nested_frame_inherits_outer_statement_snapshot() {
2340 reset_thread_locals();
2341 let rt = fresh_runtime();
2342 rt.execute_query("CREATE TABLE nested_snap (id INT)")
2343 .expect("create table");
2344
2345 let outer = StatementExecutionFrame::build(
2346 &rt,
2347 StatementIdentity::Text("SELECT * FROM nested_snap"),
2348 )
2349 .expect("outer frame builds");
2350 let _outer_guards = outer.install(&rt);
2351
2352 rt.execute_query("INSERT INTO nested_snap (id) VALUES (1)")
2355 .expect("concurrent insert");
2356
2357 let expr = QueryExpr::Table(reddb_rql::ast::TableQuery::new("nested_snap"));
2358 let nested = StatementExecutionFrame::build(&rt, StatementIdentity::Expr(&expr))
2359 .expect("nested frame builds");
2360
2361 assert_eq!(
2362 ReadFrame::snapshot(&nested).xid,
2363 ReadFrame::snapshot(&outer).xid,
2364 "nested execution must inherit the outer statement's snapshot"
2365 );
2366 }
2367
2368 #[test]
2381 fn nested_text_statement_sees_commits_made_since_the_outer_frame() {
2382 reset_thread_locals();
2383 let rt = fresh_runtime();
2384 rt.execute_query("CREATE TABLE nested_text_snap (id INT)")
2385 .expect("create table");
2386
2387 let outer = StatementExecutionFrame::build(
2388 &rt,
2389 StatementIdentity::Text("SELECT * FROM nested_text_snap"),
2390 )
2391 .expect("outer frame builds");
2392 let _outer_guards = outer.install(&rt);
2393
2394 rt.execute_query("INSERT INTO nested_text_snap (id) VALUES (1)")
2395 .expect("concurrent insert");
2396
2397 let nested = StatementExecutionFrame::build(
2398 &rt,
2399 StatementIdentity::Text("SELECT * FROM nested_text_snap"),
2400 )
2401 .expect("nested frame builds");
2402
2403 assert_ne!(
2404 ReadFrame::snapshot(&nested).xid,
2405 ReadFrame::snapshot(&outer).xid,
2406 "a nested text statement must mint a fresh snapshot, not inherit \
2407 the enclosing statement's frozen view"
2408 );
2409 }
2410
2411 #[test]
2416 fn expr_frame_rejects_as_of_instead_of_reading_live() {
2417 reset_thread_locals();
2418 let rt = fresh_runtime();
2419
2420 let mut table = reddb_rql::ast::TableQuery::new("red.vcs.commits");
2421 table.as_of = Some(reddb_rql::ast::AsOfClause::Snapshot(1));
2422 let expr = QueryExpr::Table(table);
2423
2424 let err = match StatementExecutionFrame::build(&rt, StatementIdentity::Expr(&expr)) {
2425 Err(err) => err,
2426 Ok(_) => panic!("AS OF without statement text must be refused, not read live"),
2427 };
2428 let msg = format!("{err}");
2429 assert!(
2430 msg.contains("AS OF cannot be resolved from a pre-parsed expression"),
2431 "expected a loud AS OF refusal, got: {msg}"
2432 );
2433 }
2434
2435 #[test]
2439 fn expr_frame_opts_out_of_the_result_cache() {
2440 reset_thread_locals();
2441 let rt = fresh_runtime();
2442
2443 let expr = QueryExpr::Table(reddb_rql::ast::TableQuery::new("t"));
2444 let frame = StatementExecutionFrame::build(&rt, StatementIdentity::Expr(&expr))
2445 .expect("expr frame builds");
2446
2447 assert!(frame.cache_key().is_empty(), "expr frame has no cache key");
2448 assert!(
2449 !frame.can_read_result_cache(),
2450 "expr frame must never serve from the result cache"
2451 );
2452 }
2453}