Skip to main content

reddb_server/runtime/
impl_core.rs

1use super::*;
2use crate::auth::column_policy_gate::ColumnAccessRequest;
3use crate::auth::UserId;
4use crate::catalog::CollectionModel;
5use crate::replication::cdc::ChangeRecord;
6use reddb_rql::ast::TableSource;
7// Authorization surface moved to `super::authz` (issue #1622). Re-export the
8// free IAM/policy-column helpers so this module's remaining dispatch code
9// (and the `impl_core::decision_to_strings` path used by
10// `server::handlers_iam_policy`) keeps calling them unqualified.
11pub(crate) use super::authz::policy_columns::*;
12
13// Graph inline-TVF/analytics moved to `super::graph_tvf` (issue #1625) and the
14// RLS injection family to `super::rls_injection`. Re-export the free fns still
15// referenced from this module (and via `crate::runtime::impl_core::…` paths by
16// sibling files) so those call sites need no edits.
17pub(crate) use super::graph_tvf::{abstract_degree_centrality, is_graph_tvf_name};
18pub(crate) use super::rls_injection::{
19    apply_foreign_table_filters, inject_rls_filters, inject_rls_into_join, rls_is_enabled,
20    rls_policy_filter, rls_policy_filter_for_kind,
21};
22// VCS command parse/execute moved to `super::vcs_command` (issue #1626). The
23// execute methods are inherent `pub(crate)` methods resolved via `self`; the
24// free parse helpers still called from the central dispatch (and by
25// `collections_referenced` here) are re-exported so those call sites need no
26// edits.
27pub(crate) use super::vcs_command::{
28    parse_runtime_vcs_command, strip_explain_prefix, walk_collections,
29};
30
31// Ranking / metrics / SLO / analytics-source DDL moved to
32// `super::impl_ranking` (issue #1627). Execute methods are inherent
33// `pub(crate)` methods resolved via `self`; no call-site edits needed.
34
35// Config / secret / KV resolution moved to `super::impl_config_secret` and the
36// query-audit + control-event families to `super::impl_audit_control`
37// (issue #1628). Methods are inherent `pub(crate)` methods resolved via `self`;
38// the one free fn still called via a `crate::runtime::impl_core::…` path
39// (`control_event_outcome_for_error`, from `impl_backup`) is re-exported so that
40// call site needs no edit. The dispatch here also still calls the three
41// audit-planning free fns, so they are pulled back into scope unqualified.
42pub(crate) use super::impl_audit_control::{
43    control_event_outcome_for_error, query_audit_plan, query_control_event_specs,
44};
45// Config/secret free helpers still called unqualified from the dispatch here.
46pub(crate) use super::impl_config_secret::{
47    insert_config_json_path, secret_sql_value_to_string, seed_storage_deploy_config,
48    show_config_json_result,
49};
50pub(super) use super::impl_core_outer_scope::{
51    first_column_values, query_references_outer_scope, relation_scopes_for_query,
52};
53pub(crate) use super::impl_core_result_cache_scopes::collect_table_refs;
54pub(super) use super::impl_core_result_cache_scopes::query_expr_result_cache_scopes;
55
56// Bootstrap / constructor / handle accessors moved to `super::impl_lifecycle`,
57// telemetry / gates / limits / shutdown to `super::impl_telemetry_accessors`,
58// and catalog / stats / maintenance to `super::impl_catalog_accessors`
59// (issue #1629). Methods are inherent `pub(crate)`/`pub` methods resolved via
60// `self`; the two moved free fns still called unqualified from the dispatch
61// here (`view_records_to_entities`) and the runtime-index rehydration paths
62// (`table_row_index_fields`) are re-exported so those call sites need no edit.
63pub(crate) use super::impl_lifecycle::{table_row_index_fields, view_records_to_entities};
64
65#[cfg(test)]
66thread_local! {
67    static RESULT_CACHE_MISS_EXECUTIONS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
68}
69
70#[cfg(test)]
71fn reset_result_cache_miss_executions() {
72    RESULT_CACHE_MISS_EXECUTIONS.with(|count| count.set(0));
73}
74
75#[cfg(test)]
76fn result_cache_miss_executions() -> u64 {
77    RESULT_CACHE_MISS_EXECUTIONS.with(std::cell::Cell::get)
78}
79
80pub use super::execution_context::{
81    capture_current_snapshot, clear_current_auth_identity, clear_current_connection_id,
82    clear_current_snapshot, clear_current_tenant, current_auth_identity_for_audit,
83    current_connection_id, current_tenant, entity_visible_under_current_snapshot,
84    entity_visible_with_context, set_current_auth_identity, set_current_auth_principal,
85    set_current_connection_id, set_current_snapshot, set_current_tenant, snapshot_bundle,
86    with_snapshot_bundle, SnapshotBundle, SnapshotContext,
87};
88pub(crate) use super::execution_context::{
89    config_read_permitted, current_auth_identity, current_config_value, current_kv_value,
90    current_role_projected, current_scope_override, current_secret_value,
91    current_snapshot_requires_index_fallback, current_user_projected, has_scope_override_active,
92    kv_read_permitted, parse_set_local_tenant, update_current_config_value,
93    update_current_kv_value, update_current_secret_value, xids_visible_under_current_snapshot,
94    ConfigSnapshotGuard, CurrentSnapshotGuard, KvStoreGuard, ScopeOverrideGuard, SecretStoreGuard,
95    TxLocalTenantGuard,
96};
97
98/// Cheap prefix check for a leading `WITH` keyword. Used to gate the
99/// CTE-aware parse in `execute_query` without paying for a full
100/// lexer pass on every statement. Treats `WITHIN` as not-a-CTE so
101/// `WITHIN TENANT '...' SELECT ...` doesn't mis-route.
102pub(super) fn has_with_prefix(sql: &str) -> bool {
103    let trimmed = sql.trim_start();
104    let head_end = trimmed
105        .find(|c: char| c.is_whitespace() || c == '(')
106        .unwrap_or(trimmed.len());
107    trimmed[..head_end].eq_ignore_ascii_case("WITH")
108}
109
110/// Same as `peek_top_level_as_of` but also returns the table name
111/// targeted by the AS OF clause (when the FROM clause names a
112/// concrete table). `None` for the table slot means scalar SELECT
113/// or a subquery source — callers treat those as "no enforcement".
114pub(super) fn peek_top_level_as_of_with_table(
115    sql: &str,
116) -> Option<(crate::application::vcs::AsOfSpec, Option<String>)> {
117    if !sql
118        .as_bytes()
119        .windows(5)
120        .any(|w| w.eq_ignore_ascii_case(b"as of"))
121    {
122        return None;
123    }
124    let parsed = reddb_rql::parser::parse(sql).ok()?;
125    let reddb_rql::ast::QueryExpr::Table(table) = parsed.query else {
126        return None;
127    };
128    let clause = table.as_of?;
129    let table_name = if table.table.is_empty() || table.table == "any" {
130        None
131    } else {
132        Some(table.table.clone())
133    };
134    let spec = match clause {
135        reddb_rql::ast::AsOfClause::Commit(h) => crate::application::vcs::AsOfSpec::Commit(h),
136        reddb_rql::ast::AsOfClause::Branch(b) => crate::application::vcs::AsOfSpec::Branch(b),
137        reddb_rql::ast::AsOfClause::Tag(t) => crate::application::vcs::AsOfSpec::Tag(t),
138        reddb_rql::ast::AsOfClause::TimestampMs(ts) => {
139            crate::application::vcs::AsOfSpec::TimestampMs(ts)
140        }
141        reddb_rql::ast::AsOfClause::Snapshot(x) => crate::application::vcs::AsOfSpec::Snapshot(x),
142    };
143    Some((spec, table_name))
144}
145
146pub(super) fn query_has_volatile_builtin(sql: &str) -> bool {
147    // Lowercase the bytes up to the first null/newline into a small
148    // stack buffer for cheap contains() checks. Most SQL fits in the
149    // buffer; longer queries fall back to owned lowercase.
150    const VOLATILE_TOKENS: &[&str] = &[
151        "pg_advisory_lock",
152        "pg_try_advisory_lock",
153        "pg_advisory_unlock",
154        "random()",
155        // `$config.<path>` / `$secret.<path>` resolve mutable runtime config /
156        // vault state at execution time (#1370). A cached result would serve a
157        // stale value after a later `SET CONFIG` / `SET SECRET`, so treat any
158        // query referencing them as volatile (never result-cache it).
159        "$config",
160        "$secret",
161        "$red.secret",
162        "$kv",
163        // NOW() / CURRENT_TIMESTAMP / CURRENT_DATE intentionally
164        // omitted for now — they ARE volatile but today's tests rely
165        // on caching them. Revisit once a tighter volatility story
166        // lands.
167    ];
168    let lowered = sql.to_ascii_lowercase();
169    VOLATILE_TOKENS.iter().any(|t| lowered.contains(t))
170}
171
172pub(super) fn query_is_ask_statement(sql: &str) -> bool {
173    let trimmed = sql.trim_start();
174    let head_end = trimmed
175        .find(|c: char| c.is_whitespace() || c == '(' || c == ';')
176        .unwrap_or(trimmed.len());
177    trimmed[..head_end].eq_ignore_ascii_case("ASK")
178}
179
180/// Pick the `(global_mode, collection_mode)` pair for an expression,
181/// or `None` for variants that opt out of intent-locking entirely
182/// (admin statements like `SHOW CONFIG`, transaction control, tenant
183/// toggles).
184///
185/// Phase-1 contract:
186/// - Reads  — `(IX-compatible) (Global, IS) → (Collection, IS)`
187/// - Writes — `(IX-compatible) (Global, IX) → (Collection, IX)`
188/// - DDL    — `(strong)        (Global, IX) → (Collection, X)`
189pub(super) fn intent_lock_modes_for(
190    expr: &QueryExpr,
191) -> Option<(
192    crate::runtime::lock_manager::LockMode,
193    crate::runtime::lock_manager::LockMode,
194)> {
195    use crate::runtime::lock_manager::LockMode::{Exclusive, IntentExclusive, IntentShared};
196
197    match expr {
198        // Reads — IS / IS.
199        QueryExpr::Table(_)
200        | QueryExpr::Join(_)
201        | QueryExpr::Vector(_)
202        | QueryExpr::Hybrid(_)
203        | QueryExpr::Graph(_)
204        | QueryExpr::Path(_)
205        | QueryExpr::Ask(_)
206        | QueryExpr::SearchCommand(_)
207        | QueryExpr::GraphCommand(_)
208        | QueryExpr::RankOf(_)
209        | QueryExpr::ApproxRankOf(_)
210        | QueryExpr::RankRange(_)
211        | QueryExpr::QueueSelect(_) => Some((IntentShared, IntentShared)),
212
213        // Writes — IX / IX. Non-tabular mutations (vector insert,
214        // graph node insert, queue push, timeseries point insert)
215        // don't carry their own dispatch arm here; they ride through
216        // the Insert variant or a command variant covered by the
217        // read-side arm above. P1.T4 expands only the TableQuery-ish
218        // writes; non-tabular kinds inherit when their DML variants
219        // land in later phases.
220        QueryExpr::Insert(_)
221        | QueryExpr::Update(_)
222        | QueryExpr::Delete(_)
223        | QueryExpr::QueueCommand(QueueCommand::Move { .. }) => {
224            Some((IntentExclusive, IntentExclusive))
225        }
226        QueryExpr::QueueCommand(_) => Some((IntentShared, IntentShared)),
227
228        // DDL — IX / X. A DDL against collection `c` blocks all
229        // other writers + readers on `c` but leaves other collections
230        // running (because Global stays IX, not X).
231        QueryExpr::CreateTable(_)
232        | QueryExpr::CreateCollection(_)
233        | QueryExpr::CreateVector(_)
234        | QueryExpr::DropTable(_)
235        | QueryExpr::DropGraph(_)
236        | QueryExpr::DropVector(_)
237        | QueryExpr::DropDocument(_)
238        | QueryExpr::DropKv(_)
239        | QueryExpr::DropCollection(_)
240        | QueryExpr::Truncate(_)
241        | QueryExpr::AlterTable(_)
242        | QueryExpr::CreateIndex(_)
243        | QueryExpr::DropIndex(_)
244        | QueryExpr::CreateTimeSeries(_)
245        | QueryExpr::CreateMetric(_)
246        | QueryExpr::AlterMetric(_)
247        | QueryExpr::CreateSlo(_)
248        | QueryExpr::DropTimeSeries(_)
249        | QueryExpr::CreateQueue(_)
250        | QueryExpr::AlterQueue(_)
251        | QueryExpr::DropQueue(_)
252        | QueryExpr::CreateTree(_)
253        | QueryExpr::DropTree(_)
254        | QueryExpr::CreatePolicy(_)
255        | QueryExpr::DropPolicy(_)
256        | QueryExpr::CreateView(_)
257        | QueryExpr::DropView(_)
258        | QueryExpr::RefreshMaterializedView(_)
259        | QueryExpr::CreateSchema(_)
260        | QueryExpr::DropSchema(_)
261        | QueryExpr::CreateSequence(_)
262        | QueryExpr::DropSequence(_)
263        | QueryExpr::CreateServer(_)
264        | QueryExpr::DropServer(_)
265        | QueryExpr::CreateForeignTable(_)
266        | QueryExpr::DropForeignTable(_) => Some((IntentExclusive, Exclusive)),
267
268        // Admin / control — skip intent locks. `SET TENANT`,
269        // `BEGIN / COMMIT / ROLLBACK`, `SET CONFIG`, `SHOW CONFIG`,
270        // `VACUUM`, etc. don't touch collection data the same way
271        // and the existing transaction layer already serialises the
272        // pieces that matter.
273        _ => None,
274    }
275}
276
277/// Best-effort collection inventory for an expression. Used to pick
278/// `Collection(...)` resources for the intent-lock guard. Overshoots
279/// are fine (take an extra IS, benign); undershoots leak writes past
280/// DDL X locks, so err on the side of listing more names.
281pub(super) fn collections_referenced(expr: &QueryExpr) -> Vec<String> {
282    let mut out = Vec::new();
283    walk_collections(expr, &mut out);
284    out.sort();
285    out.dedup();
286    out
287}
288
289impl RedDBRuntime {
290    /// Execute a query under a typed scope override without embedding
291    /// the tenant / user / role values into the SQL string. Use this
292    /// from transport middleware (HTTP / gRPC / worker loops) where the
293    /// scope is resolved from auth claims and the SQL is a parameterised
294    /// template — avoids the string-concat injection risk of building
295    /// `WITHIN TENANT '<id>' …` manually, and is drop-in compatible with
296    /// prepared statements that didn't know about tenancy.
297    ///
298    /// Precedence matches the `WITHIN` clause: the passed `scope`
299    /// overrides `SET LOCAL TENANT`, which overrides `SET TENANT`.
300    /// The override is pushed on the thread-local scope stack for the
301    /// duration of the call and popped on return — pool-shared
302    /// connections cannot leak it across requests.
303    pub fn execute_query_with_scope(
304        &self,
305        query: &str,
306        scope: crate::runtime::within_clause::ScopeOverride,
307    ) -> RedDBResult<RuntimeQueryResult> {
308        if scope.is_empty() {
309            return self.execute_query(query);
310        }
311        self.check_scope_override_privilege(&scope)?;
312        let _scope_guard = ScopeOverrideGuard::install(scope);
313        self.execute_query(query)
314    }
315
316    /// Issue #205 — single lifecycle exit for slow-query logging.
317    ///
318    /// `execute_query_inner` does the real work; this wrapper times it
319    /// and, if elapsed exceeds the configured threshold, hands the
320    /// triple `(QueryKind, elapsed_ms, sql_redacted, scope)` to the
321    /// SlowQueryLogger. The threshold + sample_pct were captured at
322    /// SlowQueryLogger construction (runtime startup), so the per-call
323    /// cost on below-threshold paths is one relaxed atomic load.
324    pub fn execute_query(&self, query: &str) -> RedDBResult<RuntimeQueryResult> {
325        super::execution_watchdog::label_current_execution(|| redact_sql_for_slow_log(query));
326        let started = std::time::Instant::now();
327        self.inner.node_load_telemetry.query_start();
328        let receipt = super::transactional_replication::CommitReceiptScope::begin(self);
329        let result = self.execute_query_inner(query);
330        self.finish_query_lifecycle(query, started, result, receipt.lsn())
331    }
332
333    /// Execute a SQL statement with already-decoded positional bind
334    /// parameters. Transports should call this instead of parsing +
335    /// binding on their side and then reaching for `execute_query_expr`:
336    /// this entry keeps parameterized statements inside the same
337    /// statement lifecycle as textual SQL (snapshot guard, config/secret
338    /// guards, coarse auth, intent locks, slow-query logging, integrity
339    /// tombstone filtering, and causal bookmarks).
340    pub fn execute_query_with_params(
341        &self,
342        query: &str,
343        params: &[Value],
344    ) -> RedDBResult<RuntimeQueryResult> {
345        if params.is_empty() {
346            return self.execute_query(query);
347        }
348        super::execution_watchdog::label_current_execution(|| redact_sql_for_slow_log(query));
349        let started = std::time::Instant::now();
350        self.inner.node_load_telemetry.query_start();
351        let receipt = super::transactional_replication::CommitReceiptScope::begin(self);
352        let result = self.execute_query_with_params_inner(query, params);
353        self.finish_query_lifecycle(query, started, result, receipt.lsn())
354    }
355
356    /// Execute an already-bound prepared statement together with the SQL text
357    /// it was prepared from.
358    ///
359    /// This is the prepared-statement entry point for transports. The text is
360    /// what the statement frame is built from — snapshot (including `AS OF`),
361    /// coarse privilege class, intent locks, result-cache key, and slow-query
362    /// logging all describe the real statement — so a prepared execution gets
363    /// the same statement semantics as the identical SQL text (#2183). A
364    /// transport that holds a shape in a prepared registry must keep the
365    /// original text alongside it and pass it here.
366    pub fn execute_prepared_query(
367        &self,
368        query: &str,
369        expr: QueryExpr,
370    ) -> RedDBResult<RuntimeQueryResult> {
371        let started = std::time::Instant::now();
372        self.inner.node_load_telemetry.query_start();
373        let receipt = super::transactional_replication::CommitReceiptScope::begin(self);
374        let result = self.execute_bound_query_expr_in_frame(query, expr);
375        self.finish_query_lifecycle(query, started, result, receipt.lsn())
376    }
377
378    fn finish_query_lifecycle(
379        &self,
380        query: &str,
381        started: std::time::Instant,
382        mut result: RedDBResult<RuntimeQueryResult>,
383        commit_lsn: Option<u64>,
384    ) -> RedDBResult<RuntimeQueryResult> {
385        // Issue #765 / S6 — filter integrity-tombstoned rows out of SELECT
386        // results before they reach any consumer. Fast no-op (one relaxed
387        // atomic load) unless an input-stream digest mismatch has tombstoned
388        // a RID range on this store.
389        result = result.and_then(|mut value| {
390            if value.statement_type == "select" {
391                self.filter_integrity_tombstoned(&mut value.result)?;
392            }
393            super::query_budget::check_result(self.resource_limits(), &value)?;
394            Ok(value)
395        });
396        self.finish_collection_description_transaction(&result);
397        let elapsed_ms = started.elapsed().as_millis() as u64;
398
399        // Build EffectiveScope from the same thread-locals frame-build
400        // consults — keeps the slow-log row consistent with the audit /
401        // RLS view of "this statement". `ai_scope()` is the canonical
402        // builder.
403        let scope = self.ai_scope();
404        let kind = match result
405            .as_ref()
406            .map(|r| r.statement_type)
407            .unwrap_or("select")
408        {
409            "select" => crate::telemetry::slow_query_logger::QueryKind::Select,
410            "insert" => crate::telemetry::slow_query_logger::QueryKind::Insert,
411            "update" => crate::telemetry::slow_query_logger::QueryKind::Update,
412            "delete" => crate::telemetry::slow_query_logger::QueryKind::Delete,
413            _ => crate::telemetry::slow_query_logger::QueryKind::Internal,
414        };
415        let logged_query = redact_sql_for_slow_log(query);
416        self.inner
417            .slow_query_logger
418            .record(kind, elapsed_ms, logged_query, &scope);
419
420        // Issue #1241 — record latency into the bounded per-`kind`
421        // histogram substrate (always, not only above the slow-query
422        // threshold). `started.elapsed()` is re-read here for sub-ms
423        // resolution; the cost is one `Instant::now` plus a handful of
424        // relaxed atomic adds (see `query_latency_telemetry` docs).
425        self.inner
426            .query_latency_telemetry
427            .observe(kind, started.elapsed().as_secs_f64());
428
429        // Issue #1245 — decrement the active-query gauge. One relaxed
430        // atomic sub; the matching increment happened at execute_query /
431        // execute_query_with_params entry.
432        self.inner.node_load_telemetry.query_finish();
433
434        if let Ok(ref mut query_result) = result {
435            if matches!(
436                query_result.statement_type,
437                "insert" | "update" | "delete" | "commit"
438            ) {
439                let lsn = if self.inner.db.replication.is_some() {
440                    commit_lsn
441                } else if self.current_xid().is_none() {
442                    Some(self.cdc_current_lsn())
443                } else {
444                    None
445                };
446                query_result.bookmark = lsn.map(|lsn| {
447                    crate::replication::CausalBookmark::new(self.current_replication_term(), lsn)
448                        .encode()
449                });
450            }
451        }
452
453        result
454    }
455
456    fn execute_query_with_params_inner(
457        &self,
458        query: &str,
459        params: &[Value],
460    ) -> RedDBResult<RuntimeQueryResult> {
461        let parsed = self.parameterized_query_ast(query)?;
462        let bound = crate::storage::query::user_params::bind(&parsed, params).map_err(|err| {
463            RedDBError::Validation {
464                message: err.to_string(),
465                validation: crate::json!({
466                    "code": "INVALID_PARAMS",
467                    "surface": "query.params",
468                }),
469            }
470        })?;
471        self.execute_bound_query_expr_in_frame(query, bound)
472    }
473
474    /// Cache only the unbound parser output. Binding, views, authorization,
475    /// configuration and snapshots are resolved anew for every execution.
476    fn parameterized_query_ast(&self, query: &str) -> RedDBResult<QueryExpr> {
477        use crate::storage::query::planner::{CachedPlan, QueryPlan};
478
479        // Keep exact parameterized statements separate from normalized plans.
480        let key = format!("\0parameters\0{query}");
481        if let Some(parsed) = self
482            .inner
483            .query_cache
484            .read()
485            .peek(&key)
486            .filter(|entry| entry.matches_exact_query(query))
487            .map(|entry| entry.plan.original.clone())
488        {
489            return Ok(parsed);
490        }
491        let parsed = parse_multi(query).map_err(|err| RedDBError::Query(err.to_string()))?;
492        let plan = QueryPlan::new(parsed.clone(), parsed.clone(), Default::default());
493        self.inner
494            .query_cache
495            .write()
496            .insert(key, CachedPlan::new(plan).with_exact_query(query));
497        Ok(parsed)
498    }
499
500    fn execute_bound_query_expr_in_frame(
501        &self,
502        query: &str,
503        expr: QueryExpr,
504    ) -> RedDBResult<RuntimeQueryResult> {
505        let rewritten_query = super::red_schema::rewrite_virtual_names(query);
506        let execution_query = rewritten_query.as_deref().unwrap_or(query);
507        let frame = super::statement_frame::StatementExecutionFrame::build(
508            self,
509            super::statement_frame::StatementIdentity::Text(execution_query),
510        )?;
511        // Box the guards so the ~640-byte StatementFrameGuards struct lives on
512        // the heap rather than the call stack — important for recursive paths
513        // (view refresh, nested queries) where the stack can be as small as 2 MB.
514        let _frame_guards = Box::new(frame.install(self));
515        let _log_span = crate::telemetry::span::query_span(query).entered();
516
517        let expr = self.rewrite_view_refs(expr);
518        let mode = detect_mode(execution_query);
519        let control_event_specs = query_control_event_specs(&expr);
520        let _lock_guard = match frame.prepare_dispatch(self, &expr) {
521            Ok(guard) => guard,
522            Err(err) => {
523                let outcome = control_event_outcome_for_error(&err);
524                for spec in &control_event_specs {
525                    self.emit_control_event(
526                        spec.kind,
527                        outcome,
528                        spec.action,
529                        spec.resource.clone(),
530                        Some(err.to_string()),
531                        spec.fields.clone(),
532                    )?;
533                }
534                return Err(err);
535            }
536        };
537
538        self.dispatch_expr(expr, query, mode)
539    }
540
541    pub fn causal_session(&self) -> crate::runtime::CausalSession {
542        crate::runtime::CausalSession {
543            runtime: self.clone(),
544            bookmark: None,
545            wait_timeout: std::time::Duration::from_secs(5),
546        }
547    }
548
549    pub fn wait_for_bookmark(
550        &self,
551        bookmark: &crate::replication::CausalBookmark,
552        timeout: std::time::Duration,
553    ) -> RedDBResult<()> {
554        let deadline = std::time::Instant::now() + timeout;
555        loop {
556            let applied_lsn = self.local_contiguous_applied_lsn();
557            if applied_lsn >= bookmark.commit_lsn() {
558                return Ok(());
559            }
560            let now = std::time::Instant::now();
561            if now >= deadline {
562                return Err(RedDBError::InvalidOperation(format!(
563                    "timed out waiting for causal bookmark lsn {}; applied={}",
564                    bookmark.commit_lsn(),
565                    applied_lsn
566                )));
567            }
568            let remaining = deadline.saturating_duration_since(now);
569            std::thread::sleep(remaining.min(std::time::Duration::from_millis(5)));
570        }
571    }
572
573    fn local_contiguous_applied_lsn(&self) -> u64 {
574        match self.inner.db.options().replication.role {
575            crate::replication::ReplicationRole::Replica { .. } => {
576                self.config_u64("replication.last_applied_lsn", 0)
577            }
578            _ => self.replication_commit_lsn(),
579        }
580    }
581
582    #[inline(never)]
583    pub(super) fn execute_query_inner(&self, query: &str) -> RedDBResult<RuntimeQueryResult> {
584        // ── ULTRA-TURBO: autocommit `SELECT * FROM t WHERE _entity_id = N` ──
585        //
586        // Moved above every boot-cost the normal path pays (WITHIN
587        // strip, SET LOCAL parse, transaction-state reads, snapshot
588        // guard, and tracing span) because the bench's
589        // `select_point` scenario was observed at 28× vs PostgreSQL —
590        // the dominant cost wasn't the entity fetch but the ceremony
591        // before it. Only fires when there's no ambient transaction
592        // context or WITHIN override, so the snapshot install we skip
593        // truly is a no-op for this query.
594        if !has_scope_override_active()
595            && !query.trim_start().starts_with("WITHIN")
596            && !query.trim_start().starts_with("within")
597            && !self.inner.query_audit.has_rules()
598            && !self
599                .inner
600                .transaction_state
601                .in_transaction(current_connection_id())
602        {
603            if let Some(result) = self.try_fast_entity_lookup(query) {
604                return result;
605            }
606        }
607
608        // `WITHIN TENANT '<id>' [USER '<u>'] [AS ROLE '<r>'] <stmt>` —
609        // strip the prefix, push a stack-scoped override, recurse on
610        // the inner statement, pop on return. Stack lives in a
611        // thread-local but is balanced by the RAII guard, so a
612        // pool-shared connection cannot leak the override across
613        // requests and an early `?` return still pops cleanly.
614        match crate::runtime::within_clause::try_strip_within_prefix(query) {
615            Ok(Some((scope, inner))) => {
616                self.check_scope_override_privilege(&scope)?;
617                let _scope_guard = ScopeOverrideGuard::install(scope);
618                // Re-enter the inner path, NOT `execute_query`, so the
619                // slow-query lifecycle hook records exactly one row per
620                // top-level statement (the WITHIN-stripped form would
621                // double-record).
622                return self.execute_query_inner(inner);
623            }
624            Ok(None) => {}
625            Err(msg) => return Err(RedDBError::Query(msg)),
626        }
627
628        // `EXPLAIN ANALYZE <dml>` — paid truth tier. Executes the
629        // mutating statement inside a transaction that is always
630        // rolled back, then reports the actual affected row count.
631        if let Some(inner) = strip_explain_analyze_prefix(query) {
632            return self.explain_analyze_as_rows(query, inner);
633        }
634
635        // `EXPLAIN <stmt>` — introspection. Runs the planner on the
636        // inner statement (WITHOUT executing it) and returns the
637        // CanonicalLogicalNode tree as rows so the caller can see the
638        // operator shape and estimated cost. `EXPLAIN ALTER FOR ...`
639        // is a distinct schema-diff command and continues down the
640        // regular SQL path.
641        if let Some(inner) = strip_explain_prefix(query) {
642            return self.explain_as_rows(query, inner);
643        }
644
645        // `SET LOCAL TENANT '<id>'` — write the per-transaction tenant
646        // override and return. Outside a transaction the statement is
647        // an error (matches PG semantics: SET LOCAL only takes effect
648        // within an active transaction).
649        if let Some(value) = parse_set_local_tenant(query)? {
650            self.check_scope_tenant_privilege(value.as_deref())?;
651            let conn_id = current_connection_id();
652            if !self.inner.transaction_state.in_transaction(conn_id) {
653                return Err(RedDBError::Query(
654                    "SET LOCAL TENANT requires an active transaction".to_string(),
655                ));
656            }
657            self.inner
658                .transaction_state
659                .set_local_tenant(conn_id, value.clone());
660            return Ok(RuntimeQueryResult::ok_message(
661                query.to_string(),
662                &match &value {
663                    Some(id) => format!("local tenant set: {id}"),
664                    None => "local tenant cleared".to_string(),
665                },
666                "set_local_tenant",
667            ));
668        }
669
670        if super::red_schema::is_system_schema_write(query) {
671            return Err(RedDBError::Query(
672                super::red_schema::READ_ONLY_ERROR.to_string(),
673            ));
674        }
675
676        if let Some(command) = parse_runtime_vcs_command(query) {
677            let command = command?;
678            self.check_vcs_command_privilege(&command)?;
679            return self.execute_vcs_command(query, detect_mode(query), command);
680        }
681
682        if let Some(create_source) = super::analytics_source_catalog::parse_create_statement(query)?
683        {
684            return self.execute_create_analytics_source(query, create_source);
685        }
686
687        // Issue #790 — `READ METRIC <path>` is intentionally rejected at
688        // v0. The descriptor itself is readable through
689        // `red.analytics.metrics`; the *output* read returns a
690        // structured error so callers can tell "execution engine not yet
691        // built" apart from "metric does not exist".
692        if let Some(path) = super::metric_descriptor_catalog::parse_read_metric_statement(query) {
693            return Err(super::metric_descriptor_catalog::read_output_unsupported(
694                &path,
695            ));
696        }
697
698        // Issue #918 / ADR 0035 — leaderboard rank capability catalog
699        // declarations are still recognised before the general parser.
700        // Rank reads themselves are parser AST nodes, including Redis-flavor
701        // Z* sugar that desugars to the same canonical rank shapes.
702        if let Some(parsed) = super::ranking_descriptor_catalog::parse_create_ranking(query) {
703            return self.execute_create_ranking(query, parsed?);
704        }
705        if super::ranking_descriptor_catalog::parse_show_rankings(query) {
706            return self.execute_show_rankings(query);
707        }
708
709        let rewritten_query = super::red_schema::rewrite_virtual_names(query);
710        let execution_query = rewritten_query.as_deref().unwrap_or(query);
711
712        let frame = super::statement_frame::StatementExecutionFrame::build(
713            self,
714            super::statement_frame::StatementIdentity::Text(execution_query),
715        )?;
716        let _frame_guards = Box::new(frame.install(self));
717
718        // Phase 6 logging: enter a span stamped with conn_id / tenant
719        // / query_len. Every downstream tracing::info!/warn!/error!
720        // inherits these fields — no need to thread them manually
721        // through storage/scan layers. Entered AFTER the WITHIN /
722        // SET LOCAL TENANT resolution above so the span reflects the
723        // effective scope for this statement.
724        let _log_span = crate::telemetry::span::query_span(query).entered();
725
726        // ── CTE prelude (#41) — `WITH x AS (...) SELECT ... FROM x` ──
727        if let Some(rewritten) = frame.prepare_cte(execution_query)? {
728            return self.execute_query_expr(rewritten);
729        }
730
731        // ── TURBO: bypass SQL parse for SELECT * FROM x WHERE _entity_id = N ──
732        if !self.inner.query_audit.has_rules() {
733            if let Some(result) = self.try_fast_entity_lookup(execution_query) {
734                return result;
735            }
736        }
737
738        // ── Result cache: return cached result if still fresh (30s TTL) ──
739        if !self.inner.query_audit.has_rules() {
740            if let Some(result) = frame.read_result_cache(self) {
741                return Ok(result);
742            }
743        }
744
745        #[cfg(test)]
746        RESULT_CACHE_MISS_EXECUTIONS.with(|count| count.set(count.get() + 1));
747
748        let prepared = frame.prepare_statement(self, execution_query)?;
749        let mode = prepared.mode;
750        let expr = prepared.expr;
751
752        let _query_budget = if super::query_budget::is_materialized_read(&expr) {
753            Some(self.query_budget_scope()?)
754        } else {
755            None
756        };
757
758        let statement = query_expr_name(&expr);
759        let result_cache_scopes = query_expr_result_cache_scopes(&expr);
760        let control_event_specs = query_control_event_specs(&expr);
761        let query_audit_plan = query_audit_plan(&expr);
762
763        let _lock_guard = match frame.prepare_dispatch(self, &expr) {
764            Ok(guard) => guard,
765            Err(err) => {
766                let outcome = control_event_outcome_for_error(&err);
767                for spec in &control_event_specs {
768                    self.emit_control_event(
769                        spec.kind,
770                        outcome,
771                        spec.action,
772                        spec.resource.clone(),
773                        Some(err.to_string()),
774                        spec.fields.clone(),
775                    )?;
776                }
777                return Err(err);
778            }
779        };
780        let query_audit_started = std::time::Instant::now();
781
782        let query_result = match expr {
783            QueryExpr::Function(ref command) => self.execute_function(query, command),
784            QueryExpr::Graph(_) | QueryExpr::Path(_) => {
785                self.execute_materialized_graph(query, mode, statement, &expr)
786            }
787            QueryExpr::Table(table) => {
788                let table = self.resolve_table_expr_subqueries(
789                    table,
790                    &frame as &dyn super::statement_frame::ReadFrame,
791                )?;
792                // Table-valued functions (e.g. components(g)) dispatch to a
793                // read-only executor before any catalog/virtual-table routing
794                // (issue #795).
795                if let Some(TableSource::Function {
796                    name,
797                    args,
798                    named_args,
799                }) = table.source.clone()
800                {
801                    // The graph-collection form is cacheable (issue #802): the
802                    // result-cache read at the top of this function keys on the
803                    // query string, and `result_cache_scopes` carries the graph
804                    // collection (see `collect_table_source_scopes`) so a write
805                    // to it invalidates the entry. Deterministic algorithm
806                    // output is worth caching at any row count, so the write
807                    // bypasses the generic ≤5-row payload heuristic.
808                    let tvf_result = RuntimeQueryResult {
809                        query: query.to_string(),
810                        mode,
811                        statement,
812                        engine: "runtime-graph-tvf",
813                        result: self.execute_table_function(&name, &args, &named_args)?,
814                        affected_rows: 0,
815                        statement_type: "select",
816                        bookmark: None,
817                        notice: None,
818                    };
819                    frame.write_result_cache(self, &tvf_result, result_cache_scopes.clone());
820                    return Ok(tvf_result);
821                }
822                // Inline-graph TVF (issue #799): the graph is supplied by two
823                // subqueries instead of a collection reference. Unlike the
824                // graph-collection form, the result IS cacheable — its cache
825                // key is the query string (the result-cache read at the top of
826                // `execute_query_inner` keys on it) and `result_cache_scopes`
827                // already carries the `nodes`/`edges` source collections, so a
828                // write to any of them invalidates the entry.
829                if let Some(TableSource::InlineGraphFunction {
830                    name,
831                    nodes,
832                    edges,
833                    named_args,
834                }) = table.source.clone()
835                {
836                    let inline_result = RuntimeQueryResult {
837                        query: query.to_string(),
838                        mode,
839                        statement,
840                        engine: "runtime-graph-tvf-inline",
841                        result: self.execute_inline_graph_function(
842                            &name,
843                            &nodes,
844                            &edges,
845                            &named_args,
846                        )?,
847                        affected_rows: 0,
848                        statement_type: "select",
849                        bookmark: None,
850                        notice: None,
851                    };
852                    frame.write_result_cache(self, &inline_result, result_cache_scopes);
853                    return Ok(inline_result);
854                }
855                if super::red_schema::is_virtual_table(&table.table) {
856                    return Ok(RuntimeQueryResult {
857                        query: query.to_string(),
858                        mode,
859                        statement,
860                        engine: "runtime-red-schema",
861                        result: super::red_schema::red_query(
862                            self,
863                            &table.table,
864                            &table,
865                            &frame as &dyn super::statement_frame::ReadFrame,
866                        )?,
867                        affected_rows: 0,
868                        statement_type: "select",
869                        bookmark: None,
870                        notice: None,
871                    });
872                }
873
874                // `<graph>.<output>` analytics virtual view (issue #800).
875                // Recomputed on demand — intentionally not result-cached, so it
876                // always reflects the current graph data.
877                if let Some(view_result) = self.try_resolve_analytics_view(
878                    &table,
879                    &frame as &dyn super::statement_frame::ReadFrame,
880                )? {
881                    return Ok(RuntimeQueryResult {
882                        query: query.to_string(),
883                        mode,
884                        statement,
885                        engine: "runtime-graph-analytics-view",
886                        result: view_result,
887                        affected_rows: 0,
888                        statement_type: "select",
889                        bookmark: None,
890                        notice: None,
891                    });
892                }
893
894                if let Some(result) = self.execute_probabilistic_select(&table)? {
895                    return Ok(RuntimeQueryResult {
896                        query: query.to_string(),
897                        mode,
898                        statement,
899                        engine: "runtime-probabilistic",
900                        result,
901                        affected_rows: 0,
902                        statement_type: "select",
903                        bookmark: None,
904                        notice: None,
905                    });
906                }
907
908                // Foreign-table intercept (Phase 3.2.2 PG parity).
909                //
910                // When the referenced table matches a `CREATE FOREIGN TABLE`
911                // registration, short-circuit into the FDW scan. Phase 3.2
912                // wrappers don't yet support pushdown, so filters/projections
913                // apply post-scan via `apply_foreign_table_filters` — good
914                // enough for correctness; perf work lands in 3.2.3.
915                if self.inner.foreign_tables.is_foreign_table(&table.table) {
916                    let records = self
917                        .inner
918                        .foreign_tables
919                        .scan(&table.table)
920                        .map_err(|e| RedDBError::Internal(e.to_string()))?;
921                    let result = apply_foreign_table_filters(records, &table);
922                    return Ok(RuntimeQueryResult {
923                        query: query.to_string(),
924                        mode,
925                        statement,
926                        engine: "runtime-fdw",
927                        result,
928                        affected_rows: 0,
929                        statement_type: "select",
930                        bookmark: None,
931                        notice: None,
932                    });
933                }
934
935                // Row-Level Security enforcement (Phase 2.5.2 PG parity).
936                //
937                // When RLS is enabled on this table, fetch every policy
938                // that applies to the current (role, SELECT) pair and
939                // fold them into the query's WHERE clause: policies
940                // OR-combine (any of them admitting the row is enough),
941                // then AND into the caller's existing filter.
942                //
943                // Anonymous callers (no thread-local identity) pass
944                // `role = None`; policies with a specific `TO role`
945                // clause skip, but `TO PUBLIC` policies still apply.
946                //
947                // When `inject_rls_filters` returns `None` the table has
948                // RLS enabled but no policy admits the caller's role —
949                // short-circuit with an empty result set instead of
950                // synthesising a contradiction filter.
951                let Some(table_with_rls) = self.authorize_relational_table_select(
952                    table,
953                    &frame as &dyn super::statement_frame::ReadFrame,
954                )?
955                else {
956                    let empty = crate::storage::query::unified::UnifiedResult::empty();
957                    return Ok(RuntimeQueryResult {
958                        query: query.to_string(),
959                        mode,
960                        statement,
961                        engine: "runtime-table-rls",
962                        result: empty,
963                        affected_rows: 0,
964                        statement_type: "select",
965                        bookmark: None,
966                        notice: None,
967                    });
968                };
969                Ok(RuntimeQueryResult {
970                    query: query.to_string(),
971                    mode,
972                    statement,
973                    engine: "runtime-table",
974                    // #885: lend the frame-owned row-buffer arena to the
975                    // streaming path so chunk buffers are reused across
976                    // this statement's chunk-fetches instead of allocated
977                    // fresh per chunk. This is the table-query dispatch
978                    // that receives a frame-owned arena; the prepared and
979                    // subquery dispatch paths keep `None` for the arena.
980                    result: execute_runtime_table_query_in(
981                        &self.inner.db,
982                        &table_with_rls,
983                        Some(&self.inner.index_store),
984                        Some(frame.row_arena()),
985                    )?,
986                    affected_rows: 0,
987                    statement_type: "select",
988                    bookmark: None,
989                    notice: None,
990                })
991            }
992            QueryExpr::Join(join) => {
993                // Fold per-table RLS filters into each `QueryExpr::Table`
994                // leaf of the join tree before executing. Without this
995                // the join executor scans both tables raw and ignores
996                // policies — a `WITHIN TENANT 'x'` against a join of
997                // two tenant-scoped tables would leak cross-tenant rows.
998                // When any leaf has RLS enabled and zero matching policy,
999                // short-circuit to an empty join result instead of
1000                // emitting a contradiction filter.
1001                let join_with_rls = match self.authorize_relational_join_select(
1002                    join,
1003                    &frame as &dyn super::statement_frame::ReadFrame,
1004                )? {
1005                    Some(j) => j,
1006                    None => {
1007                        return Ok(RuntimeQueryResult {
1008                            query: query.to_string(),
1009                            mode,
1010                            statement,
1011                            engine: "runtime-join-rls",
1012                            result: crate::storage::query::unified::UnifiedResult::empty(),
1013                            affected_rows: 0,
1014                            statement_type: "select",
1015                            bookmark: None,
1016                            notice: None,
1017                        });
1018                    }
1019                };
1020                Ok(RuntimeQueryResult {
1021                    query: query.to_string(),
1022                    mode,
1023                    statement,
1024                    engine: "runtime-join",
1025                    result: execute_runtime_join_query(self, &join_with_rls)?,
1026                    affected_rows: 0,
1027                    statement_type: "select",
1028                    bookmark: None,
1029                    notice: None,
1030                })
1031            }
1032            QueryExpr::Vector(vector) => Ok(RuntimeQueryResult {
1033                query: query.to_string(),
1034                mode,
1035                statement,
1036                engine: "runtime-vector",
1037                result: execute_runtime_vector_query(self, &vector)?,
1038                affected_rows: 0,
1039                statement_type: "select",
1040                bookmark: None,
1041                notice: None,
1042            }),
1043            QueryExpr::Hybrid(hybrid) => Ok(RuntimeQueryResult {
1044                query: query.to_string(),
1045                mode,
1046                statement,
1047                engine: "runtime-hybrid",
1048                result: execute_runtime_hybrid_query(self, &hybrid)?,
1049                affected_rows: 0,
1050                statement_type: "select",
1051                bookmark: None,
1052                notice: None,
1053            }),
1054            QueryExpr::RankOf(ref rank) => self.execute_rank_of(query, rank),
1055            QueryExpr::ApproxRankOf(ref rank) => self.execute_approx_rank_of(query, rank),
1056            QueryExpr::RankRange(ref range) => self.execute_rank_range(query, range),
1057            // DML execution
1058            QueryExpr::Insert(ref insert) if super::red_schema::is_virtual_table(&insert.table) => {
1059                Err(RedDBError::Query(
1060                    super::red_schema::READ_ONLY_ERROR.to_string(),
1061                ))
1062            }
1063            QueryExpr::Update(ref update) if super::red_schema::is_virtual_table(&update.table) => {
1064                Err(RedDBError::Query(
1065                    super::red_schema::READ_ONLY_ERROR.to_string(),
1066                ))
1067            }
1068            // The retention sweeper's scoped DELETE is the only write that may
1069            // reach the physical `red.control_events` ledger (issue #2900).
1070            QueryExpr::Delete(ref delete)
1071                if super::red_schema::is_virtual_table(&delete.table)
1072                    && !super::retention_sweeper::is_retention_delete(&delete.table) =>
1073            {
1074                Err(RedDBError::Query(
1075                    super::red_schema::READ_ONLY_ERROR.to_string(),
1076                ))
1077            }
1078            QueryExpr::Insert(ref insert) => self.execute_insert(query, insert),
1079            QueryExpr::Update(ref update) => self
1080                .with_deferred_store_wal_for_dml(self.update_may_emit_events(update), || {
1081                    self.execute_update(query, update)
1082                }),
1083            QueryExpr::Delete(ref delete) => self
1084                .with_deferred_store_wal_for_dml(self.delete_may_emit_events(delete), || {
1085                    self.execute_delete(query, delete)
1086                }),
1087            // DDL execution
1088            QueryExpr::CreateTable(ref create) => self.execute_create_table(query, create),
1089            QueryExpr::CreateCollection(ref create) => {
1090                self.execute_create_collection(query, create)
1091            }
1092            QueryExpr::CreateVector(ref create) => self.execute_create_vector(query, create),
1093            QueryExpr::DropTable(ref drop_tbl) => self.execute_drop_table(query, drop_tbl),
1094            QueryExpr::DropGraph(ref drop_graph) => self.execute_drop_graph(query, drop_graph),
1095            QueryExpr::DropVector(ref drop_vector) => self.execute_drop_vector(query, drop_vector),
1096            QueryExpr::DropDocument(ref drop_document) => {
1097                self.execute_drop_document(query, drop_document)
1098            }
1099            QueryExpr::DropKv(ref drop_kv) => self.execute_drop_kv(query, drop_kv),
1100            QueryExpr::DropCollection(ref drop_collection) => {
1101                self.execute_drop_collection(query, drop_collection)
1102            }
1103            QueryExpr::Truncate(ref truncate) => self.execute_truncate(query, truncate),
1104            QueryExpr::AlterTable(ref alter) => self.execute_alter_table(query, alter),
1105            QueryExpr::CreateVcsRef(ref create) => self.execute_create_vcs_ref(query, create),
1106            QueryExpr::DropVcsRef(ref drop_ref) => self.execute_drop_vcs_ref(query, drop_ref),
1107            QueryExpr::ForkStore(ref fork) => self.execute_fork_store(query, fork),
1108            QueryExpr::PromoteFork(ref promote_fork) => {
1109                self.execute_promote_fork(query, promote_fork)
1110            }
1111            QueryExpr::DropFork(ref drop_fork) => self.execute_drop_fork(query, drop_fork),
1112            QueryExpr::ExplainAlter(ref explain) => self.execute_explain_alter(query, explain),
1113            // Graph analytics commands
1114            QueryExpr::GraphCommand(ref cmd) => self.execute_graph_command(query, cmd),
1115            // Search commands
1116            QueryExpr::SearchCommand(ref cmd) => self.execute_search_command(query, cmd),
1117            // ASK: RAG query with LLM synthesis
1118            QueryExpr::Ask(ref ask) => self.execute_ask(query, ask),
1119            QueryExpr::CreateIndex(ref create_idx) => self.execute_create_index(query, create_idx),
1120            QueryExpr::DropIndex(ref drop_idx) => self.execute_drop_index(query, drop_idx),
1121            QueryExpr::ProbabilisticCommand(ref cmd) => {
1122                self.execute_probabilistic_command(query, cmd)
1123            }
1124            // Time-series DDL
1125            QueryExpr::CreateTimeSeries(ref ts) => self.execute_create_timeseries(query, ts),
1126            QueryExpr::CreateMetric(ref metric) => self.execute_create_metric(query, metric),
1127            QueryExpr::AlterMetric(ref alter) => self.execute_alter_metric(query, alter),
1128            QueryExpr::CreateSlo(ref slo) => self.execute_create_slo(query, slo),
1129            QueryExpr::DropTimeSeries(ref ts) => self.execute_drop_timeseries(query, ts),
1130            // Queue DDL and commands
1131            QueryExpr::CreateQueue(ref q) => self.execute_create_queue(query, q),
1132            QueryExpr::AlterQueue(ref q) => self.execute_alter_queue(query, q),
1133            QueryExpr::DropQueue(ref q) => self.execute_drop_queue(query, q),
1134            QueryExpr::QueueSelect(ref q) => self.execute_queue_select(query, q),
1135            QueryExpr::QueueCommand(ref cmd) => self
1136                .with_deferred_store_wal_if_transaction(|| self.execute_queue_command(query, cmd)),
1137            QueryExpr::EventsBackfill(ref backfill) => {
1138                self.execute_events_backfill(query, backfill)
1139            }
1140            QueryExpr::EventsBackfillStatus { ref collection } => Err(RedDBError::Query(format!(
1141                "EVENTS BACKFILL STATUS for '{collection}' is not implemented in this slice"
1142            ))),
1143            QueryExpr::KvCommand(ref cmd) => self.execute_kv_command(query, cmd),
1144            QueryExpr::ConfigCommand(ref cmd) => self.execute_config_command(query, cmd),
1145            QueryExpr::CreateTree(ref tree) => self.execute_create_tree(query, tree),
1146            QueryExpr::DropTree(ref tree) => self.execute_drop_tree(query, tree),
1147            QueryExpr::TreeCommand(ref cmd) => self.execute_tree_command(query, cmd),
1148            // SET CONFIG key = value
1149            QueryExpr::SetConfig { ref key, ref value } => {
1150                if key.starts_with("red.secret.") {
1151                    return Err(RedDBError::Query(
1152                        "red.secret.* is reserved for vault secrets; use SET SECRET".to_string(),
1153                    ));
1154                }
1155                if key.starts_with("red.secrets.") {
1156                    return Err(RedDBError::Query(
1157                        "red.secrets.* is reserved for vault secrets; use SET SECRET".to_string(),
1158                    ));
1159                }
1160                if key.starts_with("red.") {
1161                    return Err(RedDBError::Query(format!(
1162                        "config key `{key}` is invalid inside red.config: omit the redundant `red.` prefix"
1163                    )));
1164                }
1165                // ADR-0068 §5 clean break: reject the removed AI config keys
1166                // (old `default.*` provider/model and per-alias base_url shape)
1167                // with a didactic error naming the replacement key.
1168                crate::ai::validate_ai_config_key_on_write(key)?;
1169                let control_events_retention = key == super::control_events_retention::CONFIG_KEY;
1170                if control_events_retention {
1171                    let raw = match value {
1172                        Value::Text(text) => text.to_string(),
1173                        other => other.to_string(),
1174                    };
1175                    super::control_events_retention::parse_retention(&raw)
1176                        .map_err(RedDBError::Query)?;
1177                }
1178                // The managed-config guardrail runs first: it owns the
1179                // didactic error and the `config:write` control event for
1180                // registry-managed keys. The generic capability gate below
1181                // then covers every other key.
1182                match self.check_managed_config_write_for_set_config(key) {
1183                    Err(err) => Err(err),
1184                    Ok(()) => {
1185                        self.check_config_write_privilege(key)?;
1186                        let store = self.inner.db.store();
1187                        let json_val = match value {
1188                            Value::Text(s) => crate::serde_json::Value::String(s.to_string()),
1189                            Value::Integer(n) => crate::serde_json::Value::Number(*n as f64),
1190                            Value::Float(n) => crate::serde_json::Value::Number(*n),
1191                            Value::Boolean(b) => crate::serde_json::Value::Bool(*b),
1192                            _ => crate::serde_json::Value::String(value.to_string()),
1193                        };
1194                        store
1195                            .try_set_config_tree(key, &json_val)
1196                            .map_err(RedDBError::from)?;
1197                        update_current_config_value(key, value.clone());
1198                        if control_events_retention {
1199                            self.apply_control_events_retention()?;
1200                        }
1201                        // Config changes can flip runtime behavior mid-session
1202                        // (auto_decrypt, auto_encrypt, etc.) — invalidate the
1203                        // result cache so subsequent reads re-execute against
1204                        // the new config.
1205                        self.invalidate_result_cache();
1206                        Ok(RuntimeQueryResult::ok_message(
1207                            query.to_string(),
1208                            &format!("config set: {key}"),
1209                            "set",
1210                        ))
1211                    }
1212                }
1213            }
1214            // SET SECRET key = value
1215            QueryExpr::SetSecret { ref key, ref value } => {
1216                if key.starts_with("red.config.") {
1217                    return Err(RedDBError::Query(
1218                        "red.config.* is reserved for config; use SET CONFIG".to_string(),
1219                    ));
1220                }
1221                reject_engine_internal_vault_key(key)?;
1222                if key.starts_with("red.secret.") {
1223                    self.set_internal_provider_secret(
1224                        key,
1225                        if value.is_null() {
1226                            None
1227                        } else {
1228                            Some(secret_sql_value_to_string(value)?)
1229                        },
1230                    )?;
1231                    return Ok(RuntimeQueryResult::ok_message(
1232                        query.to_string(),
1233                        &format!("secret set: {key}"),
1234                        "set_secret",
1235                    ));
1236                }
1237                let value = if value.is_null() {
1238                    None
1239                } else {
1240                    Some(secret_sql_value_to_string(value)?)
1241                };
1242                self.set_user_secret(key, value.clone())?;
1243                update_current_secret_value(key, value);
1244                Ok(RuntimeQueryResult::ok_message(
1245                    query.to_string(),
1246                    &format!("secret set: {key}"),
1247                    "set_secret",
1248                ))
1249            }
1250            // DELETE SECRET key
1251            QueryExpr::DeleteSecret { ref key } => {
1252                reject_engine_internal_vault_key(key)?;
1253                if key.starts_with("red.secret.") {
1254                    self.set_internal_provider_secret(key, None)?;
1255                    return Ok(RuntimeQueryResult::ok_message(
1256                        query.to_string(),
1257                        &format!("secret deleted: {key}"),
1258                        "delete_secret",
1259                    ));
1260                }
1261                self.set_user_secret(key, None)?;
1262                update_current_secret_value(key, None);
1263                Ok(RuntimeQueryResult::ok_message(
1264                    query.to_string(),
1265                    &format!("secret deleted: {key}"),
1266                    "delete_secret",
1267                ))
1268            }
1269            // SET KV key = value — plain (non-encrypted) user KV entry (#1602)
1270            QueryExpr::SetKv { ref key, ref value } => {
1271                let auth_store = self.inner.auth_store.read().clone().ok_or_else(|| {
1272                    RedDBError::Query("SET KV requires an auth store".to_string())
1273                })?;
1274                self.check_kv_write_privilege(&auth_store, key)?;
1275                // `SET KV k = NULL` deletes, mirroring `SET SECRET`.
1276                if matches!(value, Value::Null) {
1277                    auth_store.plain_kv_delete(key);
1278                    update_current_kv_value(key, None);
1279                    self.invalidate_result_cache();
1280                    return Ok(RuntimeQueryResult::ok_message(
1281                        query.to_string(),
1282                        &format!("kv deleted: {key}"),
1283                        "delete_kv",
1284                    ));
1285                }
1286                let value = secret_sql_value_to_string(value)?;
1287                auth_store.plain_kv_set(key.clone(), value.clone());
1288                update_current_kv_value(key, Some(value));
1289                self.invalidate_result_cache();
1290                Ok(RuntimeQueryResult::ok_message(
1291                    query.to_string(),
1292                    &format!("kv set: {key}"),
1293                    "set_kv",
1294                ))
1295            }
1296            // DELETE KV key
1297            QueryExpr::DeleteKv { ref key } => {
1298                let auth_store = self.inner.auth_store.read().clone().ok_or_else(|| {
1299                    RedDBError::Query("DELETE KV requires an auth store".to_string())
1300                })?;
1301                self.check_kv_write_privilege(&auth_store, key)?;
1302                let deleted = auth_store.plain_kv_delete(key);
1303                if deleted {
1304                    update_current_kv_value(key, None);
1305                }
1306                self.invalidate_result_cache();
1307                Ok(RuntimeQueryResult::ok_message(
1308                    query.to_string(),
1309                    &format!("kv deleted: {key}"),
1310                    if deleted {
1311                        "delete_kv"
1312                    } else {
1313                        "delete_kv_not_found"
1314                    },
1315                ))
1316            }
1317            QueryExpr::Scrub { background, budget } => {
1318                self.execute_scrub_query(query, mode, background, budget)
1319            }
1320            // SHOW SECRET[S] [prefix]
1321            QueryExpr::ShowSecrets { ref prefix } => {
1322                let result = self.show_user_secrets(prefix.as_deref())?;
1323                Ok(RuntimeQueryResult {
1324                    query: query.to_string(),
1325                    mode,
1326                    statement: "show_secrets",
1327                    engine: "runtime-secret",
1328                    result,
1329                    affected_rows: 0,
1330                    statement_type: "select",
1331                    bookmark: None,
1332                    notice: None,
1333                })
1334            }
1335            // SHOW CONFIG [prefix] [AS JSON|FORMAT JSON]
1336            QueryExpr::ShowConfig {
1337                ref prefix,
1338                as_json,
1339            } => {
1340                if let Some(prefix) = prefix {
1341                    super::impl_config::validate_red_config_content_key("red.config", prefix)?;
1342                }
1343                self.check_config_read_privilege()?;
1344                let store = self.inner.db.store();
1345                let all_collections = store.list_collections();
1346                if !all_collections.contains(&"red.config".to_string()) {
1347                    if as_json {
1348                        return Ok(show_config_json_result(
1349                            query,
1350                            mode,
1351                            prefix,
1352                            crate::serde_json::Value::Object(crate::serde_json::Map::new()),
1353                        ));
1354                    }
1355                    let result = UnifiedResult::with_columns(vec!["key".into(), "value".into()]);
1356                    return Ok(RuntimeQueryResult {
1357                        query: query.to_string(),
1358                        mode,
1359                        statement: "show_config",
1360                        engine: "runtime-config",
1361                        result,
1362                        affected_rows: 0,
1363                        statement_type: "select",
1364                        bookmark: None,
1365                        notice: None,
1366                    });
1367                }
1368                let manager = store
1369                    .get_collection("red.config")
1370                    .ok_or_else(|| RedDBError::NotFound("red.config".to_string()))?;
1371                let entities = manager.query_all(|_| true);
1372                let mut latest = std::collections::BTreeMap::<String, (u64, Value, Value)>::new();
1373                for entity in entities {
1374                    if let EntityData::Row(ref row) = entity.data {
1375                        if let Some(ref named) = row.named {
1376                            let key_val = named.get("key").cloned().unwrap_or(Value::Null);
1377                            let val = named.get("value").cloned().unwrap_or(Value::Null);
1378                            let key_str = match &key_val {
1379                                Value::Text(s) => s.as_ref(),
1380                                _ => continue,
1381                            };
1382                            if key_str == super::function_catalog::REGISTRY_KEY {
1383                                continue;
1384                            }
1385                            if let Some(ref pfx) = prefix {
1386                                if !key_str.starts_with(pfx.as_str()) {
1387                                    continue;
1388                                }
1389                            }
1390                            let entity_id = entity.id.raw();
1391                            match latest.get(key_str) {
1392                                Some((prev_id, _, _)) if *prev_id > entity_id => {}
1393                                _ => {
1394                                    latest.insert(key_str.to_string(), (entity_id, key_val, val));
1395                                }
1396                            }
1397                        }
1398                    }
1399                }
1400                if as_json {
1401                    let mut tree = crate::serde_json::Value::Object(crate::serde_json::Map::new());
1402                    for (key, (_, _, val)) in latest {
1403                        let relative = match prefix {
1404                            Some(pfx) if key == *pfx => "",
1405                            Some(pfx) => key
1406                                .strip_prefix(pfx.as_str())
1407                                .and_then(|tail| tail.strip_prefix('.'))
1408                                .unwrap_or(key.as_str()),
1409                            None => key.as_str(),
1410                        };
1411                        insert_config_json_path(&mut tree, relative, val.to_json());
1412                    }
1413                    return Ok(show_config_json_result(query, mode, prefix, tree));
1414                }
1415                let mut result = UnifiedResult::with_columns(vec!["key".into(), "value".into()]);
1416                for (_, key_val, val) in latest.into_values() {
1417                    let mut record = UnifiedRecord::new();
1418                    record.set("key", key_val);
1419                    record.set("value", val);
1420                    result.push(record);
1421                }
1422                Ok(RuntimeQueryResult {
1423                    query: query.to_string(),
1424                    mode,
1425                    statement: "show_config",
1426                    engine: "runtime-config",
1427                    result,
1428                    affected_rows: 0,
1429                    statement_type: "select",
1430                    bookmark: None,
1431                    notice: None,
1432                })
1433            }
1434            // Session-local multi-tenancy handle (Phase 2.5.3).
1435            //
1436            // SET TENANT 'id' / SET TENANT NULL / RESET TENANT — writes
1437            // the thread-local; SHOW TENANT returns it. Paired with the
1438            // CURRENT_TENANT() scalar for use in RLS policies.
1439            QueryExpr::SetTenant(ref value) => {
1440                self.check_set_tenant_privilege(value.as_deref())?;
1441                match value {
1442                    Some(id) => set_current_tenant(id.clone()),
1443                    None => clear_current_tenant(),
1444                }
1445                Ok(RuntimeQueryResult::ok_message(
1446                    query.to_string(),
1447                    &match value {
1448                        Some(id) => format!("tenant set: {id}"),
1449                        None => "tenant cleared".to_string(),
1450                    },
1451                    "set_tenant",
1452                ))
1453            }
1454            QueryExpr::ShowTenant => {
1455                let mut result = UnifiedResult::with_columns(vec!["tenant".into()]);
1456                let mut record = UnifiedRecord::new();
1457                record.set(
1458                    "tenant",
1459                    current_tenant().map(Value::text).unwrap_or(Value::Null),
1460                );
1461                result.push(record);
1462                Ok(RuntimeQueryResult {
1463                    query: query.to_string(),
1464                    mode,
1465                    statement: "show_tenant",
1466                    engine: "runtime-tenant",
1467                    result,
1468                    affected_rows: 0,
1469                    statement_type: "select",
1470                    bookmark: None,
1471                    notice: None,
1472                })
1473            }
1474            // Transaction control (Phase 2.3 PG parity).
1475            //
1476            // BEGIN allocates a real `Xid` and stores a `TxnContext` keyed by
1477            // the current connection's id. COMMIT/ROLLBACK release it through
1478            // the `SnapshotManager` so future snapshots see the correct set of
1479            // active/aborted transactions.
1480            //
1481            // Tuple stamping (xmin/xmax) and read-path visibility filtering
1482            // land in Phase 2.3.2 — this dispatch only manages the snapshot
1483            // registry. Statements running outside a TxnContext still behave
1484            // as autocommit (xid=0 → visible to every snapshot).
1485            QueryExpr::TransactionControl(ref ctl) => {
1486                use crate::storage::transaction::IsolationLevel;
1487                use reddb_rql::ast::TxnControl;
1488
1489                // Phase 2.3 keys transactions by a thread-local connection id.
1490                // The stdio/gRPC paths wire a real per-connection id later;
1491                // for embedded use (one RedDBRuntime per process-ish caller)
1492                // we fall back to a deterministic placeholder.
1493                let conn_id = current_connection_id();
1494
1495                let (kind, msg) = match ctl {
1496                    TxnControl::Begin(requested_isolation) => {
1497                        let store = self.inner.db.store();
1498                        let _publication = store.vault_publication_lock.lock();
1499                        if self.inner.transaction_state.in_transaction(conn_id) {
1500                            return Err(RedDBError::Query("transaction already active".into()));
1501                        }
1502                        let isolation = requested_isolation
1503                            .map(IsolationLevel::from)
1504                            .unwrap_or(IsolationLevel::SnapshotIsolation);
1505                        let xid = self.inner.transaction_state.begin(conn_id, isolation);
1506                        ("begin", format!("BEGIN — xid={xid} (snapshot isolation)"))
1507                    }
1508                    TxnControl::Commit => {
1509                        let has_vault_writes = self
1510                            .inner
1511                            .pending_vault_writes
1512                            .read()
1513                            .get(&conn_id)
1514                            .is_some_and(|writes| !writes.is_empty());
1515                        let store = self.inner.db.store();
1516                        let has_graph_contracts = self
1517                            .db()
1518                            .collection_contracts()
1519                            .iter()
1520                            .any(|contract| contract.graph_contract.is_some());
1521                        let _vault_guard = (has_vault_writes || has_graph_contracts)
1522                            .then(|| store.vault_publication_lock.lock());
1523                        if has_graph_contracts && self.current_xid().is_some() {
1524                            if let Err(error) = self.validate_graph_contracts_at_commit() {
1525                                self.rollback_connection(conn_id)?;
1526                                return Err(error);
1527                            }
1528                        }
1529                        let context = self.inner.transaction_state.commit(conn_id, |ctx| {
1530                            let mut own_xids = std::collections::HashSet::new();
1531                            own_xids.insert(ctx.xid);
1532                            for (_, sub) in &ctx.savepoints {
1533                                own_xids.insert(*sub);
1534                            }
1535                            for sub in &ctx.released_sub_xids {
1536                                own_xids.insert(*sub);
1537                            }
1538                            if let Err(err) = self.check_table_row_write_conflicts(
1539                                conn_id,
1540                                &ctx.snapshot,
1541                                &own_xids,
1542                                ctx.isolation,
1543                            ) {
1544                                let undo = self.revive_pending_versioned_updates(conn_id);
1545                                self.revive_pending_tombstones(conn_id);
1546                                self.discard_pending_kv_watch_events(conn_id);
1547                                self.discard_pending_queue_wakes(conn_id);
1548                                self.discard_pending_store_wal_actions(conn_id);
1549                                self.release_pending_claim_locks(conn_id);
1550                                undo?;
1551                                return Err(err);
1552                            }
1553                            if let Err(err) = self.check_queue_dedup_write_conflicts(
1554                                conn_id,
1555                                &ctx.snapshot,
1556                                &own_xids,
1557                            ) {
1558                                let undo = self.revive_pending_versioned_updates(conn_id);
1559                                self.revive_pending_tombstones(conn_id);
1560                                self.discard_pending_queue_dedup(conn_id);
1561                                self.discard_pending_kv_watch_events(conn_id);
1562                                self.discard_pending_queue_wakes(conn_id);
1563                                self.discard_pending_store_wal_actions(conn_id);
1564                                self.release_pending_claim_locks(conn_id);
1565                                undo?;
1566                                return Err(err);
1567                            }
1568                            if let Err(err) = self.prepare_pending_vault_writes(conn_id, ctx) {
1569                                let undo = self.revive_pending_versioned_updates(conn_id);
1570                                self.revive_pending_tombstones(conn_id);
1571                                self.discard_pending_queue_dedup(conn_id);
1572                                self.discard_pending_kv_watch_events(conn_id);
1573                                self.discard_pending_queue_wakes(conn_id);
1574                                self.discard_pending_store_wal_actions(conn_id);
1575                                self.release_pending_claim_locks(conn_id);
1576                                undo?;
1577                                return Err(err);
1578                            }
1579                            // Validate before taking the publication fence:
1580                            // conflict rollback can acquire index topology.
1581                            // Retain the fence through WAL and visibility so a
1582                            // checkpoint cannot discard a durable commit's WAL.
1583                            let publication = store.vault_publication_lock.lock();
1584                            self.restore_pending_write_stamps(conn_id);
1585                            if let Err(err) = self.flush_pending_store_wal_actions(conn_id) {
1586                                drop(publication);
1587                                let undo = self.revive_pending_versioned_updates(conn_id);
1588                                self.revive_pending_tombstones(conn_id);
1589                                self.discard_pending_queue_dedup(conn_id);
1590                                self.discard_pending_kv_watch_events(conn_id);
1591                                self.discard_pending_queue_wakes(conn_id);
1592                                self.release_pending_claim_locks(conn_id);
1593                                undo?;
1594                                return Err(err);
1595                            }
1596                            #[cfg(test)]
1597                            self.index_store_ref().mutation_test_hook(
1598                                "",
1599                                super::index_store::MutationTestPhase::TransactionWalCommitted,
1600                            );
1601                            Ok(publication)
1602                        });
1603                        if context.is_err() {
1604                            self.discard_pending_vault_writes(conn_id)?;
1605                        }
1606                        let context = context?;
1607                        match context {
1608                            Some(ctx) => {
1609                                self.finalize_pending_vault_writes(conn_id);
1610                                self.finalize_pending_versioned_updates(conn_id);
1611                                self.finalize_pending_tombstones(conn_id);
1612                                self.finalize_pending_queue_dedup(conn_id);
1613                                self.finalize_pending_kv_watch_events(conn_id);
1614                                self.finalize_pending_queue_wakes(conn_id);
1615                                self.release_pending_claim_locks(conn_id);
1616                                self.recover_transactional_replication().map_err(|error| {
1617                                    RedDBError::Internal(format!(
1618                                        "commit is locally durable; replication publication is pending: {error}"
1619                                    ))
1620                                })?;
1621                                ("commit", format!("COMMIT — xid={} committed", ctx.xid))
1622                            }
1623                            None => (
1624                                "commit",
1625                                "COMMIT outside transaction — no-op (autocommit)".to_string(),
1626                            ),
1627                        }
1628                    }
1629                    TxnControl::Rollback => match self.rollback_connection(conn_id)? {
1630                        Some(ctx) => ("rollback", format!("ROLLBACK — xid={} aborted", ctx.xid)),
1631                        None => (
1632                            "rollback",
1633                            "ROLLBACK outside transaction — no-op (autocommit)".to_string(),
1634                        ),
1635                    },
1636                    // Phase 2.3.2e: savepoints map onto sub-xids. Each
1637                    // SAVEPOINT allocates a fresh xid and pushes it
1638                    // onto the per-txn stack so subsequent writes can
1639                    // be selectively rolled back. RELEASE pops without
1640                    // aborting; ROLLBACK TO aborts the sub-xid (and
1641                    // any nested ones) + revives their tombstones.
1642                    TxnControl::Savepoint(name) => {
1643                        match self.inner.transaction_state.savepoint(conn_id, name) {
1644                            Some(sub) => ("savepoint", format!("SAVEPOINT {name} — sub_xid={sub}")),
1645                            None => (
1646                                "savepoint",
1647                                "SAVEPOINT outside transaction — no-op".to_string(),
1648                            ),
1649                        }
1650                    }
1651                    TxnControl::ReleaseSavepoint(name) => {
1652                        match self
1653                            .inner
1654                            .transaction_state
1655                            .release_savepoint(conn_id, name)?
1656                        {
1657                            Some(released) => (
1658                                "release_savepoint",
1659                                format!("RELEASE SAVEPOINT {name} — {released} level(s)"),
1660                            ),
1661                            None => (
1662                                "release_savepoint",
1663                                "RELEASE outside transaction — no-op".to_string(),
1664                            ),
1665                        }
1666                    }
1667                    TxnControl::RollbackToSavepoint(name) => {
1668                        match self
1669                            .inner
1670                            .transaction_state
1671                            .rollback_to_savepoint_with(conn_id, name, |rollback| {
1672                                self.rollback_vault_savepoint(conn_id, rollback.savepoint_xid);
1673                                let reverted_updates = self.revive_versioned_updates_since(
1674                                    conn_id,
1675                                    rollback.savepoint_xid,
1676                                );
1677                                let revived =
1678                                    self.revive_tombstones_since(conn_id, rollback.savepoint_xid);
1679                                reverted_updates.map(|updates| (updates, revived))
1680                            })?
1681                        {
1682                            Some((rollback, (reverted_updates, revived))) => {
1683                                (
1684                                    "rollback_to_savepoint",
1685                                    format!(
1686                                        "ROLLBACK TO SAVEPOINT {name} — aborted {} sub_xid(s), reverted {reverted_updates} update(s), revived {revived} tombstone(s)",
1687                                        rollback.aborted_xids.len(),
1688                                    ),
1689                                )
1690                            }
1691                            None => (
1692                                "rollback_to_savepoint",
1693                                "ROLLBACK TO outside transaction — no-op".to_string(),
1694                            ),
1695                        }
1696                    }
1697                };
1698                Ok(RuntimeQueryResult::ok_message(
1699                    query.to_string(),
1700                    &msg,
1701                    kind,
1702                ))
1703            }
1704            // Schema + Sequence DDL (Phase 1.3 PG parity).
1705            //
1706            // Schemas are lightweight logical namespaces: a CREATE SCHEMA call
1707            // just registers the name in `red.config` under `schema.{name}`.
1708            // Table lookups still happen by collection name; clients using
1709            // `schema.table` qualified names collapse to collection `schema.table`.
1710            //
1711            // Sequences persist a 64-bit counter + metadata (start, increment)
1712            // in `red.config` under `sequence.{name}.*`. Scalar callers
1713            // `nextval('name')` / `currval('name')` arrive with the MVCC phase
1714            // once we have a proper mutating-function dispatch path; for now the
1715            // DDL just establishes the catalog entry so clients don't error.
1716            QueryExpr::CreateSchema(ref q) => {
1717                let store = self.inner.db.store();
1718                let key = format!("schema.{}", q.name);
1719                if store.get_config(&key).is_some() {
1720                    if q.if_not_exists {
1721                        return Ok(RuntimeQueryResult::ok_message(
1722                            query.to_string(),
1723                            &format!("schema {} already exists — skipped", q.name),
1724                            "create_schema",
1725                        ));
1726                    }
1727                    return Err(RedDBError::Internal(format!(
1728                        "schema {} already exists",
1729                        q.name
1730                    )));
1731                }
1732                store.set_config_tree(&key, &crate::serde_json::Value::Bool(true));
1733                Ok(RuntimeQueryResult::ok_message(
1734                    query.to_string(),
1735                    &format!("schema {} created", q.name),
1736                    "create_schema",
1737                ))
1738            }
1739            QueryExpr::DropSchema(ref q) => {
1740                let store = self.inner.db.store();
1741                let key = format!("schema.{}", q.name);
1742                let existed = store.get_config(&key).is_some();
1743                if !existed && !q.if_exists {
1744                    return Err(RedDBError::Internal(format!(
1745                        "schema {} does not exist",
1746                        q.name
1747                    )));
1748                }
1749                // Remove marker from red.config via set to null.
1750                store.set_config_tree(&key, &crate::serde_json::Value::Null);
1751                let suffix = if q.cascade {
1752                    " (CASCADE accepted — tables untouched)"
1753                } else {
1754                    ""
1755                };
1756                Ok(RuntimeQueryResult::ok_message(
1757                    query.to_string(),
1758                    &format!("schema {} dropped{}", q.name, suffix),
1759                    "drop_schema",
1760                ))
1761            }
1762            QueryExpr::CreateSequence(ref q) => {
1763                let store = self.inner.db.store();
1764                let base = format!("sequence.{}", q.name);
1765                let start_key = format!("{base}.start");
1766                let incr_key = format!("{base}.increment");
1767                let curr_key = format!("{base}.current");
1768                if store.get_config(&start_key).is_some() {
1769                    if q.if_not_exists {
1770                        return Ok(RuntimeQueryResult::ok_message(
1771                            query.to_string(),
1772                            &format!("sequence {} already exists — skipped", q.name),
1773                            "create_sequence",
1774                        ));
1775                    }
1776                    return Err(RedDBError::Internal(format!(
1777                        "sequence {} already exists",
1778                        q.name
1779                    )));
1780                }
1781                // Persist start + increment, and set current so the first
1782                // nextval returns `start`.
1783                let initial_current = q.start - q.increment;
1784                store.set_config_tree(
1785                    &start_key,
1786                    &crate::serde_json::Value::Number(q.start as f64),
1787                );
1788                store.set_config_tree(
1789                    &incr_key,
1790                    &crate::serde_json::Value::Number(q.increment as f64),
1791                );
1792                store.set_config_tree(
1793                    &curr_key,
1794                    &crate::serde_json::Value::Number(initial_current as f64),
1795                );
1796                Ok(RuntimeQueryResult::ok_message(
1797                    query.to_string(),
1798                    &format!(
1799                        "sequence {} created (start={}, increment={})",
1800                        q.name, q.start, q.increment
1801                    ),
1802                    "create_sequence",
1803                ))
1804            }
1805            QueryExpr::DropSequence(ref q) => {
1806                let store = self.inner.db.store();
1807                let base = format!("sequence.{}", q.name);
1808                let existed = store.get_config(&format!("{base}.start")).is_some();
1809                if !existed && !q.if_exists {
1810                    return Err(RedDBError::Internal(format!(
1811                        "sequence {} does not exist",
1812                        q.name
1813                    )));
1814                }
1815                for k in ["start", "increment", "current"] {
1816                    store.set_config_tree(&format!("{base}.{k}"), &crate::serde_json::Value::Null);
1817                }
1818                Ok(RuntimeQueryResult::ok_message(
1819                    query.to_string(),
1820                    &format!("sequence {} dropped", q.name),
1821                    "drop_sequence",
1822                ))
1823            }
1824            // Views — CREATE [MATERIALIZED] VIEW (Phase 2.1 PG parity).
1825            //
1826            // The view definition is stored in-memory on RuntimeInner (not
1827            // persisted). SELECTs that reference the view name will substitute
1828            // the stored `QueryExpr` via `resolve_view_reference` during
1829            // planning (same entry point used by table-name resolution).
1830            //
1831            // Materialized views additionally allocate a slot in
1832            // `MaterializedViewCache`; a REFRESH repopulates that slot.
1833            QueryExpr::CreateView(ref q) => {
1834                let mut views = self.inner.views.write();
1835                if views.contains_key(&q.name) && !q.or_replace {
1836                    if q.if_not_exists {
1837                        return Ok(RuntimeQueryResult::ok_message(
1838                            query.to_string(),
1839                            &format!("view {} already exists — skipped", q.name),
1840                            "create_view",
1841                        ));
1842                    }
1843                    return Err(RedDBError::Internal(format!(
1844                        "view {} already exists",
1845                        q.name
1846                    )));
1847                }
1848                views.insert(q.name.clone(), Arc::new(q.clone()));
1849                drop(views);
1850
1851                // Materialized view: register cache slot (data is empty until REFRESH).
1852                if q.materialized {
1853                    use crate::storage::cache::result::{MaterializedViewDef, RefreshPolicy};
1854                    let refresh = match q.refresh_every_ms {
1855                        Some(ms) => RefreshPolicy::Periodic(std::time::Duration::from_millis(ms)),
1856                        None => RefreshPolicy::Manual,
1857                    };
1858                    let dependencies = collect_table_refs(&q.query);
1859                    let def = MaterializedViewDef {
1860                        name: q.name.clone(),
1861                        query: format!("<parsed view {}>", q.name),
1862                        dependencies: dependencies.clone(),
1863                        refresh,
1864                        retention_duration_ms: q.retention_duration_ms,
1865                    };
1866                    self.inner.materialized_views.write().register(def);
1867
1868                    // Issue #593 slice 9a — persist the descriptor to
1869                    // the system catalog so the definition survives a
1870                    // restart. Upsert semantics (delete-then-insert by
1871                    // name) keep the catalog free of duplicate rows
1872                    // across `CREATE OR REPLACE` churn.
1873                    let descriptor =
1874                        crate::runtime::continuous_materialized_view::MaterializedViewDescriptor {
1875                            name: q.name.clone(),
1876                            source_sql: query.to_string(),
1877                            source_collections: dependencies,
1878                            refresh_every_ms: q.refresh_every_ms,
1879                            retention_duration_ms: q.retention_duration_ms,
1880                        };
1881                    let store = self.inner.db.store();
1882                    crate::runtime::continuous_materialized_view::persist_descriptor(
1883                        store.as_ref(),
1884                        &descriptor,
1885                    )?;
1886
1887                    // Issue #594 slice 9b — provision a Table-shaped
1888                    // backing collection named after the view. The
1889                    // rewriter skips materialized views (see
1890                    // `rewrite_view_refs_inner`) so `SELECT FROM v`
1891                    // resolves to this collection directly. Empty
1892                    // until REFRESH wires through it in 9c.
1893                    self.ensure_materialized_view_backing(&q.name)?;
1894                }
1895                // Plan cache may have cached a plan that didn't know about this
1896                // view — invalidate so future references pick up the new binding.
1897                // Result cache gets flushed too: OR REPLACE must not serve a
1898                // prior execution of the obsolete body.
1899                self.invalidate_plan_cache();
1900                self.invalidate_result_cache();
1901
1902                Ok(RuntimeQueryResult::ok_message(
1903                    query.to_string(),
1904                    &format!(
1905                        "{}view {} created",
1906                        if q.materialized { "materialized " } else { "" },
1907                        q.name
1908                    ),
1909                    "create_view",
1910                ))
1911            }
1912            QueryExpr::DropView(ref q) => {
1913                let mut views = self.inner.views.write();
1914                let removed = views.remove(&q.name);
1915                let existed = removed.is_some();
1916                let removed_materialized =
1917                    removed.as_ref().map(|v| v.materialized).unwrap_or(false);
1918                drop(views);
1919                if q.materialized || existed {
1920                    // Try the materialised cache too — silent if absent.
1921                    self.inner.materialized_views.write().remove(&q.name);
1922                    // Issue #593 slice 9a — remove any persisted
1923                    // catalog row. Idempotent: a no-op when the view
1924                    // was never materialized (no row was ever written).
1925                    let store = self.inner.db.store();
1926                    crate::runtime::continuous_materialized_view::remove_by_name(
1927                        store.as_ref(),
1928                        &q.name,
1929                    )?;
1930                }
1931                // Issue #594 slice 9b — drop the backing collection
1932                // that was provisioned at CREATE time. Only mat views
1933                // ever had one; regular views never did.
1934                if removed_materialized || q.materialized {
1935                    self.drop_materialized_view_backing(&q.name)?;
1936                }
1937                // Drop any plan / result cache entries that baked the
1938                // view body into their QueryExpr.
1939                self.invalidate_plan_cache();
1940                self.invalidate_result_cache();
1941                if !existed && !q.if_exists {
1942                    return Err(RedDBError::Internal(format!(
1943                        "view {} does not exist",
1944                        q.name
1945                    )));
1946                }
1947                self.invalidate_plan_cache();
1948                Ok(RuntimeQueryResult::ok_message(
1949                    query.to_string(),
1950                    &format!("view {} dropped", q.name),
1951                    "drop_view",
1952                ))
1953            }
1954            QueryExpr::RefreshMaterializedView(ref q) => {
1955                // Look up the view definition, execute its underlying query,
1956                // and stash the serialized result in the materialised cache.
1957                let view = {
1958                    let views = self.inner.views.read();
1959                    views.get(&q.name).cloned()
1960                };
1961                let view = match view {
1962                    Some(v) => v,
1963                    None => {
1964                        return Err(RedDBError::Internal(format!(
1965                            "view {} does not exist",
1966                            q.name
1967                        )))
1968                    }
1969                };
1970                if !view.materialized {
1971                    return Err(RedDBError::Internal(format!(
1972                        "view {} is not materialized — REFRESH requires \
1973                         CREATE MATERIALIZED VIEW",
1974                        q.name
1975                    )));
1976                }
1977                // Execute the underlying query fresh.
1978                let started = std::time::Instant::now();
1979                let now_ms = std::time::SystemTime::now()
1980                    .duration_since(std::time::UNIX_EPOCH)
1981                    .map(|d| d.as_millis() as u64)
1982                    .unwrap_or(0);
1983                match self.execute_query_expr((*view.query).clone()) {
1984                    Ok(inner_result) => {
1985                        // Issue #595 slice 9c — atomically replace the
1986                        // backing collection's contents under a single
1987                        // WAL group. Concurrent SELECT from the view
1988                        // sees either the prior or new contents, never
1989                        // partial. A crash before the WAL commit lands
1990                        // leaves the prior contents intact on recovery.
1991                        let entities =
1992                            view_records_to_entities(&q.name, &inner_result.result.records);
1993                        let row_count = entities.len() as u64;
1994                        let store = self.inner.db.store();
1995                        let serialized_records = match store.refresh_collection(&q.name, entities) {
1996                            Ok(records) => records,
1997                            Err(err) => {
1998                                let duration_ms = started.elapsed().as_millis() as u64;
1999                                let msg = err.to_string();
2000                                self.inner
2001                                    .materialized_views
2002                                    .write()
2003                                    .record_refresh_failure(
2004                                        &q.name,
2005                                        msg.clone(),
2006                                        duration_ms,
2007                                        now_ms,
2008                                    );
2009                                return Err(RedDBError::Internal(format!(
2010                                    "REFRESH MATERIALIZED VIEW {}: {msg}",
2011                                    q.name
2012                                )));
2013                            }
2014                        };
2015
2016                        // Issue #596 slice 9d — emit a Refresh
2017                        // ChangeRecord into the logical-WAL spool so
2018                        // replicas deterministically replay the same
2019                        // backing-collection contents via
2020                        // `LogicalChangeApplier::apply_record`.
2021                        if self.inner.db.replication.is_some() {
2022                            let lsn = self.inner.cdc.emit(
2023                                crate::replication::cdc::ChangeOperation::Refresh,
2024                                &q.name,
2025                                0,
2026                                "refresh",
2027                            );
2028                            self.invalidate_result_cache_for_table(&q.name);
2029                            let timestamp = std::time::SystemTime::now()
2030                                .duration_since(std::time::UNIX_EPOCH)
2031                                .unwrap_or_default()
2032                                .as_millis() as u64;
2033                            let record = ChangeRecord::for_refresh(
2034                                lsn,
2035                                timestamp,
2036                                q.name.clone(),
2037                                serialized_records,
2038                            )
2039                            .with_term(self.current_replication_term());
2040                            self.stage_or_publish_logical_record(record)?;
2041                        }
2042
2043                        let duration_ms = started.elapsed().as_millis() as u64;
2044                        let serialized = format!("{:?}", inner_result.result);
2045                        self.inner
2046                            .materialized_views
2047                            .write()
2048                            .record_refresh_success(
2049                                &q.name,
2050                                serialized.into_bytes(),
2051                                row_count,
2052                                duration_ms,
2053                                now_ms,
2054                            );
2055                        // SELECT FROM v now reads through the rewriter
2056                        // skip into the backing collection — drop the
2057                        // result cache so prior empty-backing reads
2058                        // don't shadow the new contents.
2059                        self.invalidate_result_cache();
2060                        Ok(RuntimeQueryResult::ok_message(
2061                            query.to_string(),
2062                            &format!("materialized view {} refreshed", q.name),
2063                            "refresh_materialized_view",
2064                        ))
2065                    }
2066                    Err(err) => {
2067                        let duration_ms = started.elapsed().as_millis() as u64;
2068                        let msg = err.to_string();
2069                        self.inner
2070                            .materialized_views
2071                            .write()
2072                            .record_refresh_failure(&q.name, msg.clone(), duration_ms, now_ms);
2073                        Err(err)
2074                    }
2075                }
2076            }
2077            // Row Level Security (Phase 2.5 PG parity).
2078            //
2079            // Policies live in an in-memory registry keyed by (table, name).
2080            // Enforcement (AND-ing the policy's USING clause into every
2081            // query's WHERE for the table) arrives in Phase 2.5.2 via the
2082            // filter compiler; this dispatch only manages the catalog.
2083            QueryExpr::CreatePolicy(ref q) => {
2084                let key = (q.table.clone(), q.name.clone());
2085                self.inner
2086                    .rls_policies
2087                    .write()
2088                    .insert(key, Arc::new(q.clone()));
2089                self.invalidate_plan_cache();
2090                self.invalidate_result_cache();
2091                // Issue #120 — surface policy names in the
2092                // schema-vocabulary so AskPipeline (#121) can resolve
2093                // a policy reference back to its table.
2094                self.schema_vocabulary_apply(
2095                    crate::runtime::schema_vocabulary::DdlEvent::CreatePolicy {
2096                        collection: q.table.clone(),
2097                        policy: q.name.clone(),
2098                    },
2099                );
2100                Ok(RuntimeQueryResult::ok_message(
2101                    query.to_string(),
2102                    &format!("policy {} on {} created", q.name, q.table),
2103                    "create_policy",
2104                ))
2105            }
2106            QueryExpr::DropPolicy(ref q) => {
2107                let removed = self
2108                    .inner
2109                    .rls_policies
2110                    .write()
2111                    .remove(&(q.table.clone(), q.name.clone()))
2112                    .is_some();
2113                if !removed && !q.if_exists {
2114                    return Err(RedDBError::Internal(format!(
2115                        "policy {} on {} does not exist",
2116                        q.name, q.table
2117                    )));
2118                }
2119                self.invalidate_plan_cache();
2120                self.invalidate_result_cache();
2121                // Issue #120 — keep the schema-vocabulary policy
2122                // entry in sync.
2123                self.schema_vocabulary_apply(
2124                    crate::runtime::schema_vocabulary::DdlEvent::DropPolicy {
2125                        collection: q.table.clone(),
2126                        policy: q.name.clone(),
2127                    },
2128                );
2129                Ok(RuntimeQueryResult::ok_message(
2130                    query.to_string(),
2131                    &format!("policy {} on {} dropped", q.name, q.table),
2132                    "drop_policy",
2133                ))
2134            }
2135            // Foreign Data Wrappers (Phase 3.2 PG parity).
2136            //
2137            // CREATE SERVER / CREATE FOREIGN TABLE register into the shared
2138            // `ForeignTableRegistry`. The read path consults that registry
2139            // before dispatching a SELECT — when the table name matches a
2140            // registered foreign table, we forward the scan to the wrapper
2141            // and skip the normal collection lookup.
2142            //
2143            // Phase 3.2 is in-memory only; persistence across restarts is a
2144            // 3.2.2 follow-up that mirrors the view registry pattern.
2145            QueryExpr::CreateServer(ref q) => {
2146                use crate::storage::fdw::FdwOptions;
2147                let registry = Arc::clone(&self.inner.foreign_tables);
2148                if registry.server(&q.name).is_some() {
2149                    if q.if_not_exists {
2150                        return Ok(RuntimeQueryResult::ok_message(
2151                            query.to_string(),
2152                            &format!("server {} already exists — skipped", q.name),
2153                            "create_server",
2154                        ));
2155                    }
2156                    return Err(RedDBError::Internal(format!(
2157                        "server {} already exists",
2158                        q.name
2159                    )));
2160                }
2161                let mut opts = FdwOptions::new();
2162                for (k, v) in &q.options {
2163                    opts.values.insert(k.clone(), v.clone());
2164                }
2165                registry
2166                    .create_server(&q.name, &q.wrapper, opts)
2167                    .map_err(|e| RedDBError::Internal(e.to_string()))?;
2168                Ok(RuntimeQueryResult::ok_message(
2169                    query.to_string(),
2170                    &format!("server {} created (wrapper {})", q.name, q.wrapper),
2171                    "create_server",
2172                ))
2173            }
2174            QueryExpr::DropServer(ref q) => {
2175                let existed = self.inner.foreign_tables.drop_server(&q.name);
2176                if !existed && !q.if_exists {
2177                    return Err(RedDBError::Internal(format!(
2178                        "server {} does not exist",
2179                        q.name
2180                    )));
2181                }
2182                Ok(RuntimeQueryResult::ok_message(
2183                    query.to_string(),
2184                    &format!(
2185                        "server {} dropped{}",
2186                        q.name,
2187                        if q.cascade { " (cascade)" } else { "" }
2188                    ),
2189                    "drop_server",
2190                ))
2191            }
2192            QueryExpr::CreateForeignTable(ref q) => {
2193                use crate::storage::fdw::{FdwOptions, ForeignColumn, ForeignTable};
2194                let registry = Arc::clone(&self.inner.foreign_tables);
2195                if registry.foreign_table(&q.name).is_some() {
2196                    if q.if_not_exists {
2197                        return Ok(RuntimeQueryResult::ok_message(
2198                            query.to_string(),
2199                            &format!("foreign table {} already exists — skipped", q.name),
2200                            "create_foreign_table",
2201                        ));
2202                    }
2203                    return Err(RedDBError::Internal(format!(
2204                        "foreign table {} already exists",
2205                        q.name
2206                    )));
2207                }
2208                let mut opts = FdwOptions::new();
2209                for (k, v) in &q.options {
2210                    opts.values.insert(k.clone(), v.clone());
2211                }
2212                let columns: Vec<ForeignColumn> = q
2213                    .columns
2214                    .iter()
2215                    .map(|c| ForeignColumn {
2216                        name: c.name.clone(),
2217                        data_type: c.data_type.clone(),
2218                        not_null: c.not_null,
2219                    })
2220                    .collect();
2221                registry
2222                    .create_foreign_table(ForeignTable {
2223                        name: q.name.clone(),
2224                        server_name: q.server.clone(),
2225                        columns,
2226                        options: opts,
2227                    })
2228                    .map_err(|e| RedDBError::Internal(e.to_string()))?;
2229                self.invalidate_plan_cache();
2230                Ok(RuntimeQueryResult::ok_message(
2231                    query.to_string(),
2232                    &format!("foreign table {} created (server {})", q.name, q.server),
2233                    "create_foreign_table",
2234                ))
2235            }
2236            QueryExpr::DropForeignTable(ref q) => {
2237                let existed = self.inner.foreign_tables.drop_foreign_table(&q.name);
2238                if !existed && !q.if_exists {
2239                    return Err(RedDBError::Internal(format!(
2240                        "foreign table {} does not exist",
2241                        q.name
2242                    )));
2243                }
2244                self.invalidate_plan_cache();
2245                Ok(RuntimeQueryResult::ok_message(
2246                    query.to_string(),
2247                    &format!("foreign table {} dropped", q.name),
2248                    "drop_foreign_table",
2249                ))
2250            }
2251            // COPY table FROM 'path' (Phase 1.5 PG parity).
2252            //
2253            // Stream CSV rows through the shared `CsvImporter`. The collection
2254            // is auto-created on first insert (via `insert_auto`-style path);
2255            // VACUUM/ANALYZE afterwards is up to the caller.
2256            QueryExpr::CopyFrom(ref q) => {
2257                use crate::storage::import::{CsvConfig, CsvImporter};
2258                self.check_copy_from_privilege(&q.table)?;
2259                confine_copy_from_path(&q.path)?;
2260                let store = self.inner.db.store();
2261                let cfg = CsvConfig {
2262                    collection: q.table.clone(),
2263                    has_header: q.has_header,
2264                    delimiter: q.delimiter.map(|c| c as u8).unwrap_or(b','),
2265                    ..CsvConfig::default()
2266                };
2267                let importer = CsvImporter::new(cfg);
2268                let stats = importer
2269                    .import_file(&q.path, store.as_ref())
2270                    .map_err(|e| RedDBError::Internal(format!("COPY failed: {e}")))?;
2271                // Tables are written → invalidate cached plans / result cache.
2272                self.note_table_write(&q.table);
2273                Ok(RuntimeQueryResult::ok_message(
2274                    query.to_string(),
2275                    &format!(
2276                        "COPY imported {} rows into {} ({} errors skipped, {}ms)",
2277                        stats.records_imported, q.table, stats.errors_skipped, stats.duration_ms
2278                    ),
2279                    "copy_from",
2280                ))
2281            }
2282            // Maintenance commands (Phase 1.2 PG parity).
2283            //
2284            // - VACUUM [FULL] [table]: refreshes planner stats for the target
2285            //   collection(s) and — when FULL — triggers a full pager persist
2286            //   (flushes dirty pages + fsync). Also invalidates the result cache
2287            //   so subsequent reads re-execute against the freshly compacted
2288            //   storage. RedDB's segment/btree GC runs continuously via the
2289            //   background lifecycle; explicit space reclamation for sealed
2290            //   segments arrives with Phase 2.3 (MVCC + dead-tuple reclamation).
2291            // - ANALYZE [table]: reruns `analyze_collection` +
2292            //   `persist_table_stats` via `refresh_table_planner_stats` so the
2293            //   planner has fresh histograms, distinct estimates, null counts.
2294            //
2295            // Both commands accept an optional target; omitting the target
2296            // iterates every collection in the store.
2297            QueryExpr::MaintenanceCommand(ref cmd) => {
2298                use reddb_rql::ast::MaintenanceCommand as Mc;
2299                let store = self.inner.db.store();
2300                let (kind, msg) = match cmd {
2301                    Mc::Analyze { target } => {
2302                        let targets: Vec<String> = match target {
2303                            Some(t) => vec![t.clone()],
2304                            None => store.list_collections(),
2305                        };
2306                        for t in &targets {
2307                            self.refresh_table_planner_stats(t);
2308                        }
2309                        (
2310                            "analyze",
2311                            format!("ANALYZE refreshed stats for {} table(s)", targets.len()),
2312                        )
2313                    }
2314                    Mc::Vacuum { target, full } => {
2315                        let targets: Vec<String> = match target {
2316                            Some(t) => vec![t.clone()],
2317                            None => store.list_collections(),
2318                        };
2319                        let mut vacuum_stats =
2320                            crate::storage::unified::store::MvccVacuumStats::default();
2321                        for t in &targets {
2322                            let cutoff_xid = self.mvcc_vacuum_cutoff_xid_for(t)?;
2323                            let stats = store.vacuum_mvcc_history(t, cutoff_xid).map_err(|e| {
2324                                RedDBError::Internal(format!(
2325                                    "VACUUM MVCC history failed for {t}: {e}"
2326                                ))
2327                            })?;
2328                            if stats.reclaimed_versions > 0 {
2329                                self.rebuild_runtime_indexes_for_table(t)?;
2330                            }
2331                            vacuum_stats.add(&stats);
2332                        }
2333                        // The cutoff protects snapshots, not physical references.
2334                        // Aborted inserts can remain in this or another collection;
2335                        // forgetting their outcome would make them visible again.
2336                        // Stats refresh covers every target (same as ANALYZE).
2337                        for t in &targets {
2338                            self.refresh_table_planner_stats(t);
2339                        }
2340                        // FULL forces a pager persist (dirty-page flush + fsync).
2341                        // Regular VACUUM relies on the background writer / segment
2342                        // lifecycle so the command is non-blocking.
2343                        let persisted = if *full {
2344                            match store.persist() {
2345                                Ok(()) => true,
2346                                Err(e) => {
2347                                    return Err(RedDBError::Internal(format!(
2348                                        "VACUUM FULL persist failed: {e:?}"
2349                                    )));
2350                                }
2351                            }
2352                        } else {
2353                            false
2354                        };
2355                        // Result cache depended on pre-vacuum state.
2356                        self.invalidate_result_cache();
2357                        (
2358                            "vacuum",
2359                            format!(
2360                                "VACUUM{} processed {} table(s): scanned_versions={}, retained_versions={}, reclaimed_versions={}, retained_history_versions={}, reclaimed_history_versions={}, retained_tombstones={}, reclaimed_tombstones={}{}",
2361                                if *full { " FULL" } else { "" },
2362                                targets.len(),
2363                                vacuum_stats.scanned_versions,
2364                                vacuum_stats.retained_versions,
2365                                vacuum_stats.reclaimed_versions,
2366                                vacuum_stats.retained_history_versions,
2367                                vacuum_stats.reclaimed_history_versions,
2368                                vacuum_stats.retained_tombstones,
2369                                vacuum_stats.reclaimed_tombstones,
2370                                if persisted {
2371                                    " (pages flushed to disk)"
2372                                } else {
2373                                    ""
2374                                }
2375                            ),
2376                        )
2377                    }
2378                };
2379                Ok(RuntimeQueryResult::ok_message(
2380                    query.to_string(),
2381                    &msg,
2382                    kind,
2383                ))
2384            }
2385            // GRANT / REVOKE / ALTER USER (RBAC milestone).
2386            //
2387            // These hit the AuthStore directly. The statement frame /
2388            // privilege gate has already decided whether the caller may
2389            // even run the statement; here we just translate the AST into
2390            // AuthStore calls.
2391            QueryExpr::Grant(ref g) => self.execute_grant_statement(query, g),
2392            QueryExpr::Revoke(ref r) => self.execute_revoke_statement(query, r),
2393            QueryExpr::AlterUser(ref a) => self.execute_alter_user_statement(query, a),
2394            QueryExpr::CreateUser(ref u) => self.execute_create_user_statement(query, u),
2395            QueryExpr::CreateIamPolicy { ref id, ref json } => {
2396                self.execute_create_iam_policy(query, id, json)
2397            }
2398            QueryExpr::DropIamPolicy { ref id } => self.execute_drop_iam_policy(query, id),
2399            QueryExpr::AttachPolicy {
2400                ref policy_id,
2401                ref principal,
2402            } => self.execute_attach_policy(query, policy_id, principal),
2403            QueryExpr::DetachPolicy {
2404                ref policy_id,
2405                ref principal,
2406            } => self.execute_detach_policy(query, policy_id, principal),
2407            QueryExpr::ShowPolicies { ref filter } => {
2408                self.execute_show_policies(query, filter.as_ref())
2409            }
2410            QueryExpr::ShowEffectivePermissions {
2411                ref user,
2412                ref resource,
2413            } => self.execute_show_effective_permissions(query, user, resource.as_ref()),
2414            QueryExpr::SimulatePolicy {
2415                ref user,
2416                ref action,
2417                ref resource,
2418            } => self.execute_simulate_policy(query, user, action, resource),
2419            QueryExpr::LintPolicy { ref source } => self.execute_lint_policy(query, source),
2420            QueryExpr::MigratePolicyMode {
2421                ref target,
2422                dry_run,
2423            } => self.execute_migrate_policy_mode(query, target, dry_run),
2424            QueryExpr::CreateMigration(ref q) => self.execute_create_migration(query, q),
2425            QueryExpr::ApplyMigration(ref q) => self.execute_apply_migration(query, q),
2426            QueryExpr::RollbackMigration(ref q) => self.execute_rollback_migration(query, q),
2427            QueryExpr::ExplainMigration(ref q) => self.execute_explain_migration(query, q),
2428            _ => Err(RedDBError::Query(
2429                "unsupported command in runtime dispatcher".to_string(),
2430            )),
2431        };
2432
2433        if _query_budget.is_some() {
2434            super::query_budget::charge(0)?;
2435        }
2436        if !control_event_specs.is_empty() {
2437            let (outcome, reason) = match &query_result {
2438                Ok(_) => (crate::runtime::control_events::Outcome::Allowed, None),
2439                Err(err) => (control_event_outcome_for_error(err), Some(err.to_string())),
2440            };
2441            for spec in &control_event_specs {
2442                self.emit_control_event(
2443                    spec.kind,
2444                    outcome,
2445                    spec.action,
2446                    spec.resource.clone(),
2447                    reason.clone(),
2448                    spec.fields.clone(),
2449                )?;
2450            }
2451        }
2452
2453        if let (Some(plan), Ok(result)) = (&query_audit_plan, &query_result) {
2454            self.emit_query_audit(
2455                query,
2456                plan,
2457                query_audit_started.elapsed().as_millis() as u64,
2458                result,
2459            );
2460        }
2461
2462        // Cache SELECT results for 30s.
2463        // Skip: pre-serialized JSON (large clone), and result sets > 5 rows.
2464        // Large multi-row results (range scans, filtered scans) are rarely
2465        // repeated with the same literal values so the cache hit rate is near
2466        // zero while the clone cost (100 records × ~16 fields each) is high.
2467        // Aggregations (1 row) and point lookups (1 row) still benefit.
2468        if let Ok(ref result) = query_result {
2469            frame.write_result_cache(self, result, result_cache_scopes);
2470        }
2471
2472        query_result
2473    }
2474
2475    /// Execute a pre-parsed `QueryExpr` that has no accompanying SQL text,
2476    /// bypassing SQL parsing and the plan cache.
2477    ///
2478    /// Prefer [`Self::execute_prepared_query`] or
2479    /// [`Self::execute_query_with_params`]: they carry the statement text, so
2480    /// the frame's snapshot (including `AS OF`), coarse privilege class, lock
2481    /// intent, and result-cache key all describe the statement that actually
2482    /// runs. This entry exists for the nested in-statement callers — the CTE
2483    /// prelude, materialized-view refresh, and the inline graph TVF — which
2484    /// hold an expression the outer statement already parsed.
2485    ///
2486    /// Cost: this is no longer a "zero overhead" path. It builds and installs
2487    /// a full `StatementExecutionFrame` (tenant / config / secret / KV guards
2488    /// plus an MVCC snapshot), which is what buys it the same snapshot
2489    /// isolation as textual SQL. Nested calls inherit the enclosing
2490    /// statement's snapshot rather than minting a new one, and the frame opts
2491    /// out of the result cache because there is no stable text key.
2492    ///
2493    /// Keeps secret SELECT results masked, identical to `execute_query`.
2494    pub fn execute_query_expr(&self, expr: QueryExpr) -> RedDBResult<RuntimeQueryResult> {
2495        let frame = super::statement_frame::StatementExecutionFrame::build(
2496            self,
2497            super::statement_frame::StatementIdentity::Expr(&expr),
2498        )?;
2499        let _frame_guards = Box::new(frame.install(self));
2500        // View rewrite (Phase 2.1): substitute any `QueryExpr::Table(tq)`
2501        // whose `tq.table` matches a registered view with the view's
2502        // underlying query. Safe to call even when no views are registered.
2503        let expr = self.rewrite_view_refs(expr);
2504
2505        self.validate_model_operations_before_auth(&expr)?;
2506        // Granular RBAC privilege check. Runs before dispatch so a
2507        // denied caller never reaches storage. Fail-closed: any error
2508        // resolving the action / resource produces PermissionDenied.
2509        if let Err(err) = self.check_query_privilege(&expr) {
2510            return Err(RedDBError::Query(format!("permission denied: {err}")));
2511        }
2512
2513        frame.release_snapshot_for_maintenance(&expr);
2514        let statement = query_expr_name(&expr);
2515        let mode = detect_mode(statement);
2516        let query_str = statement;
2517
2518        self.dispatch_expr(expr, query_str, mode)
2519    }
2520
2521    pub(super) fn validate_model_operations_before_auth(
2522        &self,
2523        expr: &QueryExpr,
2524    ) -> RedDBResult<()> {
2525        self.validate_vault_table_access(expr)?;
2526        use crate::catalog::CollectionModel;
2527        use crate::runtime::ddl::polymorphic_resolver;
2528        use reddb_rql::ast::KvCommand;
2529
2530        let system_schema_target = match expr {
2531            QueryExpr::DropTable(q) => Some(q.name.as_str()),
2532            QueryExpr::DropGraph(q) => Some(q.name.as_str()),
2533            QueryExpr::DropVector(q) => Some(q.name.as_str()),
2534            QueryExpr::DropDocument(q) => Some(q.name.as_str()),
2535            QueryExpr::DropKv(q) => Some(q.name.as_str()),
2536            QueryExpr::DropCollection(q) => Some(q.name.as_str()),
2537            QueryExpr::Truncate(q) => Some(q.name.as_str()),
2538            _ => None,
2539        };
2540        if system_schema_target.is_some_and(crate::runtime::impl_ddl::is_system_schema_name) {
2541            return Err(RedDBError::Query("system schema is read-only".to_string()));
2542        }
2543
2544        let expected = match expr {
2545            QueryExpr::DropTable(q) => Some((q.name.as_str(), CollectionModel::Table)),
2546            QueryExpr::DropGraph(q) => Some((q.name.as_str(), CollectionModel::Graph)),
2547            QueryExpr::DropVector(q) => Some((q.name.as_str(), CollectionModel::Vector)),
2548            QueryExpr::DropDocument(q) => Some((q.name.as_str(), CollectionModel::Document)),
2549            QueryExpr::DropKv(q) => Some((q.name.as_str(), q.model)),
2550            QueryExpr::DropCollection(q) => q.model.map(|model| (q.name.as_str(), model)),
2551            QueryExpr::Truncate(q) => q.model.map(|model| (q.name.as_str(), model)),
2552            QueryExpr::KvCommand(cmd) => {
2553                let (collection, model) = match cmd {
2554                    KvCommand::Put {
2555                        collection, model, ..
2556                    }
2557                    | KvCommand::Get {
2558                        collection, model, ..
2559                    }
2560                    | KvCommand::Incr {
2561                        collection, model, ..
2562                    }
2563                    | KvCommand::Cas {
2564                        collection, model, ..
2565                    }
2566                    | KvCommand::List {
2567                        collection, model, ..
2568                    }
2569                    | KvCommand::Delete {
2570                        collection, model, ..
2571                    } => (collection.as_str(), *model),
2572                    KvCommand::Rotate { collection, .. }
2573                    | KvCommand::History { collection, .. }
2574                    | KvCommand::Purge { collection, .. } => {
2575                        (collection.as_str(), CollectionModel::Vault)
2576                    }
2577                    KvCommand::InvalidateTags { collection, .. } => {
2578                        (collection.as_str(), CollectionModel::Kv)
2579                    }
2580                    KvCommand::Watch {
2581                        collection, model, ..
2582                    } => (collection.as_str(), *model),
2583                    KvCommand::Reveal { collection, .. } => {
2584                        (collection.as_str(), CollectionModel::Vault)
2585                    }
2586                };
2587                Some((collection, model))
2588            }
2589            QueryExpr::ConfigCommand(cmd) => {
2590                self.validate_config_command_before_auth(cmd)?;
2591                None
2592            }
2593            _ => None,
2594        };
2595
2596        let Some((name, expected_model)) = expected else {
2597            return Ok(());
2598        };
2599        // Declared models are authoritative in the catalog snapshot. Resolve
2600        // just this contract instead of observing every row in every collection
2601        // for a point command. Keep the snapshot fallback for undeclared legacy
2602        // collections and orphaned contracts, preserving their inference rules.
2603        if let Some(contract) = self.inner.db.collection_contract_arc(name) {
2604            if self.inner.db.store().get_collection(name).is_some() {
2605                return polymorphic_resolver::ensure_model_match(
2606                    expected_model,
2607                    contract.declared_model,
2608                );
2609            }
2610        }
2611        let snapshot = self.inner.db.catalog_model_snapshot();
2612        let Some(actual_model) = snapshot
2613            .collections
2614            .iter()
2615            .find(|collection| collection.name == name)
2616            .map(|collection| collection.declared_model.unwrap_or(collection.model))
2617        else {
2618            return Ok(());
2619        };
2620        polymorphic_resolver::ensure_model_match(expected_model, actual_model)
2621    }
2622
2623    /// Walk a `QueryExpr` and replace `QueryExpr::Table(tq)` nodes whose
2624    /// `tq.table` matches a registered view name with the view's stored
2625    /// body. Recurses through joins so `SELECT ... FROM t JOIN myview ...`
2626    /// resolves correctly. Pure operation — no side effects.
2627    pub(super) fn rewrite_view_refs(&self, expr: QueryExpr) -> QueryExpr {
2628        // Fast path: no views registered → return original expression.
2629        if self.inner.views.read().is_empty() {
2630            return expr;
2631        }
2632        self.rewrite_view_refs_inner(expr)
2633    }
2634
2635    fn rewrite_view_refs_inner(&self, expr: QueryExpr) -> QueryExpr {
2636        use reddb_rql::ast::{Filter, TableSource};
2637        match expr {
2638            QueryExpr::Table(mut tq) => {
2639                // 1. If the TableSource is a subquery, recurse into it so
2640                //    `SELECT ... FROM (SELECT ... FROM myview) t` expands.
2641                //    The legacy `table` field (set to a synthetic
2642                //    "__subq_NNNN" sentinel) stays as-is so callers that
2643                //    read it keep compiling.
2644                if let Some(TableSource::Subquery(body)) = tq.source.take() {
2645                    tq.source = Some(TableSource::Subquery(Box::new(
2646                        self.rewrite_view_refs_inner(*body),
2647                    )));
2648                    return QueryExpr::Table(tq);
2649                }
2650
2651                // 2. Restore the source field (took it above for match).
2652                // When the source was `None` or `TableSource::Name(_)`, the
2653                // real lookup key is `tq.table` — check the view registry.
2654                let maybe_view = {
2655                    let views = self.inner.views.read();
2656                    views.get(&tq.table).cloned()
2657                };
2658                let Some(view) = maybe_view else {
2659                    return QueryExpr::Table(tq);
2660                };
2661
2662                // Issue #594 slice 9b — materialized views are read
2663                // from their backing collection, not by substituting
2664                // the body. Returning the TableQuery as-is lets the
2665                // normal table-read path resolve `SELECT FROM v`
2666                // against the collection provisioned at CREATE time.
2667                if view.materialized {
2668                    return QueryExpr::Table(tq);
2669                }
2670
2671                // Recurse into the view body — views may reference other
2672                // views. The recursion yields the final QueryExpr we need
2673                // to merge the outer's filter / limit / offset into.
2674                let inner_expr = self.rewrite_view_refs_inner((*view.query).clone());
2675
2676                // Phase 5: when the body is a Table we merge the outer
2677                // TableQuery's WHERE / LIMIT / OFFSET into it so stacked
2678                // views filter recursively. Non-table bodies (Search,
2679                // Ask, Vector, Graph, Hybrid) can't meaningfully combine
2680                // with an outer Table query today — return the body
2681                // verbatim; outer predicates are lost. Full projection
2682                // merge lands in Phase 5.2.
2683                match inner_expr {
2684                    QueryExpr::Table(mut inner_tq) => {
2685                        if let Some(outer_filter) = tq.filter.take() {
2686                            inner_tq.filter = Some(match inner_tq.filter.take() {
2687                                Some(existing) => {
2688                                    Filter::And(Box::new(existing), Box::new(outer_filter))
2689                                }
2690                                None => outer_filter,
2691                            });
2692                            // Keep the `Expr` form in lock-step with the
2693                            // merged `Filter`. The executor prefers
2694                            // `where_expr` and nulls `filter` when it is
2695                            // present (see `execute_query_inner`), so a
2696                            // stacked view whose outer predicate was only
2697                            // merged into `filter` would silently drop that
2698                            // predicate at eval time (#635).
2699                            inner_tq.where_expr = inner_tq
2700                                .filter
2701                                .as_ref()
2702                                .map(reddb_rql::sql_lowering::filter_to_expr);
2703                        }
2704                        if let Some(outer_limit) = tq.limit {
2705                            inner_tq.limit = Some(match inner_tq.limit {
2706                                Some(existing) => existing.min(outer_limit),
2707                                None => outer_limit,
2708                            });
2709                        }
2710                        if let Some(outer_offset) = tq.offset {
2711                            inner_tq.offset = Some(match inner_tq.offset {
2712                                Some(existing) => existing + outer_offset,
2713                                None => outer_offset,
2714                            });
2715                        }
2716                        QueryExpr::Table(inner_tq)
2717                    }
2718                    other => other,
2719                }
2720            }
2721            QueryExpr::Join(mut jq) => {
2722                jq.left = Box::new(self.rewrite_view_refs_inner(*jq.left));
2723                jq.right = Box::new(self.rewrite_view_refs_inner(*jq.right));
2724                QueryExpr::Join(jq)
2725            }
2726            // Other variants don't carry nested QueryExpr that can reference
2727            // a view by table name. Return as-is.
2728            other => other,
2729        }
2730    }
2731
2732    fn resolve_table_expr_subqueries(
2733        &self,
2734        mut table: TableQuery,
2735        frame: &dyn super::statement_frame::ReadFrame,
2736    ) -> RedDBResult<TableQuery> {
2737        // Only a `Subquery` source needs recursive resolution. `.take()`
2738        // would otherwise drop a `Name` / `Function` source on the floor
2739        // (the `if let` skips the body but the take already cleared it),
2740        // which silently broke `SELECT * FROM components(g)` — the TVF
2741        // dispatch downstream keys off `TableSource::Function` and never
2742        // fired. Restore any non-subquery source unchanged (issue #795).
2743        match table.source.take() {
2744            Some(TableSource::Subquery(inner)) => {
2745                let inner = self.resolve_select_expr_subqueries(*inner, frame)?;
2746                table.source = Some(TableSource::Subquery(Box::new(inner)));
2747            }
2748            other => table.source = other,
2749        }
2750
2751        let outer_scopes = relation_scopes_for_query(&QueryExpr::Table(table.clone()));
2752        for item in &mut table.select_items {
2753            if let reddb_rql::ast::SelectItem::Expr { expr, .. } = item {
2754                *expr = self.resolve_expr_subqueries(expr.clone(), &outer_scopes, frame)?;
2755            }
2756        }
2757        if let Some(where_expr) = table.where_expr.take() {
2758            table.where_expr =
2759                Some(self.resolve_expr_subqueries(where_expr, &outer_scopes, frame)?);
2760            table.filter = None;
2761        }
2762        if let Some(having_expr) = table.having_expr.take() {
2763            table.having_expr =
2764                Some(self.resolve_expr_subqueries(having_expr, &outer_scopes, frame)?);
2765            table.having = None;
2766        }
2767        for expr in &mut table.group_by_exprs {
2768            *expr = self.resolve_expr_subqueries(expr.clone(), &outer_scopes, frame)?;
2769        }
2770        for clause in &mut table.order_by {
2771            if let Some(expr) = clause.expr.take() {
2772                clause.expr = Some(self.resolve_expr_subqueries(expr, &outer_scopes, frame)?);
2773            }
2774        }
2775        Ok(table)
2776    }
2777
2778    fn resolve_select_expr_subqueries(
2779        &self,
2780        expr: QueryExpr,
2781        frame: &dyn super::statement_frame::ReadFrame,
2782    ) -> RedDBResult<QueryExpr> {
2783        match expr {
2784            QueryExpr::Table(table) => self
2785                .resolve_table_expr_subqueries(table, frame)
2786                .map(QueryExpr::Table),
2787            QueryExpr::Join(mut join) => {
2788                join.left = Box::new(self.resolve_select_expr_subqueries(*join.left, frame)?);
2789                join.right = Box::new(self.resolve_select_expr_subqueries(*join.right, frame)?);
2790                Ok(QueryExpr::Join(join))
2791            }
2792            other => Ok(other),
2793        }
2794    }
2795
2796    fn resolve_expr_subqueries(
2797        &self,
2798        expr: reddb_rql::ast::Expr,
2799        outer_scopes: &[String],
2800        frame: &dyn super::statement_frame::ReadFrame,
2801    ) -> RedDBResult<reddb_rql::ast::Expr> {
2802        use reddb_rql::ast::Expr;
2803
2804        match expr {
2805            Expr::Subquery { query, span } => {
2806                let values = self.execute_expr_subquery_values(query, outer_scopes, frame)?;
2807                if values.len() > 1 {
2808                    return Err(RedDBError::Query(
2809                        "scalar subquery returned more than one row".to_string(),
2810                    ));
2811                }
2812                Ok(Expr::Literal {
2813                    value: values.into_iter().next().unwrap_or(Value::Null),
2814                    span,
2815                })
2816            }
2817            Expr::BinaryOp { op, lhs, rhs, span } => Ok(Expr::BinaryOp {
2818                op,
2819                lhs: Box::new(self.resolve_expr_subqueries(*lhs, outer_scopes, frame)?),
2820                rhs: Box::new(self.resolve_expr_subqueries(*rhs, outer_scopes, frame)?),
2821                span,
2822            }),
2823            Expr::UnaryOp { op, operand, span } => Ok(Expr::UnaryOp {
2824                op,
2825                operand: Box::new(self.resolve_expr_subqueries(*operand, outer_scopes, frame)?),
2826                span,
2827            }),
2828            Expr::Cast {
2829                inner,
2830                target,
2831                span,
2832            } => Ok(Expr::Cast {
2833                inner: Box::new(self.resolve_expr_subqueries(*inner, outer_scopes, frame)?),
2834                target,
2835                span,
2836            }),
2837            Expr::FunctionCall { name, args, span } => {
2838                let args = args
2839                    .into_iter()
2840                    .map(|arg| self.resolve_expr_subqueries(arg, outer_scopes, frame))
2841                    .collect::<RedDBResult<Vec<_>>>()?;
2842                Ok(Expr::FunctionCall { name, args, span })
2843            }
2844            Expr::WindowFunctionCall {
2845                name,
2846                args,
2847                mut window,
2848                span,
2849            } => {
2850                let args = args
2851                    .into_iter()
2852                    .map(|arg| self.resolve_expr_subqueries(arg, outer_scopes, frame))
2853                    .collect::<RedDBResult<Vec<_>>>()?;
2854                for expr in &mut window.partition_by {
2855                    *expr = self.resolve_expr_subqueries(expr.clone(), outer_scopes, frame)?;
2856                }
2857                for clause in &mut window.order_by {
2858                    clause.expr =
2859                        self.resolve_expr_subqueries(clause.expr.clone(), outer_scopes, frame)?;
2860                }
2861                Ok(Expr::WindowFunctionCall {
2862                    name,
2863                    args,
2864                    window,
2865                    span,
2866                })
2867            }
2868            Expr::Case {
2869                branches,
2870                else_,
2871                span,
2872            } => {
2873                let branches = branches
2874                    .into_iter()
2875                    .map(|(cond, value)| {
2876                        Ok((
2877                            self.resolve_expr_subqueries(cond, outer_scopes, frame)?,
2878                            self.resolve_expr_subqueries(value, outer_scopes, frame)?,
2879                        ))
2880                    })
2881                    .collect::<RedDBResult<Vec<_>>>()?;
2882                let else_ = else_
2883                    .map(|expr| self.resolve_expr_subqueries(*expr, outer_scopes, frame))
2884                    .transpose()?
2885                    .map(Box::new);
2886                Ok(Expr::Case {
2887                    branches,
2888                    else_,
2889                    span,
2890                })
2891            }
2892            Expr::IsNull {
2893                operand,
2894                negated,
2895                span,
2896            } => Ok(Expr::IsNull {
2897                operand: Box::new(self.resolve_expr_subqueries(*operand, outer_scopes, frame)?),
2898                negated,
2899                span,
2900            }),
2901            Expr::InList {
2902                target,
2903                values,
2904                negated,
2905                span,
2906            } => {
2907                let target =
2908                    Box::new(self.resolve_expr_subqueries(*target, outer_scopes, frame)?);
2909                let mut resolved = Vec::new();
2910                for value in values {
2911                    if let Expr::Subquery { query, .. } = value {
2912                        resolved.extend(
2913                            self.execute_expr_subquery_values(query, outer_scopes, frame)?
2914                                .into_iter()
2915                                .map(Expr::lit),
2916                        );
2917                    } else {
2918                        resolved.push(self.resolve_expr_subqueries(value, outer_scopes, frame)?);
2919                    }
2920                }
2921                Ok(Expr::InList {
2922                    target,
2923                    values: resolved,
2924                    negated,
2925                    span,
2926                })
2927            }
2928            Expr::Between {
2929                target,
2930                low,
2931                high,
2932                negated,
2933                span,
2934            } => Ok(Expr::Between {
2935                target: Box::new(self.resolve_expr_subqueries(*target, outer_scopes, frame)?),
2936                low: Box::new(self.resolve_expr_subqueries(*low, outer_scopes, frame)?),
2937                high: Box::new(self.resolve_expr_subqueries(*high, outer_scopes, frame)?),
2938                negated,
2939                span,
2940            }),
2941            other => Ok(other),
2942        }
2943    }
2944
2945    fn execute_expr_subquery_values(
2946        &self,
2947        subquery: reddb_rql::ast::ExprSubquery,
2948        outer_scopes: &[String],
2949        frame: &dyn super::statement_frame::ReadFrame,
2950    ) -> RedDBResult<Vec<Value>> {
2951        let query = *subquery.query;
2952        if query_references_outer_scope(&query, outer_scopes) {
2953            return Err(RedDBError::Query(
2954                "NOT_YET_SUPPORTED: correlated subqueries are not supported yet; track follow-up issue #470-correlated-subqueries".to_string(),
2955            ));
2956        }
2957        let query = self.rewrite_view_refs(query);
2958        let query = self.resolve_select_expr_subqueries(query, frame)?;
2959        let query = self.authorize_relational_select_expr(query, frame)?;
2960        let result = match query {
2961            QueryExpr::Table(table) => {
2962                execute_runtime_table_query(&self.inner.db, &table, Some(&self.inner.index_store))?
2963            }
2964            QueryExpr::Join(join) => execute_runtime_join_query(self, &join)?,
2965            other => {
2966                return Err(RedDBError::Query(format!(
2967                    "expression subquery must be a SELECT query, got {}",
2968                    query_expr_name(&other)
2969                )))
2970            }
2971        };
2972        first_column_values(result)
2973    }
2974
2975    fn execute_materialized_graph(
2976        &self,
2977        query: &str,
2978        mode: QueryMode,
2979        statement: &'static str,
2980        expr: &QueryExpr,
2981    ) -> RedDBResult<RuntimeQueryResult> {
2982        // Apply MVCC visibility + RLS gate while materialising the
2983        // graph: every node entity is screened against the source
2984        // collection's policy chain (basic and `Nodes`-targeted)
2985        // and dropped when the caller's tenant / role doesn't
2986        // admit it. Edges are pruned automatically because the
2987        // graph builder skips edges whose endpoints aren't in
2988        // `allowed_nodes`.
2989        let (graph, node_properties, edge_properties) = self.materialize_graph_with_rls()?;
2990        let result =
2991            crate::storage::query::unified::UnifiedExecutor::execute_on_with_graph_properties_checked(
2992                &graph,
2993                expr,
2994                node_properties,
2995                edge_properties,
2996                super::function_budget::graph_work_check(),
2997            )
2998            .map_err(|err| RedDBError::Query(err.to_string()))?;
2999
3000        Ok(RuntimeQueryResult {
3001            query: query.to_string(),
3002            mode,
3003            statement,
3004            engine: "materialized-graph",
3005            result,
3006            affected_rows: 0,
3007            statement_type: "select",
3008            bookmark: None,
3009            notice: None,
3010        })
3011    }
3012
3013    fn dispatch_expr(
3014        &self,
3015        expr: QueryExpr,
3016        query_str: &str,
3017        mode: QueryMode,
3018    ) -> RedDBResult<RuntimeQueryResult> {
3019        // Typed read plans only: mutation/transaction cleanup must never fail
3020        // because a read result or cooperative deadline budget was exhausted.
3021        let is_read = super::query_budget::is_materialized_read(&expr);
3022        let _budget = if is_read {
3023            Some(super::query_budget::Scope::enter(
3024                self.resource_limits(),
3025                &self.inner.query_budget_slots,
3026            )?)
3027        } else {
3028            None
3029        };
3030        let result = self.dispatch_expr_inner(expr, query_str, mode);
3031        if is_read {
3032            super::query_budget::charge(0)?;
3033        }
3034        let result = result?;
3035        super::query_budget::check_result(self.resource_limits(), &result)?;
3036        if is_read {
3037            super::query_budget::charge(0)?;
3038        }
3039        Ok(result)
3040    }
3041
3042    fn dispatch_expr_inner(
3043        &self,
3044        expr: QueryExpr,
3045        query_str: &str,
3046        mode: QueryMode,
3047    ) -> RedDBResult<RuntimeQueryResult> {
3048        let statement = query_expr_name(&expr);
3049        match expr {
3050            QueryExpr::Function(command) => self.execute_function(query_str, &command),
3051            QueryExpr::Graph(_) | QueryExpr::Path(_) => {
3052                self.execute_materialized_graph(query_str, mode, statement, &expr)
3053            }
3054            QueryExpr::Table(table) => {
3055                let scope = self.ai_scope();
3056                let table = self.resolve_table_expr_subqueries(
3057                    table,
3058                    &scope as &dyn super::statement_frame::ReadFrame,
3059                )?;
3060                // Table-valued functions (e.g. components(g)) dispatch to a
3061                // read-only executor before any catalog/virtual-table routing
3062                // (issue #795).
3063                if let Some(TableSource::Function {
3064                    name,
3065                    args,
3066                    named_args,
3067                }) = table.source.clone()
3068                {
3069                    return Ok(RuntimeQueryResult {
3070                        query: query_str.to_string(),
3071                        mode,
3072                        statement,
3073                        engine: "runtime-graph-tvf",
3074                        result: self.execute_table_function(&name, &args, &named_args)?,
3075                        affected_rows: 0,
3076                        statement_type: "select",
3077                        bookmark: None,
3078                        notice: None,
3079                    });
3080                }
3081                // Inline-graph TVF (issue #799) on the prepared-statement /
3082                // direct-expr path. Result caching is wired on the
3083                // `execute_query_inner` path; here we just compute and return.
3084                if let Some(TableSource::InlineGraphFunction {
3085                    name,
3086                    nodes,
3087                    edges,
3088                    named_args,
3089                }) = table.source.clone()
3090                {
3091                    return Ok(RuntimeQueryResult {
3092                        query: query_str.to_string(),
3093                        mode,
3094                        statement,
3095                        engine: "runtime-graph-tvf-inline",
3096                        result: self.execute_inline_graph_function(
3097                            &name,
3098                            &nodes,
3099                            &edges,
3100                            &named_args,
3101                        )?,
3102                        affected_rows: 0,
3103                        statement_type: "select",
3104                        bookmark: None,
3105                        notice: None,
3106                    });
3107                }
3108                if super::red_schema::is_virtual_table(&table.table) {
3109                    return Ok(RuntimeQueryResult {
3110                        query: query_str.to_string(),
3111                        mode,
3112                        statement,
3113                        engine: "runtime-red-schema",
3114                        result: super::red_schema::red_query(
3115                            self,
3116                            &table.table,
3117                            &table,
3118                            &scope as &dyn super::statement_frame::ReadFrame,
3119                        )?,
3120                        affected_rows: 0,
3121                        statement_type: "select",
3122                        bookmark: None,
3123                        notice: None,
3124                    });
3125                }
3126                // `<graph>.<output>` analytics virtual view (issue #800).
3127                if let Some(view_result) = self.try_resolve_analytics_view(
3128                    &table,
3129                    &scope as &dyn super::statement_frame::ReadFrame,
3130                )? {
3131                    return Ok(RuntimeQueryResult {
3132                        query: query_str.to_string(),
3133                        mode,
3134                        statement,
3135                        engine: "runtime-graph-analytics-view",
3136                        result: view_result,
3137                        affected_rows: 0,
3138                        statement_type: "select",
3139                        bookmark: None,
3140                        notice: None,
3141                    });
3142                }
3143                let Some(table_with_rls) = self.authorize_relational_table_select(
3144                    table,
3145                    &scope as &dyn super::statement_frame::ReadFrame,
3146                )?
3147                else {
3148                    return Ok(RuntimeQueryResult {
3149                        query: query_str.to_string(),
3150                        mode,
3151                        statement,
3152                        engine: "runtime-table-rls",
3153                        result: crate::storage::query::unified::UnifiedResult::empty(),
3154                        affected_rows: 0,
3155                        statement_type: "select",
3156                        bookmark: None,
3157                        notice: None,
3158                    });
3159                };
3160                Ok(RuntimeQueryResult {
3161                    query: query_str.to_string(),
3162                    mode,
3163                    statement,
3164                    engine: "runtime-table",
3165                    result: execute_runtime_table_query(
3166                        &self.inner.db,
3167                        &table_with_rls,
3168                        Some(&self.inner.index_store),
3169                    )?,
3170                    affected_rows: 0,
3171                    statement_type: "select",
3172                    bookmark: None,
3173                    notice: None,
3174                })
3175            }
3176            QueryExpr::Join(join) => {
3177                let scope = self.ai_scope();
3178                let Some(join_with_rls) = self.authorize_relational_join_select(
3179                    join,
3180                    &scope as &dyn super::statement_frame::ReadFrame,
3181                )?
3182                else {
3183                    return Ok(RuntimeQueryResult {
3184                        query: query_str.to_string(),
3185                        mode,
3186                        statement,
3187                        engine: "runtime-join-rls",
3188                        result: crate::storage::query::unified::UnifiedResult::empty(),
3189                        affected_rows: 0,
3190                        statement_type: "select",
3191                        bookmark: None,
3192                        notice: None,
3193                    });
3194                };
3195                Ok(RuntimeQueryResult {
3196                    query: query_str.to_string(),
3197                    mode,
3198                    statement,
3199                    engine: "runtime-join",
3200                    result: execute_runtime_join_query(self, &join_with_rls)?,
3201                    affected_rows: 0,
3202                    statement_type: "select",
3203                    bookmark: None,
3204                    notice: None,
3205                })
3206            }
3207            QueryExpr::Vector(vector) => Ok(RuntimeQueryResult {
3208                query: query_str.to_string(),
3209                mode,
3210                statement,
3211                engine: "runtime-vector",
3212                result: execute_runtime_vector_query(self, &vector)?,
3213                affected_rows: 0,
3214                statement_type: "select",
3215                bookmark: None,
3216                notice: None,
3217            }),
3218            QueryExpr::Hybrid(hybrid) => Ok(RuntimeQueryResult {
3219                query: query_str.to_string(),
3220                mode,
3221                statement,
3222                engine: "runtime-hybrid",
3223                result: execute_runtime_hybrid_query(self, &hybrid)?,
3224                affected_rows: 0,
3225                statement_type: "select",
3226                bookmark: None,
3227                notice: None,
3228            }),
3229            QueryExpr::Insert(ref insert) if super::red_schema::is_virtual_table(&insert.table) => {
3230                Err(RedDBError::Query(
3231                    super::red_schema::READ_ONLY_ERROR.to_string(),
3232                ))
3233            }
3234            QueryExpr::Update(ref update) if super::red_schema::is_virtual_table(&update.table) => {
3235                Err(RedDBError::Query(
3236                    super::red_schema::READ_ONLY_ERROR.to_string(),
3237                ))
3238            }
3239            QueryExpr::Delete(ref delete) if super::red_schema::is_virtual_table(&delete.table) => {
3240                Err(RedDBError::Query(
3241                    super::red_schema::READ_ONLY_ERROR.to_string(),
3242                ))
3243            }
3244            QueryExpr::Insert(ref insert) => self.execute_insert(query_str, insert),
3245            QueryExpr::Update(ref update) => self
3246                .with_deferred_store_wal_for_dml(self.update_may_emit_events(update), || {
3247                    self.execute_update(query_str, update)
3248                }),
3249            QueryExpr::Delete(ref delete) => self
3250                .with_deferred_store_wal_for_dml(self.delete_may_emit_events(delete), || {
3251                    self.execute_delete(query_str, delete)
3252                }),
3253            QueryExpr::QueueCommand(ref cmd) => self.with_deferred_store_wal_if_transaction(|| {
3254                self.execute_queue_command(query_str, cmd)
3255            }),
3256            QueryExpr::KvCommand(ref cmd) => self.execute_kv_command(query_str, cmd),
3257            QueryExpr::SearchCommand(ref cmd) => self.execute_search_command(query_str, cmd),
3258            QueryExpr::Ask(ref ask) => self.execute_ask(query_str, ask),
3259            _ => Err(RedDBError::Query(format!(
3260                "prepared-statement execution does not support {statement} statements"
3261            ))),
3262        }
3263    }
3264
3265    /// Dispatch a graph-collection table-valued function call in FROM
3266    /// position (e.g. `SELECT * FROM components(g)`).
3267    ///
3268    /// Validates the function name and arity here, materializes the whole
3269    /// active graph read-only, then runs the algorithm via the shared
3270    /// `dispatch_graph_algorithm` path. Never mutates the catalog or store.
3271    fn execute_table_function(
3272        &self,
3273        name: &str,
3274        args: &[String],
3275        named_args: &[(String, f64)],
3276    ) -> RedDBResult<crate::storage::query::unified::UnifiedResult> {
3277        if name.eq_ignore_ascii_case("red.diff") {
3278            return self.execute_vcs_diff_tvf(args, named_args);
3279        }
3280        if !is_graph_tvf_name(name) {
3281            return Err(RedDBError::Query(format!("unknown table function: {name}")));
3282        }
3283        // Every graph-collection TVF takes exactly one graph argument.
3284        if args.len() != 1 {
3285            return Err(RedDBError::Query(format!(
3286                "table function '{name}' takes exactly 1 graph argument, got {}",
3287                args.len()
3288            )));
3289        }
3290
3291        // Read-only materialization of the full active graph. Passing `None`
3292        // for the projection uses the full graph store. Like #795/#796, the
3293        // v0 form runs over the whole graph store regardless of the collection
3294        // argument value. Materialization never mutates any store.
3295        let (nodes, edges) = self.materialize_whole_graph_abstract()?;
3296        self.dispatch_graph_algorithm(name, nodes, edges, named_args)
3297    }
3298
3299    pub(crate) fn revive_versioned_updates_since(
3300        &self,
3301        conn_id: u64,
3302        stamper_xid: u64,
3303    ) -> RedDBResult<usize> {
3304        // Snapshot undo identities without retaining the journal while waiting
3305        // for topology. Writers take topology before recording their undo entry.
3306        let candidates = {
3307            let guard = self.inner.pending_versioned_updates.read();
3308            let Some(pending) = guard.get(&conn_id) else {
3309                return Ok(0);
3310            };
3311            pending
3312                .iter()
3313                .rev()
3314                .filter(|entry| entry.3 >= stamper_xid)
3315                .cloned()
3316                .collect::<Vec<_>>()
3317        };
3318        let mut reverted = 0usize;
3319        for candidate in candidates {
3320            let (collection, old_id, new_id, xid, previous_xmax) = &candidate;
3321            let topology_lock = self.index_store_ref().collection_topology_lock(collection);
3322            #[cfg(test)]
3323            self.index_store_ref().mutation_test_hook(
3324                collection,
3325                super::index_store::MutationTestPhase::BeforeUndoTopology,
3326            );
3327            let topology_guard = topology_lock.read();
3328            let mut guard = self.inner.pending_versioned_updates.write();
3329            let Some(pending) = guard.get_mut(&conn_id) else {
3330                continue;
3331            };
3332            // Revalidate after waiting. Remove only successfully restored entries;
3333            // an error leaves this entry and the remaining undo journal intact.
3334            let Some(position) = pending.iter().rposition(|entry| entry == &candidate) else {
3335                continue;
3336            };
3337            self.revive_versioned_update(
3338                collection,
3339                *old_id,
3340                *new_id,
3341                *xid,
3342                *previous_xmax,
3343                topology_guard,
3344            )?;
3345            pending.remove(position);
3346            reverted += 1;
3347            if pending.is_empty() {
3348                guard.remove(&conn_id);
3349            }
3350        }
3351        Ok(reverted)
3352    }
3353
3354    /// `EXPLAIN` is peeled off the statement text before parsing, so the
3355    /// planner ran on the inner statement with no privilege check at all:
3356    /// a read-only principal could plan any write and read the table's
3357    /// column list and row estimate back out of the plan. The plan needs
3358    /// exactly the privilege the statement it describes needs.
3359    fn check_explain_target_privilege(&self, inner_sql: &str) -> RedDBResult<()> {
3360        let parsed =
3361            reddb_rql::parser::parse(inner_sql).map_err(|e| RedDBError::Query(e.to_string()))?;
3362        self.check_query_privilege(&parsed.query)
3363            .map_err(|err| RedDBError::Query(format!("permission denied: {err}")))
3364    }
3365
3366    /// Wrap the planner's `RuntimeQueryExplain` as rows on a
3367    /// `RuntimeQueryResult` so callers over the SQL interface see the
3368    /// plan tree in the same shape a SELECT produces.
3369    ///
3370    /// Columns: `op`, `source`, `estimated_rows`, `estimated_cost`, `depth`.
3371    /// Nodes are walked depth-first; `depth` counts from 0 at the
3372    /// root so a text renderer can indent without re-walking.
3373    fn explain_as_rows(&self, raw_query: &str, inner_sql: &str) -> RedDBResult<RuntimeQueryResult> {
3374        self.check_explain_target_privilege(inner_sql)?;
3375        let explain = self.explain_query(inner_sql)?;
3376
3377        let mut columns = vec![
3378            "op".to_string(),
3379            "source".to_string(),
3380            "estimated_rows".to_string(),
3381            "estimated_cost".to_string(),
3382            "depth".to_string(),
3383        ];
3384
3385        let mut records: Vec<crate::storage::query::unified::UnifiedRecord> = Vec::new();
3386
3387        // Prepend `CteScan` markers when the query carried a leading
3388        // WITH clause. The CTE bodies are already inlined into the
3389        // main plan tree, but operators reading EXPLAIN need to see
3390        // which named CTEs were resolved — without this row the plan
3391        // would look indistinguishable from a hand-inlined query.
3392        for name in &explain.cte_materializations {
3393            use std::sync::Arc;
3394            let mut rec = crate::storage::query::unified::UnifiedRecord::default();
3395            rec.set_arc(Arc::from("op"), Value::text("CteScan".to_string()));
3396            rec.set_arc(Arc::from("source"), Value::text(name.clone()));
3397            rec.set_arc(Arc::from("estimated_rows"), Value::Float(0.0));
3398            rec.set_arc(Arc::from("estimated_cost"), Value::Float(0.0));
3399            rec.set_arc(Arc::from("depth"), Value::Integer(0));
3400            records.push(rec);
3401        }
3402
3403        let vector_details = explain.statement == "vector";
3404        if vector_details {
3405            columns.extend(["access_path_reason".to_string(), "index_hint".to_string()]);
3406        }
3407        walk_plan_node(&explain.logical_plan.root, 0, &mut records, vector_details);
3408
3409        let result = crate::storage::query::unified::UnifiedResult {
3410            columns,
3411            records,
3412            stats: Default::default(),
3413            pre_serialized_json: None,
3414        };
3415
3416        Ok(RuntimeQueryResult {
3417            query: raw_query.to_string(),
3418            mode: explain.mode,
3419            statement: "explain",
3420            engine: "runtime-explain",
3421            result,
3422            affected_rows: 0,
3423            statement_type: "select",
3424            bookmark: None,
3425            notice: None,
3426        })
3427    }
3428
3429    fn explain_analyze_vector_as_rows(
3430        &self,
3431        raw_query: &str,
3432        expr: QueryExpr,
3433    ) -> RedDBResult<RuntimeQueryResult> {
3434        let QueryExpr::Vector(query) = &expr else {
3435            return Err(RedDBError::Internal(
3436                "expected vector analysis target".to_string(),
3437            ));
3438        };
3439        let source = query.collection.clone();
3440        // The typed entry installs the full statement frame and privilege gate,
3441        // and cannot serve an earlier result-cache measurement as a fresh run.
3442        let execution = self.execute_query_expr(expr)?;
3443        let stats = execution.result.stats;
3444        let vector = stats.vector.as_ref().ok_or_else(|| {
3445            RedDBError::Internal("vector executor did not provide measurements".to_string())
3446        })?;
3447        let fields = vec![
3448            ("op", Value::text(vector.access_path.clone())),
3449            ("source", Value::text(source)),
3450            ("index_used", Value::Boolean(vector.index_used)),
3451            ("mode_requested", Value::text(vector.mode_requested.clone())),
3452            ("mode_executed", Value::text(vector.mode_executed.clone())),
3453            (
3454                "fallback_reason",
3455                vector
3456                    .fallback_reason
3457                    .as_ref()
3458                    .map_or(Value::Null, |reason| Value::text(reason.clone())),
3459            ),
3460            (
3461                "approximate_distance_evaluations",
3462                Value::UnsignedInteger(vector.approximate_distance_evaluations),
3463            ),
3464            (
3465                "peak_topk_entries",
3466                Value::UnsignedInteger(vector.peak_topk_entries),
3467            ),
3468            (
3469                "candidates_examined",
3470                Value::UnsignedInteger(vector.candidates_examined),
3471            ),
3472            (
3473                "metadata_rejected",
3474                Value::UnsignedInteger(vector.metadata_rejected),
3475            ),
3476            ("rls_rejected", Value::UnsignedInteger(vector.rls_rejected)),
3477            (
3478                "visibility_rejected",
3479                Value::UnsignedInteger(vector.visibility_rejected),
3480            ),
3481            (
3482                "exact_distance_evaluations",
3483                Value::UnsignedInteger(vector.exact_distance_evaluations),
3484            ),
3485            ("actual_rows", Value::UnsignedInteger(vector.rows_returned)),
3486            (
3487                "actual_ms",
3488                Value::Float(stats.exec_time_us as f64 / 1000.0),
3489            ),
3490            ("metrics_scope", Value::text("vector_pipeline")),
3491            (
3492                "operators",
3493                Value::Json(vector.operators_json().to_string().into_bytes()),
3494            ),
3495        ];
3496        let columns = fields.iter().map(|(name, _)| name.to_string()).collect();
3497        let mut record = crate::storage::query::unified::UnifiedRecord::default();
3498        for (name, value) in fields {
3499            record.set_owned(name.to_string(), value);
3500        }
3501        Ok(RuntimeQueryResult {
3502            query: raw_query.to_string(),
3503            mode: execution.mode,
3504            statement: "explain_analyze",
3505            engine: "runtime-explain-analyze",
3506            result: crate::storage::query::unified::UnifiedResult {
3507                columns,
3508                records: vec![record],
3509                stats,
3510                pre_serialized_json: None,
3511            },
3512            affected_rows: 0,
3513            statement_type: "select",
3514            bookmark: None,
3515            notice: None,
3516        })
3517    }
3518
3519    fn explain_analyze_as_rows(
3520        &self,
3521        raw_query: &str,
3522        inner_sql: &str,
3523    ) -> RedDBResult<RuntimeQueryResult> {
3524        if strip_keyword_ci(inner_sql.trim_start(), "VECTOR").is_some() {
3525            let expr = parse_multi(inner_sql).map_err(|err| RedDBError::Query(err.to_string()))?;
3526            if matches!(&expr, QueryExpr::Vector(_)) {
3527                return self.explain_analyze_vector_as_rows(raw_query, expr);
3528            }
3529        }
3530        if !starts_with_dml_keyword(inner_sql) {
3531            return Err(RedDBError::Query(
3532                "EXPLAIN ANALYZE currently supports INSERT, UPDATE, DELETE, and VECTOR SEARCH"
3533                    .to_string(),
3534            ));
3535        }
3536
3537        self.check_explain_target_privilege(inner_sql)?;
3538        let explain = self.explain_query(inner_sql)?;
3539        let conn_id = current_connection_id();
3540        if self.inner.transaction_state.in_transaction(conn_id) {
3541            return Err(RedDBError::Query(
3542                "EXPLAIN ANALYZE requires no active transaction".to_string(),
3543            ));
3544        }
3545
3546        self.execute_query_inner("BEGIN")?;
3547        let started = std::time::Instant::now();
3548        let execution = self.execute_query_inner(inner_sql);
3549        let elapsed_ms = started.elapsed().as_secs_f64() * 1000.0;
3550        let rollback = self.execute_query_inner("ROLLBACK");
3551
3552        let affected_rows = match execution {
3553            Ok(result) => result.affected_rows,
3554            Err(err) => {
3555                rollback?;
3556                return Err(err);
3557            }
3558        };
3559        rollback?;
3560
3561        let columns = vec![
3562            "op".to_string(),
3563            "source".to_string(),
3564            "estimated_rows".to_string(),
3565            "estimated_cost".to_string(),
3566            "actual_rows".to_string(),
3567            "actual_ms".to_string(),
3568            "depth".to_string(),
3569        ];
3570        let mut records = Vec::new();
3571        walk_analyze_plan_node(
3572            &explain.logical_plan.root,
3573            0,
3574            affected_rows,
3575            elapsed_ms,
3576            &mut records,
3577        );
3578
3579        let result = crate::storage::query::unified::UnifiedResult {
3580            columns,
3581            records,
3582            stats: Default::default(),
3583            pre_serialized_json: None,
3584        };
3585
3586        Ok(RuntimeQueryResult {
3587            query: raw_query.to_string(),
3588            mode: explain.mode,
3589            statement: "explain_analyze",
3590            engine: "runtime-explain-analyze",
3591            result,
3592            affected_rows: 0,
3593            statement_type: "select",
3594            bookmark: None,
3595            notice: None,
3596        })
3597    }
3598}
3599
3600fn redact_sql_for_slow_log(query: &str) -> String {
3601    let lowered = query.to_ascii_lowercase();
3602    if lowered.contains("secret") || lowered.contains("vault") {
3603        return "secret statement (SQL redacted)".to_string();
3604    }
3605    let credential_candidate = lowered.contains("password")
3606        && ((lowered.contains("create") && lowered.contains("user"))
3607            || (lowered.contains("alter") && lowered.contains("user")));
3608    if !credential_candidate {
3609        return query.to_string();
3610    }
3611    match parse_multi(query) {
3612        Ok(QueryExpr::CreateUser(stmt)) => {
3613            let target = UserId::from_parts(stmt.tenant.as_deref(), &stmt.username);
3614            format!("CREATE USER {target} PASSWORD '***' ROLE {}", stmt.role)
3615        }
3616        Ok(QueryExpr::AlterUser(stmt))
3617            if stmt
3618                .attributes
3619                .iter()
3620                .any(|attr| matches!(attr, reddb_rql::ast::AlterUserAttribute::Password(_))) =>
3621        {
3622            let target = UserId::from_parts(stmt.tenant.as_deref(), &stmt.username);
3623            format!("ALTER USER {target} PASSWORD '***'")
3624        }
3625        Ok(_) => "credential statement (SQL redacted)".to_string(),
3626        Err(_) => "credential statement (SQL redacted)".to_string(),
3627    }
3628}
3629
3630fn strip_explain_analyze_prefix(sql: &str) -> Option<&str> {
3631    let rest = strip_keyword_ci(sql.trim_start(), "EXPLAIN")?.trim_start();
3632    Some(strip_keyword_ci(rest, "ANALYZE")?.trim_start()).filter(|inner| !inner.is_empty())
3633}
3634
3635fn strip_keyword_ci<'a>(sql: &'a str, keyword: &str) -> Option<&'a str> {
3636    // `get` is None past the end or inside a multi-byte character, where
3637    // `split_at` would panic (and a release build aborts on panic).
3638    let head = sql.get(..keyword.len())?;
3639    let rest = &sql[keyword.len()..];
3640    if !head.eq_ignore_ascii_case(keyword) {
3641        return None;
3642    }
3643    if rest
3644        .chars()
3645        .next()
3646        .is_some_and(|ch| !ch.is_ascii_whitespace())
3647    {
3648        return None;
3649    }
3650    Some(rest)
3651}
3652
3653fn starts_with_dml_keyword(sql: &str) -> bool {
3654    let trimmed = sql.trim_start();
3655    let head_end = trimmed
3656        .find(|ch: char| ch.is_ascii_whitespace())
3657        .unwrap_or(trimmed.len());
3658    let head = &trimmed[..head_end];
3659    head.eq_ignore_ascii_case("INSERT")
3660        || head.eq_ignore_ascii_case("UPDATE")
3661        || head.eq_ignore_ascii_case("DELETE")
3662}
3663
3664fn walk_plan_node(
3665    node: &crate::storage::query::planner::CanonicalLogicalNode,
3666    depth: usize,
3667    out: &mut Vec<crate::storage::query::unified::UnifiedRecord>,
3668    vector_details: bool,
3669) {
3670    use std::sync::Arc;
3671    let mut rec = crate::storage::query::unified::UnifiedRecord::default();
3672    rec.set_arc(Arc::from("op"), Value::text(node.operator.clone()));
3673    rec.set_arc(
3674        Arc::from("source"),
3675        node.source.clone().map(Value::text).unwrap_or(Value::Null),
3676    );
3677    rec.set_arc(
3678        Arc::from("estimated_rows"),
3679        Value::Float(node.estimated_rows),
3680    );
3681    rec.set_arc(
3682        Arc::from("estimated_cost"),
3683        Value::Float(node.operator_cost),
3684    );
3685    rec.set_arc(Arc::from("depth"), Value::Integer(depth as i64));
3686    if vector_details {
3687        for name in ["access_path_reason", "index_hint"] {
3688            rec.set_owned(
3689                name.to_string(),
3690                node.details
3691                    .get(name)
3692                    .cloned()
3693                    .map(Value::text)
3694                    .unwrap_or(Value::Null),
3695            );
3696        }
3697    }
3698    out.push(rec);
3699    for child in &node.children {
3700        walk_plan_node(child, depth + 1, out, vector_details);
3701    }
3702}
3703
3704fn walk_analyze_plan_node(
3705    node: &crate::storage::query::planner::CanonicalLogicalNode,
3706    depth: usize,
3707    affected_rows: u64,
3708    elapsed_ms: f64,
3709    out: &mut Vec<crate::storage::query::unified::UnifiedRecord>,
3710) {
3711    use std::sync::Arc;
3712    let mut rec = crate::storage::query::unified::UnifiedRecord::default();
3713    rec.set_arc(Arc::from("op"), Value::text(node.operator.clone()));
3714    rec.set_arc(
3715        Arc::from("source"),
3716        node.source.clone().map(Value::text).unwrap_or(Value::Null),
3717    );
3718    rec.set_arc(
3719        Arc::from("estimated_rows"),
3720        Value::Float(node.estimated_rows),
3721    );
3722    rec.set_arc(
3723        Arc::from("estimated_cost"),
3724        Value::Float(node.operator_cost),
3725    );
3726    rec.set_arc(
3727        Arc::from("actual_rows"),
3728        Value::UnsignedInteger(if depth == 0 { affected_rows } else { 0 }),
3729    );
3730    rec.set_arc(
3731        Arc::from("actual_ms"),
3732        Value::Float(if depth == 0 { elapsed_ms } else { 0.0 }),
3733    );
3734    rec.set_arc(Arc::from("depth"), Value::Integer(depth as i64));
3735    out.push(rec);
3736
3737    for child in &node.children {
3738        walk_analyze_plan_node(child, depth + 1, 0, 0.0, out);
3739    }
3740}
3741
3742#[cfg(test)]
3743mod declared_model_validation_tests {
3744    use super::*;
3745    use crate::catalog::CollectionModel;
3746    use crate::storage::no_malloc_hot_paths::measure_allocations;
3747    use reddb_rql::ast::KvCommand;
3748
3749    fn get(collection: &str) -> QueryExpr {
3750        QueryExpr::KvCommand(KvCommand::Get {
3751            model: CollectionModel::Kv,
3752            collection: collection.into(),
3753            key: "item".into(),
3754        })
3755    }
3756
3757    #[test]
3758    fn declared_model_validation_keeps_mismatches_and_observes_contract_changes() {
3759        let runtime = RedDBRuntime::in_memory().expect("runtime");
3760        runtime
3761            .execute_query("KV PUT declared.item = 1")
3762            .expect("seed");
3763        runtime
3764            .validate_model_operations_before_auth(&get("declared"))
3765            .expect("KV contract");
3766        let db = runtime.db();
3767        for (model, name) in [
3768            (CollectionModel::Table, "table"),
3769            (CollectionModel::Mixed, "mixed"),
3770        ] {
3771            let mut contract = db.collection_contract("declared").expect("contract");
3772            contract.declared_model = model;
3773            db.save_collection_contract(contract)
3774                .expect("replace contract");
3775            let error = runtime
3776                .validate_model_operations_before_auth(&get("declared"))
3777                .expect_err("mismatch");
3778            assert_eq!(
3779                error.to_string(),
3780                format!("INVALID_OPERATION: model mismatch: expected kv, got {name}")
3781            );
3782        }
3783    }
3784
3785    #[test]
3786    fn declared_model_validation_preserves_legacy_inference_and_missing_collections() {
3787        let runtime = RedDBRuntime::in_memory().expect("runtime");
3788        let db = runtime.db();
3789        let store = db.store();
3790        store
3791            .create_collection("legacy")
3792            .expect("legacy collection");
3793        store
3794            .get_collection("legacy")
3795            .expect("manager")
3796            .insert(crate::storage::UnifiedEntity::table_row(
3797                crate::storage::EntityId::new(1),
3798                "legacy",
3799                1,
3800                Vec::new(),
3801            ))
3802            .expect("uncontracted table row");
3803        assert!(db.collection_contract("legacy").is_none());
3804        let error = runtime
3805            .validate_model_operations_before_auth(&get("legacy"))
3806            .expect_err("inferred table");
3807        assert!(error
3808            .to_string()
3809            .contains("model mismatch: expected kv, got table"));
3810        runtime
3811            .validate_model_operations_before_auth(&get("missing"))
3812            .expect("missing stays deferred to execution");
3813    }
3814
3815    #[test]
3816    fn declared_model_validation_does_not_treat_orphan_contracts_as_collections() {
3817        let runtime = RedDBRuntime::in_memory().expect("runtime");
3818        runtime
3819            .execute_query("KV PUT declared.item = 1")
3820            .expect("seed");
3821        let db = runtime.db();
3822        let mut contract = db.collection_contract("declared").expect("contract");
3823        contract.name = "orphan".into();
3824        contract.declared_model = CollectionModel::Table;
3825        db.save_collection_contract(contract)
3826            .expect("orphan contract");
3827        assert!(db.store().get_collection("orphan").is_none());
3828        runtime
3829            .validate_model_operations_before_auth(&get("orphan"))
3830            .expect("no physical collection to validate");
3831    }
3832
3833    #[test]
3834    fn declared_model_validation_allocates_nothing_with_unrelated_collections() {
3835        let runtime = RedDBRuntime::in_memory().expect("runtime");
3836        runtime
3837            .execute_query("KV PUT declared.item = 1")
3838            .expect("seed");
3839        let expr = get("declared");
3840        for unrelated in [0, 64] {
3841            let db = runtime.db();
3842            let store = db.store();
3843            for index in 0..unrelated {
3844                let name = format!("unrelated_{index}");
3845                store
3846                    .create_collection(&name)
3847                    .expect("unrelated collection");
3848            }
3849            runtime
3850                .validate_model_operations_before_auth(&expr)
3851                .expect("warm contract cache");
3852            let (result, count) =
3853                measure_allocations(|| runtime.validate_model_operations_before_auth(&expr));
3854            result.expect("declared KV");
3855            assert_eq!(
3856                count.allocs, 0,
3857                "validation must only borrow the target contract"
3858            );
3859        }
3860    }
3861}
3862
3863#[cfg(test)]
3864mod multibyte_sql_tests {
3865    use super::*;
3866
3867    #[test]
3868    fn explain_analyze_prefix_ignores_multibyte_text_at_the_keyword_boundary() {
3869        // `strip_keyword_ci` used `split_at(keyword.len())`, which panics when
3870        // that byte offset is inside a multi-byte character.
3871        for pad in 0..16 {
3872            for wide in ["é", "日", "😀"] {
3873                let sql = format!("{}{wide}llo", "a".repeat(pad));
3874                assert_eq!(strip_explain_analyze_prefix(&sql), None, "{sql:?}");
3875            }
3876        }
3877        assert_eq!(
3878            strip_explain_analyze_prefix("explain  analyze DELETE FROM t"),
3879            Some("DELETE FROM t")
3880        );
3881    }
3882
3883    /// One malformed or unusual statement must never take the process down:
3884    /// release builds abort on panic, so any panic reachable from
3885    /// `execute_query` is a remote denial of service. Put a multi-byte
3886    /// character at every byte offset a keyword matcher might slice at.
3887    #[test]
3888    fn multibyte_sql_never_panics_execute_query() {
3889        let rt = RedDBRuntime::in_memory().expect("in-memory runtime");
3890        let seeds = [
3891            "",
3892            "SELECT ",
3893            "SELECT '",
3894            "EXPLAIN ",
3895            "EXPLAIN ANALYZE ",
3896            "CHECKPOINT ",
3897            "CHECKOUT ",
3898            "RESET ",
3899            "MERGE ",
3900            "CHERRY PICK ",
3901            "REVERT ",
3902            "RESOLVE CONFLICT ",
3903            "INSERT INTO t VALUES ('",
3904        ];
3905        let mut panicked = Vec::new();
3906        for seed in seeds {
3907            for pad in 0..16 {
3908                for wide in ["é", "日", "😀"] {
3909                    let sql = format!("{seed}{}{wide}llo", "a".repeat(pad));
3910                    let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
3911                        let _ = rt.execute_query(&sql);
3912                    }));
3913                    if outcome.is_err() {
3914                        panicked.push(sql);
3915                    }
3916                }
3917            }
3918        }
3919        assert!(
3920            panicked.is_empty(),
3921            "execute_query panicked on {} statement(s), first: {:?}",
3922            panicked.len(),
3923            panicked.first()
3924        );
3925    }
3926}
3927
3928#[cfg(test)]
3929mod inline_graph_tvf_tests {
3930    use super::*;
3931
3932    fn scopes_for(sql: &str) -> HashSet<String> {
3933        let expr = reddb_rql::parser::parse(sql).expect("parse").query;
3934        query_expr_result_cache_scopes(&expr)
3935    }
3936
3937    #[test]
3938    fn inline_tvf_cache_scopes_include_source_collections() {
3939        // The result-cache key for the inline form must derive from the
3940        // `nodes`/`edges` source collections so a write to either invalidates
3941        // the cached result (issue #799).
3942        let scopes = scopes_for(
3943            "SELECT * FROM components(nodes => (SELECT id FROM hosts), edges => (SELECT src, dst FROM links))",
3944        );
3945        assert!(scopes.contains("hosts"), "nodes source scoped: {scopes:?}");
3946        assert!(scopes.contains("links"), "edges source scoped: {scopes:?}");
3947    }
3948
3949    #[test]
3950    fn graph_collection_tvf_cache_scope_is_graph_argument() {
3951        // The graph-collection form still materializes the active graph, but
3952        // result-cache invalidation is scoped to the named graph argument so
3953        // INSERT INTO g NODE/EDGE invalidates cached TVF rows.
3954        let scopes = scopes_for("SELECT * FROM components(g)");
3955        assert!(scopes.contains("g"), "collection form scoped: {scopes:?}");
3956    }
3957
3958    #[test]
3959    fn abstract_degree_centrality_counts_undirected_endpoints() {
3960        let nodes = vec!["a".to_string(), "b".to_string(), "c".to_string()];
3961        let edges = vec![
3962            ("a".to_string(), "b".to_string(), 1.0_f32),
3963            ("b".to_string(), "c".to_string(), 1.0_f32),
3964        ];
3965        let degrees = abstract_degree_centrality(&nodes, &edges);
3966        assert_eq!(
3967            degrees,
3968            vec![
3969                ("a".to_string(), 1),
3970                ("b".to_string(), 2),
3971                ("c".to_string(), 1),
3972            ]
3973        );
3974    }
3975}
3976
3977/// Vault keys the engine itself owns. `SET SECRET` / `DELETE SECRET` share
3978/// the vault KV space with the IAM policy blobs, the attachment tables and
3979/// the `SECRET()` column master key; letting a principal with `secret:write`
3980/// overwrite them is an escalation (allow-all policy after restart) or a
3981/// permanent data loss (rotated AES key). Provider credentials under
3982/// `red.secret.ai.*` stay writable — that is the documented use.
3983fn reject_engine_internal_vault_key(key: &str) -> RedDBResult<()> {
3984    let lowered = key.to_ascii_lowercase();
3985    let internal = lowered == "red.secret.aes_key"
3986        || lowered.starts_with("red.iam.")
3987        || lowered.starts_with("red.acl.")
3988        || lowered.starts_with("red.vault.");
3989    if internal {
3990        return Err(RedDBError::Query(format!(
3991            "`{key}` is an engine-internal vault key and cannot be set or deleted through SET/DELETE SECRET"
3992        )));
3993    }
3994    Ok(())
3995}
3996
3997/// Optional confinement for `COPY … FROM '<path>'`. When
3998/// `REDDB_COPY_IMPORT_ROOT` is set, the (canonicalised) source path must live
3999/// under that directory; otherwise the statement is refused. Unset keeps the
4000/// historical behaviour (any readable file, admin-only via the privilege
4001/// gate).
4002fn confine_copy_from_path(path: &str) -> RedDBResult<()> {
4003    let Ok(root) = std::env::var("REDDB_COPY_IMPORT_ROOT") else {
4004        return Ok(());
4005    };
4006    let root = std::fs::canonicalize(&root).map_err(|e| {
4007        RedDBError::Query(format!(
4008            "REDDB_COPY_IMPORT_ROOT `{root}` is not usable: {e}"
4009        ))
4010    })?;
4011    let resolved = std::fs::canonicalize(path)
4012        .map_err(|e| RedDBError::Query(format!("COPY FROM `{path}`: {e}")))?;
4013    if !resolved.starts_with(&root) || !resolved.is_file() {
4014        return Err(RedDBError::Query(format!(
4015            "COPY FROM `{path}` is outside the configured import root"
4016        )));
4017    }
4018    Ok(())
4019}
4020
4021#[cfg(test)]
4022mod result_cache_execution_tests {
4023    use super::*;
4024
4025    const QUERY: &str = "SELECT SUM(n) AS n FROM result_cache_probe";
4026
4027    fn runtime_with_rows(cache_enabled: bool) -> RedDBRuntime {
4028        let runtime = RedDBRuntime::in_memory().expect("runtime");
4029        runtime
4030            .execute_query("CREATE TABLE result_cache_probe (id INT, n INT)")
4031            .expect("create table");
4032        runtime
4033            .execute_query(
4034                "INSERT INTO result_cache_probe (id, n) VALUES (1, 10), (2, 20), (3, 30)",
4035            )
4036            .expect("seed rows");
4037        runtime
4038            .execute_query(&format!(
4039                "SET CONFIG runtime.result_cache.enabled = {cache_enabled}"
4040            ))
4041            .expect("configure result cache");
4042        runtime
4043    }
4044
4045    fn aggregate_value(runtime: &RedDBRuntime) -> i64 {
4046        let result = runtime.execute_query(QUERY).expect("aggregate query");
4047        match result.result.records[0].get("n") {
4048            Some(reddb_types::Value::Integer(value)) => *value,
4049            other => panic!("expected integer aggregate, got {other:?}"),
4050        }
4051    }
4052
4053    #[test]
4054    fn hot_hit_bypasses_query_execution_pipeline() {
4055        let runtime = runtime_with_rows(true);
4056        reset_result_cache_miss_executions();
4057        let before = runtime.result_cache_metrics();
4058
4059        assert_eq!(aggregate_value(&runtime), 60);
4060        assert_eq!(result_cache_miss_executions(), 1);
4061        assert_eq!(aggregate_value(&runtime), 60);
4062
4063        let after = runtime.result_cache_metrics();
4064        assert_eq!(
4065            result_cache_miss_executions(),
4066            1,
4067            "hit re-entered the executor"
4068        );
4069        assert_eq!(after.0 - before.0, 1, "second read must be a cache hit");
4070        assert_eq!(after.1 - before.1, 1, "first read must populate the cache");
4071    }
4072
4073    #[test]
4074    fn disabled_cache_executes_every_read() {
4075        let runtime = runtime_with_rows(false);
4076        reset_result_cache_miss_executions();
4077        let before = runtime.result_cache_metrics();
4078
4079        assert_eq!(aggregate_value(&runtime), 60);
4080        assert_eq!(aggregate_value(&runtime), 60);
4081
4082        assert_eq!(result_cache_miss_executions(), 2);
4083        assert_eq!(
4084            runtime.result_cache_metrics(),
4085            before,
4086            "disabled cache must not report lookups"
4087        );
4088    }
4089
4090    #[test]
4091    fn table_write_forces_one_reexecution_then_hits_again() {
4092        let runtime = runtime_with_rows(true);
4093        assert_eq!(aggregate_value(&runtime), 60);
4094        assert_eq!(aggregate_value(&runtime), 60);
4095        runtime
4096            .execute_query("INSERT INTO result_cache_probe (id, n) VALUES (4, 40)")
4097            .expect("mutate cached table");
4098        reset_result_cache_miss_executions();
4099        let before = runtime.result_cache_metrics();
4100
4101        assert_eq!(aggregate_value(&runtime), 100);
4102        assert_eq!(result_cache_miss_executions(), 1);
4103        assert_eq!(aggregate_value(&runtime), 100);
4104
4105        let after = runtime.result_cache_metrics();
4106        assert_eq!(result_cache_miss_executions(), 1);
4107        assert_eq!(after.0 - before.0, 1, "post-write result must become hot");
4108        assert_eq!(
4109            after.1 - before.1,
4110            1,
4111            "write must invalidate the old result"
4112        );
4113    }
4114}
4115
4116#[cfg(test)]
4117mod security_gate_tests {
4118    use super::*;
4119    use crate::auth::store::AuthStore;
4120    use crate::auth::{AuthConfig, Role};
4121
4122    /// Clears the thread-local identity on drop so one test's principal
4123    /// never leaks into the next on a shared thread.
4124    struct IdentityGuard;
4125
4126    impl IdentityGuard {
4127        fn install(username: &str, role: Role) -> Self {
4128            set_current_auth_identity(username.to_string(), role);
4129            Self
4130        }
4131    }
4132
4133    impl Drop for IdentityGuard {
4134        fn drop(&mut self) {
4135            clear_current_auth_identity();
4136        }
4137    }
4138
4139    struct ScopedIdentityGuard;
4140
4141    impl ScopedIdentityGuard {
4142        fn install(tenant: &str, username: &str, role: Role) -> Self {
4143            crate::runtime::execution_context::set_current_auth_principal(
4144                crate::auth::UserId::scoped(tenant, username),
4145                role,
4146            );
4147            set_current_tenant(tenant.to_string());
4148            Self
4149        }
4150    }
4151
4152    impl Drop for ScopedIdentityGuard {
4153        fn drop(&mut self) {
4154            clear_current_auth_identity();
4155            clear_current_tenant();
4156        }
4157    }
4158
4159    fn runtime_with_user(username: &str, role: Role) -> RedDBRuntime {
4160        let store = std::sync::Arc::new(AuthStore::new(AuthConfig {
4161            enabled: true,
4162            session_ttl_secs: 60,
4163            require_auth: true,
4164            auto_encrypt_storage: false,
4165            vault_enabled: false,
4166            cert: Default::default(),
4167            oauth: Default::default(),
4168        }));
4169        store.create_user(username, "pw", role).expect("user");
4170        let runtime =
4171            RedDBRuntime::with_options(crate::api::RedDBOptions::in_memory()).expect("runtime");
4172        runtime.set_auth_store(store);
4173        runtime
4174    }
4175
4176    fn runtime_with_store(username: &str, role: Role) -> (RedDBRuntime, std::sync::Arc<AuthStore>) {
4177        let store = std::sync::Arc::new(AuthStore::new(AuthConfig {
4178            enabled: true,
4179            session_ttl_secs: 60,
4180            require_auth: true,
4181            auto_encrypt_storage: false,
4182            vault_enabled: false,
4183            cert: Default::default(),
4184            oauth: Default::default(),
4185        }));
4186        store.create_user(username, "pw", role).expect("user");
4187        let runtime =
4188            RedDBRuntime::with_options(crate::api::RedDBOptions::in_memory()).expect("runtime");
4189        runtime.set_auth_store(std::sync::Arc::clone(&store));
4190        (runtime, store)
4191    }
4192
4193    #[test]
4194    fn tenant_credential_cannot_override_credential_scope() {
4195        use crate::runtime::within_clause::{FieldOverride, ScopeOverride};
4196
4197        let store = std::sync::Arc::new(AuthStore::new(AuthConfig {
4198            enabled: true,
4199            require_auth: true,
4200            ..AuthConfig::default()
4201        }));
4202        store
4203            .create_user_in_tenant(Some("acme"), "admin", "pw", Role::Admin)
4204            .expect("tenant admin");
4205        let runtime =
4206            RedDBRuntime::with_options(crate::api::RedDBOptions::in_memory()).expect("runtime");
4207        runtime.set_auth_store(store);
4208        let _identity = ScopedIdentityGuard::install("acme", "admin", Role::Admin);
4209
4210        runtime
4211            .execute_query("WITHIN TENANT 'acme' SELECT 1")
4212            .expect("own tenant remains valid");
4213        for sql in [
4214            "WITHIN TENANT 'globex' SELECT 1",
4215            "WITHIN TENANT NULL SELECT 1",
4216            "WITHIN TENANT 'acme' USER 'other' SELECT 1",
4217            "WITHIN TENANT 'acme' AS ROLE 'read' SELECT 1",
4218        ] {
4219            assert!(runtime.execute_query(sql).is_err(), "must reject {sql}");
4220        }
4221        assert!(runtime
4222            .execute_query_with_scope(
4223                "SELECT 1",
4224                ScopeOverride {
4225                    tenant: FieldOverride::Set("globex".to_string()),
4226                    ..ScopeOverride::default()
4227                },
4228            )
4229            .is_err());
4230
4231        set_current_connection_id(44_201);
4232        runtime.execute_query("BEGIN").expect("begin");
4233        assert!(runtime.execute_query("SET LOCAL TENANT 'globex'").is_err());
4234        runtime.execute_query("ROLLBACK").expect("rollback");
4235        clear_current_connection_id();
4236    }
4237
4238    #[test]
4239    fn tenant_admin_sql_user_lifecycle_is_tenant_bounded() {
4240        let store = std::sync::Arc::new(AuthStore::new(AuthConfig {
4241            enabled: true,
4242            require_auth: true,
4243            ..AuthConfig::default()
4244        }));
4245        store
4246            .create_user_in_tenant(Some("acme"), "admin", "pw", Role::Admin)
4247            .expect("tenant admin");
4248        let runtime =
4249            RedDBRuntime::with_options(crate::api::RedDBOptions::in_memory()).expect("runtime");
4250        runtime.set_auth_store(std::sync::Arc::clone(&store));
4251        let _identity = ScopedIdentityGuard::install("acme", "admin", Role::Admin);
4252
4253        runtime
4254            .execute_query("CREATE USER acme.alice PASSWORD 'pw' ROLE read")
4255            .expect("same-tenant create");
4256        assert!(runtime
4257            .execute_query("CREATE USER globex.alice PASSWORD 'pw' ROLE read")
4258            .is_err());
4259        assert!(runtime
4260            .execute_query("ALTER USER globex.alice PASSWORD 'owned'")
4261            .is_err());
4262        let cross_tenant_allow = crate::auth::policies::Policy::from_json_str(
4263            r#"{
4264                "id":"tenant-cross-user",
4265                "version":1,
4266                "statements":[{
4267                    "effect":"allow",
4268                    "actions":["user:create","user:password:change"],
4269                    "resources":["user:tenant/globex/*"]
4270                }]
4271            }"#,
4272        )
4273        .expect("cross-tenant policy");
4274        store.put_policy(cross_tenant_allow).expect("put policy");
4275        store
4276            .attach_policy(
4277                crate::auth::store::PrincipalRef::User(crate::auth::UserId::scoped(
4278                    "acme", "admin",
4279                )),
4280                "tenant-cross-user",
4281            )
4282            .expect("attach policy");
4283        assert!(runtime
4284            .execute_query("CREATE USER globex.bob PASSWORD 'pw' ROLE read")
4285            .is_err());
4286        assert!(store.get_user(Some("globex"), "alice").is_none());
4287        assert!(store.get_user(Some("globex"), "bob").is_none());
4288    }
4289
4290    #[test]
4291    fn slow_log_redacts_user_password_statements() {
4292        for sql in [
4293            "CREATE USER alice PASSWORD 'super-secret' ROLE admin",
4294            "CREATE USER acme.alice PASSWORD 'super-secret' ROLE read",
4295            "ALTER USER alice PASSWORD 'super-secret'",
4296            "AlTeR UsEr acme.alice PaSsWoRd 'super-secret'",
4297            "EXPLAIN CREATE USER alice PASSWORD 'super-secret' ROLE read",
4298            "EXPLAIN ALTER USER alice PASSWORD 'super-secret'",
4299            "ALTER USER alice PASSWORD 'unterminated",
4300        ] {
4301            let redacted = redact_sql_for_slow_log(sql);
4302            assert!(!redacted.contains("super-secret"), "leaked from {sql}");
4303            assert!(!redacted.contains("unterminated"), "leaked from {sql}");
4304        }
4305        assert_eq!(
4306            redact_sql_for_slow_log("SELECT password FROM accounts"),
4307            "SELECT password FROM accounts"
4308        );
4309    }
4310
4311    #[test]
4312    fn nested_reads_need_select_on_the_inner_table() {
4313        use crate::auth::privileges::{Action, GrantPrincipal, Resource};
4314        use crate::auth::UserId;
4315        let (runtime, store) = runtime_with_store("ro", Role::Read);
4316        runtime
4317            .execute_query("CREATE TABLE gate_open (a INTEGER)")
4318            .expect("create");
4319        runtime
4320            .execute_query("CREATE TABLE gate_closed (b INTEGER)")
4321            .expect("create");
4322        // One explicit grant switches the legacy fallback off, so `ro`
4323        // may read exactly `gate_open`.
4324        store
4325            .grant(
4326                &UserId::from_parts(None, "admin"),
4327                Role::Admin,
4328                GrantPrincipal::User(UserId::from_parts(None, "ro")),
4329                Resource::table_from_name("gate_open"),
4330                vec![Action::Select],
4331                false,
4332                None,
4333            )
4334            .expect("grant");
4335        let _identity = IdentityGuard::install("ro", Role::Read);
4336        runtime
4337            .execute_query("SELECT * FROM (SELECT a FROM gate_open) s")
4338            .expect("derived table over a granted table is fine");
4339        // The outer statement names only the synthetic subquery table, so
4340        // the inner table used to be read with no check at all.
4341        for sql in [
4342            "SELECT * FROM (SELECT b FROM gate_closed) s",
4343            "SELECT a FROM gate_open WHERE a IN (SELECT b FROM gate_closed)",
4344        ] {
4345            let err = runtime
4346                .execute_query(sql)
4347                .expect_err("nested read of an ungranted table must be refused");
4348            assert!(
4349                err.to_string().contains("permission denied"),
4350                "{sql}: unexpected error: {err}"
4351            );
4352        }
4353    }
4354
4355    #[test]
4356    fn policy_listings_are_self_or_policy_management() {
4357        let (runtime, store) = runtime_with_store("ro", Role::Read);
4358        store.create_user("other", "pw", Role::Read).expect("user");
4359        let _identity = IdentityGuard::install("ro", Role::Read);
4360        runtime
4361            .execute_query("SHOW EFFECTIVE PERMISSIONS FOR ro")
4362            .expect("a principal may inspect its own permissions");
4363        let err = runtime
4364            .execute_query("SHOW EFFECTIVE PERMISSIONS FOR other")
4365            .expect_err("inspecting another principal is policy management");
4366        assert!(
4367            err.to_string().contains("permission denied"),
4368            "unexpected error: {err}"
4369        );
4370    }
4371
4372    #[test]
4373    fn secret_columns_stay_masked_for_readers_without_secret_read() {
4374        use reddb_types::Value;
4375        let (runtime, store) = runtime_with_store("ro", Role::Read);
4376        store.create_user("root", "pw", Role::Admin).expect("admin");
4377        store.ensure_vault_secret_key();
4378        runtime
4379            .execute_query(
4380                "INSERT INTO creds_gate (name, token) VALUES ('stripe', SECRET('sk_live_abc'))",
4381            )
4382            .expect("insert");
4383
4384        let token_for = |username: &str, role: Role| {
4385            let _identity = IdentityGuard::install(username, role);
4386            let result = runtime
4387                .execute_query("SELECT name, token FROM creds_gate")
4388                .expect("select");
4389            result.result.records[0]
4390                .get("token")
4391                .cloned()
4392                .expect("token column")
4393        };
4394        // Ordinary SELECT stays masked for every role. Plaintext retrieval
4395        // requires an explicit reveal operation.
4396        assert!(
4397            matches!(token_for("ro", Role::Read), Value::Secret(_)),
4398            "a read-role principal must see the column masked"
4399        );
4400        assert!(matches!(token_for("root", Role::Admin), Value::Secret(_)));
4401    }
4402
4403    #[test]
4404    fn store_wide_operations_need_the_admin_tier() {
4405        let runtime = runtime_with_user("bob", Role::Write);
4406        let _identity = IdentityGuard::install("bob", Role::Write);
4407        // These fell through the gate's wildcard arm, so a write-role
4408        // principal could scrub or vacuum the store.
4409        for sql in ["VACUUM", "SCRUB"] {
4410            let err = runtime
4411                .execute_query(sql)
4412                .expect_err("store-wide operation must be refused for a non-admin");
4413            assert!(
4414                err.to_string().contains("permission denied"),
4415                "{sql}: unexpected error: {err}"
4416            );
4417        }
4418    }
4419
4420    #[test]
4421    fn explain_needs_the_privilege_of_the_statement_it_plans() {
4422        let runtime = runtime_with_user("ro", Role::Read);
4423        let _identity = IdentityGuard::install("ro", Role::Read);
4424        runtime
4425            .execute_query("EXPLAIN SELECT 1 AS one")
4426            .expect("planning a read is a read");
4427        // EXPLAIN used to bypass the gate entirely, so a read-only
4428        // principal could plan any write and read the schema back.
4429        let err = runtime
4430            .execute_query("EXPLAIN INSERT INTO gate_t (a) VALUES (1)")
4431            .expect_err("planning a write needs the write privilege");
4432        assert!(
4433            err.to_string().contains("permission denied"),
4434            "unexpected EXPLAIN error: {err}"
4435        );
4436    }
4437
4438    #[test]
4439    fn copy_from_a_server_path_is_admin_only() {
4440        let runtime = runtime_with_user("bob", Role::Write);
4441        let _identity = IdentityGuard::install("bob", Role::Write);
4442        // `COPY … FROM '<path>'` opens a file on the *server*, so a
4443        // write-role principal used to be able to read /proc/self/environ
4444        // (admin token, vault certificate, cloud keys) into a table.
4445        let err = runtime
4446            .execute_query("COPY leak FROM '/etc/hostname'")
4447            .expect_err("COPY FROM must be refused for a non-admin");
4448        assert!(
4449            err.to_string().contains("permission denied"),
4450            "unexpected COPY error: {err}"
4451        );
4452    }
4453
4454    #[test]
4455    fn vcs_history_rewrites_are_admin_only() {
4456        let runtime = runtime_with_user("bob", Role::Write);
4457        let _identity = IdentityGuard::install("bob", Role::Write);
4458        // VCS commands were dispatched before the statement frame was built,
4459        // so `RESET HARD TO` ran with no privilege check at all.
4460        let err = runtime
4461            .execute_query("RESET HARD TO 'deadbeef'")
4462            .expect_err("RESET must be refused for a non-admin");
4463        assert!(
4464            err.to_string().contains("permission denied"),
4465            "unexpected RESET error: {err}"
4466        );
4467    }
4468
4469    #[test]
4470    fn ai_provider_config_writes_are_admin_only() {
4471        let runtime = runtime_with_user("bob", Role::Write);
4472        let _identity = IdentityGuard::install("bob", Role::Write);
4473        // This namespace decides which vault secret is sent, as a bearer, to
4474        // which host — the exfiltration primitive behind the SET CONFIG gap.
4475        let err = runtime
4476            .execute_query(
4477                "SET CONFIG ai.providers.openai.tokens.default.secret_ref = 'red.secret.aes_key'",
4478            )
4479            .expect_err("AI provider config must be refused for a non-admin");
4480        assert!(
4481            err.to_string().contains("permission denied"),
4482            "unexpected SET CONFIG error: {err}"
4483        );
4484    }
4485
4486    #[test]
4487    fn engine_internal_vault_keys_are_not_writable_through_set_secret() {
4488        let runtime = runtime_with_user("root", Role::Admin);
4489        let _identity = IdentityGuard::install("root", Role::Admin);
4490        // Even an admin must not overwrite the IAM policy blob (an allow-all
4491        // policy would survive a restart) or the `SECRET()` master key
4492        // (rotating it destroys every encrypted column value).
4493        for key in [
4494            "red.iam.policies",
4495            "red.iam.attachments.users",
4496            "red.secret.aes_key",
4497        ] {
4498            let err = runtime
4499                .execute_query(&format!("SET SECRET {key} = 'x'"))
4500                .expect_err("engine-internal vault key must be refused");
4501            assert!(
4502                err.to_string().contains("engine-internal"),
4503                "unexpected error for {key}: {err}"
4504            );
4505        }
4506    }
4507}