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: self.execute_table_with_having_exists(
981                        table_with_rls,
982                        &frame,
983                        Some(frame.row_arena()),
984                    )?,
985                    affected_rows: 0,
986                    statement_type: "select",
987                    bookmark: None,
988                    notice: None,
989                })
990            }
991            QueryExpr::Join(join) => {
992                // Fold per-table RLS filters into each `QueryExpr::Table`
993                // leaf of the join tree before executing. Without this
994                // the join executor scans both tables raw and ignores
995                // policies — a `WITHIN TENANT 'x'` against a join of
996                // two tenant-scoped tables would leak cross-tenant rows.
997                // When any leaf has RLS enabled and zero matching policy,
998                // short-circuit to an empty join result instead of
999                // emitting a contradiction filter.
1000                let join_with_rls = match self.authorize_relational_join_select(
1001                    join,
1002                    &frame as &dyn super::statement_frame::ReadFrame,
1003                )? {
1004                    Some(j) => j,
1005                    None => {
1006                        return Ok(RuntimeQueryResult {
1007                            query: query.to_string(),
1008                            mode,
1009                            statement,
1010                            engine: "runtime-join-rls",
1011                            result: crate::storage::query::unified::UnifiedResult::empty(),
1012                            affected_rows: 0,
1013                            statement_type: "select",
1014                            bookmark: None,
1015                            notice: None,
1016                        });
1017                    }
1018                };
1019                Ok(RuntimeQueryResult {
1020                    query: query.to_string(),
1021                    mode,
1022                    statement,
1023                    engine: "runtime-join",
1024                    result: execute_runtime_join_query(self, &join_with_rls)?,
1025                    affected_rows: 0,
1026                    statement_type: "select",
1027                    bookmark: None,
1028                    notice: None,
1029                })
1030            }
1031            QueryExpr::Vector(vector) => Ok(RuntimeQueryResult {
1032                query: query.to_string(),
1033                mode,
1034                statement,
1035                engine: "runtime-vector",
1036                result: execute_runtime_vector_query(self, &vector)?,
1037                affected_rows: 0,
1038                statement_type: "select",
1039                bookmark: None,
1040                notice: None,
1041            }),
1042            QueryExpr::Hybrid(hybrid) => Ok(RuntimeQueryResult {
1043                query: query.to_string(),
1044                mode,
1045                statement,
1046                engine: "runtime-hybrid",
1047                result: execute_runtime_hybrid_query(self, &hybrid)?,
1048                affected_rows: 0,
1049                statement_type: "select",
1050                bookmark: None,
1051                notice: None,
1052            }),
1053            QueryExpr::RankOf(ref rank) => self.execute_rank_of(query, rank),
1054            QueryExpr::ApproxRankOf(ref rank) => self.execute_approx_rank_of(query, rank),
1055            QueryExpr::RankRange(ref range) => self.execute_rank_range(query, range),
1056            // DML execution
1057            QueryExpr::Insert(ref insert) if super::red_schema::is_virtual_table(&insert.table) => {
1058                Err(RedDBError::Query(
1059                    super::red_schema::READ_ONLY_ERROR.to_string(),
1060                ))
1061            }
1062            QueryExpr::Update(ref update) if super::red_schema::is_virtual_table(&update.table) => {
1063                Err(RedDBError::Query(
1064                    super::red_schema::READ_ONLY_ERROR.to_string(),
1065                ))
1066            }
1067            // The retention sweeper's scoped DELETE is the only write that may
1068            // reach the physical `red.control_events` ledger (issue #2900).
1069            QueryExpr::Delete(ref delete)
1070                if super::red_schema::is_virtual_table(&delete.table)
1071                    && !super::retention_sweeper::is_retention_delete(&delete.table) =>
1072            {
1073                Err(RedDBError::Query(
1074                    super::red_schema::READ_ONLY_ERROR.to_string(),
1075                ))
1076            }
1077            QueryExpr::Insert(ref insert) => self.execute_insert(query, insert),
1078            QueryExpr::Update(ref update) => self
1079                .with_deferred_store_wal_for_dml(self.update_may_emit_events(update), || {
1080                    self.execute_update(query, update)
1081                }),
1082            QueryExpr::Delete(ref delete) => self
1083                .with_deferred_store_wal_for_dml(self.delete_may_emit_events(delete), || {
1084                    self.execute_delete(query, delete)
1085                }),
1086            // DDL execution
1087            QueryExpr::CreateTable(ref create) => self.execute_create_table(query, create),
1088            QueryExpr::CreateCollection(ref create) => {
1089                self.execute_create_collection(query, create)
1090            }
1091            QueryExpr::CreateVector(ref create) => self.execute_create_vector(query, create),
1092            QueryExpr::DropTable(ref drop_tbl) => self.execute_drop_table(query, drop_tbl),
1093            QueryExpr::DropGraph(ref drop_graph) => self.execute_drop_graph(query, drop_graph),
1094            QueryExpr::DropVector(ref drop_vector) => self.execute_drop_vector(query, drop_vector),
1095            QueryExpr::DropDocument(ref drop_document) => {
1096                self.execute_drop_document(query, drop_document)
1097            }
1098            QueryExpr::DropKv(ref drop_kv) => self.execute_drop_kv(query, drop_kv),
1099            QueryExpr::DropCollection(ref drop_collection) => {
1100                self.execute_drop_collection(query, drop_collection)
1101            }
1102            QueryExpr::Truncate(ref truncate) => self.execute_truncate(query, truncate),
1103            QueryExpr::AlterTable(ref alter) => self.execute_alter_table(query, alter),
1104            QueryExpr::CreateVcsRef(ref create) => self.execute_create_vcs_ref(query, create),
1105            QueryExpr::DropVcsRef(ref drop_ref) => self.execute_drop_vcs_ref(query, drop_ref),
1106            QueryExpr::ForkStore(ref fork) => self.execute_fork_store(query, fork),
1107            QueryExpr::PromoteFork(ref promote_fork) => {
1108                self.execute_promote_fork(query, promote_fork)
1109            }
1110            QueryExpr::DropFork(ref drop_fork) => self.execute_drop_fork(query, drop_fork),
1111            QueryExpr::ExplainAlter(ref explain) => self.execute_explain_alter(query, explain),
1112            // Graph analytics commands
1113            QueryExpr::GraphCommand(ref cmd) => self.execute_graph_command(query, cmd),
1114            // Search commands
1115            QueryExpr::SearchCommand(ref cmd) => self.execute_search_command(query, cmd),
1116            // ASK: RAG query with LLM synthesis
1117            QueryExpr::Ask(ref ask) => self.execute_ask(query, ask),
1118            QueryExpr::CreateIndex(ref create_idx) => self.execute_create_index(query, create_idx),
1119            QueryExpr::DropIndex(ref drop_idx) => self.execute_drop_index(query, drop_idx),
1120            QueryExpr::ProbabilisticCommand(ref cmd) => {
1121                self.execute_probabilistic_command(query, cmd)
1122            }
1123            // Time-series DDL
1124            QueryExpr::CreateTimeSeries(ref ts) => self.execute_create_timeseries(query, ts),
1125            QueryExpr::CreateMetric(ref metric) => self.execute_create_metric(query, metric),
1126            QueryExpr::AlterMetric(ref alter) => self.execute_alter_metric(query, alter),
1127            QueryExpr::CreateSlo(ref slo) => self.execute_create_slo(query, slo),
1128            QueryExpr::DropTimeSeries(ref ts) => self.execute_drop_timeseries(query, ts),
1129            // Queue DDL and commands
1130            QueryExpr::CreateQueue(ref q) => self.execute_create_queue(query, q),
1131            QueryExpr::AlterQueue(ref q) => self.execute_alter_queue(query, q),
1132            QueryExpr::DropQueue(ref q) => self.execute_drop_queue(query, q),
1133            QueryExpr::QueueSelect(ref q) => self.execute_queue_select(query, q),
1134            QueryExpr::QueueCommand(ref cmd) => self
1135                .with_deferred_store_wal_if_transaction(|| self.execute_queue_command(query, cmd)),
1136            QueryExpr::EventsBackfill(ref backfill) => {
1137                self.execute_events_backfill(query, backfill)
1138            }
1139            QueryExpr::EventsBackfillStatus { ref collection } => Err(RedDBError::Query(format!(
1140                "EVENTS BACKFILL STATUS for '{collection}' is not implemented in this slice"
1141            ))),
1142            QueryExpr::KvCommand(ref cmd) => self.execute_kv_command(query, cmd),
1143            QueryExpr::ConfigCommand(ref cmd) => self.execute_config_command(query, cmd),
1144            QueryExpr::CreateTree(ref tree) => self.execute_create_tree(query, tree),
1145            QueryExpr::DropTree(ref tree) => self.execute_drop_tree(query, tree),
1146            QueryExpr::TreeCommand(ref cmd) => self.execute_tree_command(query, cmd),
1147            // SET CONFIG key = value
1148            QueryExpr::SetConfig { ref key, ref value } => {
1149                if key.starts_with("red.secret.") {
1150                    return Err(RedDBError::Query(
1151                        "red.secret.* is reserved for vault secrets; use SET SECRET".to_string(),
1152                    ));
1153                }
1154                if key.starts_with("red.secrets.") {
1155                    return Err(RedDBError::Query(
1156                        "red.secrets.* is reserved for vault secrets; use SET SECRET".to_string(),
1157                    ));
1158                }
1159                if key.starts_with("red.") {
1160                    return Err(RedDBError::Query(format!(
1161                        "config key `{key}` is invalid inside red.config: omit the redundant `red.` prefix"
1162                    )));
1163                }
1164                // ADR-0068 §5 clean break: reject the removed AI config keys
1165                // (old `default.*` provider/model and per-alias base_url shape)
1166                // with a didactic error naming the replacement key.
1167                crate::ai::validate_ai_config_key_on_write(key)?;
1168                let control_events_retention = key == super::control_events_retention::CONFIG_KEY;
1169                if control_events_retention {
1170                    let raw = match value {
1171                        Value::Text(text) => text.to_string(),
1172                        other => other.to_string(),
1173                    };
1174                    super::control_events_retention::parse_retention(&raw)
1175                        .map_err(RedDBError::Query)?;
1176                }
1177                // The managed-config guardrail runs first: it owns the
1178                // didactic error and the `config:write` control event for
1179                // registry-managed keys. The generic capability gate below
1180                // then covers every other key.
1181                match self.check_managed_config_write_for_set_config(key) {
1182                    Err(err) => Err(err),
1183                    Ok(()) => {
1184                        self.check_config_write_privilege(key)?;
1185                        let store = self.inner.db.store();
1186                        let json_val = match value {
1187                            Value::Text(s) => crate::serde_json::Value::String(s.to_string()),
1188                            Value::Integer(n) => crate::serde_json::Value::Number(*n as f64),
1189                            Value::Float(n) => crate::serde_json::Value::Number(*n),
1190                            Value::Boolean(b) => crate::serde_json::Value::Bool(*b),
1191                            _ => crate::serde_json::Value::String(value.to_string()),
1192                        };
1193                        store
1194                            .try_set_config_tree(key, &json_val)
1195                            .map_err(RedDBError::from)?;
1196                        update_current_config_value(key, value.clone());
1197                        if control_events_retention {
1198                            self.apply_control_events_retention()?;
1199                        }
1200                        // Config changes can flip runtime behavior mid-session
1201                        // (auto_decrypt, auto_encrypt, etc.) — invalidate the
1202                        // result cache so subsequent reads re-execute against
1203                        // the new config.
1204                        self.invalidate_result_cache();
1205                        Ok(RuntimeQueryResult::ok_message(
1206                            query.to_string(),
1207                            &format!("config set: {key}"),
1208                            "set",
1209                        ))
1210                    }
1211                }
1212            }
1213            // SET SECRET key = value
1214            QueryExpr::SetSecret { ref key, ref value } => {
1215                if key.starts_with("red.config.") {
1216                    return Err(RedDBError::Query(
1217                        "red.config.* is reserved for config; use SET CONFIG".to_string(),
1218                    ));
1219                }
1220                reject_engine_internal_vault_key(key)?;
1221                if key.starts_with("red.secret.") {
1222                    self.set_internal_provider_secret(
1223                        key,
1224                        if value.is_null() {
1225                            None
1226                        } else {
1227                            Some(secret_sql_value_to_string(value)?)
1228                        },
1229                    )?;
1230                    return Ok(RuntimeQueryResult::ok_message(
1231                        query.to_string(),
1232                        &format!("secret set: {key}"),
1233                        "set_secret",
1234                    ));
1235                }
1236                let value = if value.is_null() {
1237                    None
1238                } else {
1239                    Some(secret_sql_value_to_string(value)?)
1240                };
1241                self.set_user_secret(key, value.clone())?;
1242                update_current_secret_value(key, value);
1243                Ok(RuntimeQueryResult::ok_message(
1244                    query.to_string(),
1245                    &format!("secret set: {key}"),
1246                    "set_secret",
1247                ))
1248            }
1249            // DELETE SECRET key
1250            QueryExpr::DeleteSecret { ref key } => {
1251                reject_engine_internal_vault_key(key)?;
1252                if key.starts_with("red.secret.") {
1253                    self.set_internal_provider_secret(key, None)?;
1254                    return Ok(RuntimeQueryResult::ok_message(
1255                        query.to_string(),
1256                        &format!("secret deleted: {key}"),
1257                        "delete_secret",
1258                    ));
1259                }
1260                self.set_user_secret(key, None)?;
1261                update_current_secret_value(key, None);
1262                Ok(RuntimeQueryResult::ok_message(
1263                    query.to_string(),
1264                    &format!("secret deleted: {key}"),
1265                    "delete_secret",
1266                ))
1267            }
1268            // SET KV key = value — plain (non-encrypted) user KV entry (#1602)
1269            QueryExpr::SetKv { ref key, ref value } => {
1270                let auth_store = self.inner.auth_store.read().clone().ok_or_else(|| {
1271                    RedDBError::Query("SET KV requires an auth store".to_string())
1272                })?;
1273                self.check_kv_write_privilege(&auth_store, key)?;
1274                // `SET KV k = NULL` deletes, mirroring `SET SECRET`.
1275                if matches!(value, Value::Null) {
1276                    auth_store.plain_kv_delete(key);
1277                    update_current_kv_value(key, None);
1278                    self.invalidate_result_cache();
1279                    return Ok(RuntimeQueryResult::ok_message(
1280                        query.to_string(),
1281                        &format!("kv deleted: {key}"),
1282                        "delete_kv",
1283                    ));
1284                }
1285                let value = secret_sql_value_to_string(value)?;
1286                auth_store.plain_kv_set(key.clone(), value.clone());
1287                update_current_kv_value(key, Some(value));
1288                self.invalidate_result_cache();
1289                Ok(RuntimeQueryResult::ok_message(
1290                    query.to_string(),
1291                    &format!("kv set: {key}"),
1292                    "set_kv",
1293                ))
1294            }
1295            // DELETE KV key
1296            QueryExpr::DeleteKv { ref key } => {
1297                let auth_store = self.inner.auth_store.read().clone().ok_or_else(|| {
1298                    RedDBError::Query("DELETE KV requires an auth store".to_string())
1299                })?;
1300                self.check_kv_write_privilege(&auth_store, key)?;
1301                let deleted = auth_store.plain_kv_delete(key);
1302                if deleted {
1303                    update_current_kv_value(key, None);
1304                }
1305                self.invalidate_result_cache();
1306                Ok(RuntimeQueryResult::ok_message(
1307                    query.to_string(),
1308                    &format!("kv deleted: {key}"),
1309                    if deleted {
1310                        "delete_kv"
1311                    } else {
1312                        "delete_kv_not_found"
1313                    },
1314                ))
1315            }
1316            QueryExpr::Scrub { background, budget } => {
1317                self.execute_scrub_query(query, mode, background, budget)
1318            }
1319            // SHOW SECRET[S] [prefix]
1320            QueryExpr::ShowSecrets { ref prefix } => {
1321                let result = self.show_user_secrets(prefix.as_deref())?;
1322                Ok(RuntimeQueryResult {
1323                    query: query.to_string(),
1324                    mode,
1325                    statement: "show_secrets",
1326                    engine: "runtime-secret",
1327                    result,
1328                    affected_rows: 0,
1329                    statement_type: "select",
1330                    bookmark: None,
1331                    notice: None,
1332                })
1333            }
1334            // SHOW CONFIG [prefix] [AS JSON|FORMAT JSON]
1335            QueryExpr::ShowConfig {
1336                ref prefix,
1337                as_json,
1338            } => {
1339                if let Some(prefix) = prefix {
1340                    super::impl_config::validate_red_config_content_key("red.config", prefix)?;
1341                }
1342                self.check_config_read_privilege()?;
1343                let store = self.inner.db.store();
1344                let all_collections = store.list_collections();
1345                if !all_collections.contains(&"red.config".to_string()) {
1346                    if as_json {
1347                        return Ok(show_config_json_result(
1348                            query,
1349                            mode,
1350                            prefix,
1351                            crate::serde_json::Value::Object(crate::serde_json::Map::new()),
1352                        ));
1353                    }
1354                    let result = UnifiedResult::with_columns(vec!["key".into(), "value".into()]);
1355                    return Ok(RuntimeQueryResult {
1356                        query: query.to_string(),
1357                        mode,
1358                        statement: "show_config",
1359                        engine: "runtime-config",
1360                        result,
1361                        affected_rows: 0,
1362                        statement_type: "select",
1363                        bookmark: None,
1364                        notice: None,
1365                    });
1366                }
1367                let manager = store
1368                    .get_collection("red.config")
1369                    .ok_or_else(|| RedDBError::NotFound("red.config".to_string()))?;
1370                let mut latest = std::collections::BTreeMap::<String, (u64, Value, Value)>::new();
1371                // Under bounded disk residency a checkpointed row is on disk,
1372                // and `query_all` only walks the resident ones: a value set
1373                // before the last restart was missing from this listing while
1374                // the engine still applied it.
1375                manager
1376                    .try_scan_for_each(None, usize::MAX, |entity| {
1377                        let EntityData::Row(ref row) = entity.data else {
1378                            return true;
1379                        };
1380                        let Some(ref named) = row.named else {
1381                            return true;
1382                        };
1383                        let key_val = named.get("key").cloned().unwrap_or(Value::Null);
1384                        let val = named.get("value").cloned().unwrap_or(Value::Null);
1385                        let key_str = match &key_val {
1386                            Value::Text(s) => s.as_ref(),
1387                            _ => return true,
1388                        };
1389                        if key_str == super::function_catalog::REGISTRY_KEY {
1390                            return true;
1391                        }
1392                        if let Some(ref pfx) = prefix {
1393                            if !key_str.starts_with(pfx.as_str()) {
1394                                return true;
1395                            }
1396                        }
1397                        let entity_id = entity.id.raw();
1398                        match latest.get(key_str) {
1399                            Some((prev_id, _, _)) if *prev_id > entity_id => {}
1400                            _ => {
1401                                latest.insert(key_str.to_string(), (entity_id, key_val, val));
1402                            }
1403                        }
1404                        true
1405                    })
1406                    .map_err(RedDBError::from)?;
1407                if as_json {
1408                    let mut tree = crate::serde_json::Value::Object(crate::serde_json::Map::new());
1409                    for (key, (_, _, val)) in latest {
1410                        let relative = match prefix {
1411                            Some(pfx) if key == *pfx => "",
1412                            Some(pfx) => key
1413                                .strip_prefix(pfx.as_str())
1414                                .and_then(|tail| tail.strip_prefix('.'))
1415                                .unwrap_or(key.as_str()),
1416                            None => key.as_str(),
1417                        };
1418                        insert_config_json_path(&mut tree, relative, val.to_json());
1419                    }
1420                    return Ok(show_config_json_result(query, mode, prefix, tree));
1421                }
1422                let mut result = UnifiedResult::with_columns(vec!["key".into(), "value".into()]);
1423                for (_, key_val, val) in latest.into_values() {
1424                    let mut record = UnifiedRecord::new();
1425                    record.set("key", key_val);
1426                    record.set("value", val);
1427                    result.push(record);
1428                }
1429                Ok(RuntimeQueryResult {
1430                    query: query.to_string(),
1431                    mode,
1432                    statement: "show_config",
1433                    engine: "runtime-config",
1434                    result,
1435                    affected_rows: 0,
1436                    statement_type: "select",
1437                    bookmark: None,
1438                    notice: None,
1439                })
1440            }
1441            // Session-local multi-tenancy handle (Phase 2.5.3).
1442            //
1443            // SET TENANT 'id' / SET TENANT NULL / RESET TENANT — writes
1444            // the thread-local; SHOW TENANT returns it. Paired with the
1445            // CURRENT_TENANT() scalar for use in RLS policies.
1446            QueryExpr::SetTenant(ref value) => {
1447                self.check_set_tenant_privilege(value.as_deref())?;
1448                match value {
1449                    Some(id) => set_current_tenant(id.clone()),
1450                    None => clear_current_tenant(),
1451                }
1452                Ok(RuntimeQueryResult::ok_message(
1453                    query.to_string(),
1454                    &match value {
1455                        Some(id) => format!("tenant set: {id}"),
1456                        None => "tenant cleared".to_string(),
1457                    },
1458                    "set_tenant",
1459                ))
1460            }
1461            QueryExpr::ShowTenant => {
1462                let mut result = UnifiedResult::with_columns(vec!["tenant".into()]);
1463                let mut record = UnifiedRecord::new();
1464                record.set(
1465                    "tenant",
1466                    current_tenant().map(Value::text).unwrap_or(Value::Null),
1467                );
1468                result.push(record);
1469                Ok(RuntimeQueryResult {
1470                    query: query.to_string(),
1471                    mode,
1472                    statement: "show_tenant",
1473                    engine: "runtime-tenant",
1474                    result,
1475                    affected_rows: 0,
1476                    statement_type: "select",
1477                    bookmark: None,
1478                    notice: None,
1479                })
1480            }
1481            // Transaction control (Phase 2.3 PG parity).
1482            //
1483            // BEGIN allocates a real `Xid` and stores a `TxnContext` keyed by
1484            // the current connection's id. COMMIT/ROLLBACK release it through
1485            // the `SnapshotManager` so future snapshots see the correct set of
1486            // active/aborted transactions.
1487            //
1488            // Tuple stamping (xmin/xmax) and read-path visibility filtering
1489            // land in Phase 2.3.2 — this dispatch only manages the snapshot
1490            // registry. Statements running outside a TxnContext still behave
1491            // as autocommit (xid=0 → visible to every snapshot).
1492            QueryExpr::TransactionControl(ref ctl) => {
1493                use crate::storage::transaction::IsolationLevel;
1494                use reddb_rql::ast::TxnControl;
1495
1496                // Phase 2.3 keys transactions by a thread-local connection id.
1497                // The stdio/gRPC paths wire a real per-connection id later;
1498                // for embedded use (one RedDBRuntime per process-ish caller)
1499                // we fall back to a deterministic placeholder.
1500                let conn_id = current_connection_id();
1501
1502                let (kind, msg) = match ctl {
1503                    TxnControl::Begin(requested_isolation) => {
1504                        let store = self.inner.db.store();
1505                        let _publication = store.vault_publication_lock.lock();
1506                        if self.inner.transaction_state.in_transaction(conn_id) {
1507                            return Err(RedDBError::Query("transaction already active".into()));
1508                        }
1509                        let isolation = requested_isolation
1510                            .map(IsolationLevel::from)
1511                            .unwrap_or(IsolationLevel::SnapshotIsolation);
1512                        let xid = self.inner.transaction_state.begin(conn_id, isolation);
1513                        ("begin", format!("BEGIN — xid={xid} (snapshot isolation)"))
1514                    }
1515                    TxnControl::Commit => {
1516                        let has_vault_writes = self
1517                            .inner
1518                            .pending_vault_writes
1519                            .read()
1520                            .get(&conn_id)
1521                            .is_some_and(|writes| !writes.is_empty());
1522                        let store = self.inner.db.store();
1523                        let has_graph_contracts = self
1524                            .db()
1525                            .collection_contracts()
1526                            .iter()
1527                            .any(|contract| contract.graph_contract.is_some());
1528                        let _vault_guard = (has_vault_writes || has_graph_contracts)
1529                            .then(|| store.vault_publication_lock.lock());
1530                        if has_graph_contracts && self.current_xid().is_some() {
1531                            if let Err(error) = self.validate_graph_contracts_at_commit() {
1532                                self.rollback_connection(conn_id)?;
1533                                return Err(error);
1534                            }
1535                        }
1536                        let context = self.inner.transaction_state.commit(conn_id, |ctx| {
1537                            let mut own_xids = std::collections::HashSet::new();
1538                            own_xids.insert(ctx.xid);
1539                            for (_, sub) in &ctx.savepoints {
1540                                own_xids.insert(*sub);
1541                            }
1542                            for sub in &ctx.released_sub_xids {
1543                                own_xids.insert(*sub);
1544                            }
1545                            if let Err(err) = self.check_table_row_write_conflicts(
1546                                conn_id,
1547                                &ctx.snapshot,
1548                                &own_xids,
1549                                ctx.isolation,
1550                            ) {
1551                                let undo = self.revive_pending_versioned_updates(conn_id);
1552                                self.revive_pending_tombstones(conn_id);
1553                                self.discard_pending_kv_watch_events(conn_id);
1554                                self.discard_pending_queue_wakes(conn_id);
1555                                self.discard_pending_store_wal_actions(conn_id);
1556                                self.release_pending_claim_locks(conn_id);
1557                                undo?;
1558                                return Err(err);
1559                            }
1560                            if let Err(err) = self.check_queue_dedup_write_conflicts(
1561                                conn_id,
1562                                &ctx.snapshot,
1563                                &own_xids,
1564                            ) {
1565                                let undo = self.revive_pending_versioned_updates(conn_id);
1566                                self.revive_pending_tombstones(conn_id);
1567                                self.discard_pending_queue_dedup(conn_id);
1568                                self.discard_pending_kv_watch_events(conn_id);
1569                                self.discard_pending_queue_wakes(conn_id);
1570                                self.discard_pending_store_wal_actions(conn_id);
1571                                self.release_pending_claim_locks(conn_id);
1572                                undo?;
1573                                return Err(err);
1574                            }
1575                            if let Err(err) = self.prepare_pending_vault_writes(conn_id, ctx) {
1576                                let undo = self.revive_pending_versioned_updates(conn_id);
1577                                self.revive_pending_tombstones(conn_id);
1578                                self.discard_pending_queue_dedup(conn_id);
1579                                self.discard_pending_kv_watch_events(conn_id);
1580                                self.discard_pending_queue_wakes(conn_id);
1581                                self.discard_pending_store_wal_actions(conn_id);
1582                                self.release_pending_claim_locks(conn_id);
1583                                undo?;
1584                                return Err(err);
1585                            }
1586                            // Validate before taking the publication fence:
1587                            // conflict rollback can acquire index topology.
1588                            // Retain the fence through WAL and visibility so a
1589                            // checkpoint cannot discard a durable commit's WAL.
1590                            let publication = store.vault_publication_lock.lock();
1591                            self.restore_pending_write_stamps(conn_id);
1592                            if let Err(err) = self.flush_pending_store_wal_actions(conn_id) {
1593                                drop(publication);
1594                                let undo = self.revive_pending_versioned_updates(conn_id);
1595                                self.revive_pending_tombstones(conn_id);
1596                                self.discard_pending_queue_dedup(conn_id);
1597                                self.discard_pending_kv_watch_events(conn_id);
1598                                self.discard_pending_queue_wakes(conn_id);
1599                                self.release_pending_claim_locks(conn_id);
1600                                undo?;
1601                                return Err(err);
1602                            }
1603                            #[cfg(test)]
1604                            self.index_store_ref().mutation_test_hook(
1605                                "",
1606                                super::index_store::MutationTestPhase::TransactionWalCommitted,
1607                            );
1608                            Ok(publication)
1609                        });
1610                        if context.is_err() {
1611                            self.discard_pending_vault_writes(conn_id)?;
1612                        }
1613                        let context = context?;
1614                        match context {
1615                            Some(ctx) => {
1616                                self.finalize_pending_vault_writes(conn_id);
1617                                self.finalize_pending_versioned_updates(conn_id);
1618                                self.finalize_pending_tombstones(conn_id);
1619                                self.finalize_pending_queue_dedup(conn_id);
1620                                self.finalize_pending_kv_watch_events(conn_id);
1621                                self.finalize_pending_queue_wakes(conn_id);
1622                                self.release_pending_claim_locks(conn_id);
1623                                self.recover_transactional_replication().map_err(|error| {
1624                                    RedDBError::Internal(format!(
1625                                        "commit is locally durable; replication publication is pending: {error}"
1626                                    ))
1627                                })?;
1628                                ("commit", format!("COMMIT — xid={} committed", ctx.xid))
1629                            }
1630                            None => (
1631                                "commit",
1632                                "COMMIT outside transaction — no-op (autocommit)".to_string(),
1633                            ),
1634                        }
1635                    }
1636                    TxnControl::Rollback => match self.rollback_connection(conn_id)? {
1637                        Some(ctx) => ("rollback", format!("ROLLBACK — xid={} aborted", ctx.xid)),
1638                        None => (
1639                            "rollback",
1640                            "ROLLBACK outside transaction — no-op (autocommit)".to_string(),
1641                        ),
1642                    },
1643                    // Phase 2.3.2e: savepoints map onto sub-xids. Each
1644                    // SAVEPOINT allocates a fresh xid and pushes it
1645                    // onto the per-txn stack so subsequent writes can
1646                    // be selectively rolled back. RELEASE pops without
1647                    // aborting; ROLLBACK TO aborts the sub-xid (and
1648                    // any nested ones) + revives their tombstones.
1649                    TxnControl::Savepoint(name) => {
1650                        match self.inner.transaction_state.savepoint(conn_id, name) {
1651                            Some(sub) => ("savepoint", format!("SAVEPOINT {name} — sub_xid={sub}")),
1652                            None => (
1653                                "savepoint",
1654                                "SAVEPOINT outside transaction — no-op".to_string(),
1655                            ),
1656                        }
1657                    }
1658                    TxnControl::ReleaseSavepoint(name) => {
1659                        match self
1660                            .inner
1661                            .transaction_state
1662                            .release_savepoint(conn_id, name)?
1663                        {
1664                            Some(released) => (
1665                                "release_savepoint",
1666                                format!("RELEASE SAVEPOINT {name} — {released} level(s)"),
1667                            ),
1668                            None => (
1669                                "release_savepoint",
1670                                "RELEASE outside transaction — no-op".to_string(),
1671                            ),
1672                        }
1673                    }
1674                    TxnControl::RollbackToSavepoint(name) => {
1675                        match self
1676                            .inner
1677                            .transaction_state
1678                            .rollback_to_savepoint_with(conn_id, name, |rollback| {
1679                                self.rollback_vault_savepoint(conn_id, rollback.savepoint_xid);
1680                                let reverted_updates = self.revive_versioned_updates_since(
1681                                    conn_id,
1682                                    rollback.savepoint_xid,
1683                                );
1684                                let revived =
1685                                    self.revive_tombstones_since(conn_id, rollback.savepoint_xid);
1686                                reverted_updates.map(|updates| (updates, revived))
1687                            })?
1688                        {
1689                            Some((rollback, (reverted_updates, revived))) => {
1690                                (
1691                                    "rollback_to_savepoint",
1692                                    format!(
1693                                        "ROLLBACK TO SAVEPOINT {name} — aborted {} sub_xid(s), reverted {reverted_updates} update(s), revived {revived} tombstone(s)",
1694                                        rollback.aborted_xids.len(),
1695                                    ),
1696                                )
1697                            }
1698                            None => (
1699                                "rollback_to_savepoint",
1700                                "ROLLBACK TO outside transaction — no-op".to_string(),
1701                            ),
1702                        }
1703                    }
1704                };
1705                Ok(RuntimeQueryResult::ok_message(
1706                    query.to_string(),
1707                    &msg,
1708                    kind,
1709                ))
1710            }
1711            // Schema + Sequence DDL (Phase 1.3 PG parity).
1712            //
1713            // Schemas are lightweight logical namespaces: a CREATE SCHEMA call
1714            // just registers the name in `red.config` under `schema.{name}`.
1715            // Table lookups still happen by collection name; clients using
1716            // `schema.table` qualified names collapse to collection `schema.table`.
1717            //
1718            // Sequences persist a 64-bit counter + metadata (start, increment)
1719            // in `red.config` under `sequence.{name}.*`. Scalar callers
1720            // `nextval('name')` / `currval('name')` arrive with the MVCC phase
1721            // once we have a proper mutating-function dispatch path; for now the
1722            // DDL just establishes the catalog entry so clients don't error.
1723            QueryExpr::CreateSchema(ref q) => {
1724                let store = self.inner.db.store();
1725                let key = format!("schema.{}", q.name);
1726                if store.get_config(&key).is_some() {
1727                    if q.if_not_exists {
1728                        return Ok(RuntimeQueryResult::ok_message(
1729                            query.to_string(),
1730                            &format!("schema {} already exists — skipped", q.name),
1731                            "create_schema",
1732                        ));
1733                    }
1734                    return Err(RedDBError::Internal(format!(
1735                        "schema {} already exists",
1736                        q.name
1737                    )));
1738                }
1739                store.set_config_tree(&key, &crate::serde_json::Value::Bool(true));
1740                Ok(RuntimeQueryResult::ok_message(
1741                    query.to_string(),
1742                    &format!("schema {} created", q.name),
1743                    "create_schema",
1744                ))
1745            }
1746            QueryExpr::DropSchema(ref q) => {
1747                let store = self.inner.db.store();
1748                let key = format!("schema.{}", q.name);
1749                let existed = store.get_config(&key).is_some();
1750                if !existed && !q.if_exists {
1751                    return Err(RedDBError::Internal(format!(
1752                        "schema {} does not exist",
1753                        q.name
1754                    )));
1755                }
1756                // Remove marker from red.config via set to null.
1757                store.set_config_tree(&key, &crate::serde_json::Value::Null);
1758                let suffix = if q.cascade {
1759                    " (CASCADE accepted — tables untouched)"
1760                } else {
1761                    ""
1762                };
1763                Ok(RuntimeQueryResult::ok_message(
1764                    query.to_string(),
1765                    &format!("schema {} dropped{}", q.name, suffix),
1766                    "drop_schema",
1767                ))
1768            }
1769            QueryExpr::CreateSequence(ref q) => {
1770                let store = self.inner.db.store();
1771                let base = format!("sequence.{}", q.name);
1772                let start_key = format!("{base}.start");
1773                let incr_key = format!("{base}.increment");
1774                let curr_key = format!("{base}.current");
1775                if store.get_config(&start_key).is_some() {
1776                    if q.if_not_exists {
1777                        return Ok(RuntimeQueryResult::ok_message(
1778                            query.to_string(),
1779                            &format!("sequence {} already exists — skipped", q.name),
1780                            "create_sequence",
1781                        ));
1782                    }
1783                    return Err(RedDBError::Internal(format!(
1784                        "sequence {} already exists",
1785                        q.name
1786                    )));
1787                }
1788                // Persist start + increment, and set current so the first
1789                // nextval returns `start`.
1790                let initial_current = q.start - q.increment;
1791                store.set_config_tree(
1792                    &start_key,
1793                    &crate::serde_json::Value::Number(q.start as f64),
1794                );
1795                store.set_config_tree(
1796                    &incr_key,
1797                    &crate::serde_json::Value::Number(q.increment as f64),
1798                );
1799                store.set_config_tree(
1800                    &curr_key,
1801                    &crate::serde_json::Value::Number(initial_current as f64),
1802                );
1803                Ok(RuntimeQueryResult::ok_message(
1804                    query.to_string(),
1805                    &format!(
1806                        "sequence {} created (start={}, increment={})",
1807                        q.name, q.start, q.increment
1808                    ),
1809                    "create_sequence",
1810                ))
1811            }
1812            QueryExpr::DropSequence(ref q) => {
1813                let store = self.inner.db.store();
1814                let base = format!("sequence.{}", q.name);
1815                let existed = store.get_config(&format!("{base}.start")).is_some();
1816                if !existed && !q.if_exists {
1817                    return Err(RedDBError::Internal(format!(
1818                        "sequence {} does not exist",
1819                        q.name
1820                    )));
1821                }
1822                for k in ["start", "increment", "current"] {
1823                    store.set_config_tree(&format!("{base}.{k}"), &crate::serde_json::Value::Null);
1824                }
1825                Ok(RuntimeQueryResult::ok_message(
1826                    query.to_string(),
1827                    &format!("sequence {} dropped", q.name),
1828                    "drop_sequence",
1829                ))
1830            }
1831            // Views — CREATE [MATERIALIZED] VIEW (Phase 2.1 PG parity).
1832            //
1833            // The view definition is stored in-memory on RuntimeInner (not
1834            // persisted). SELECTs that reference the view name will substitute
1835            // the stored `QueryExpr` via `resolve_view_reference` during
1836            // planning (same entry point used by table-name resolution).
1837            //
1838            // Materialized views additionally allocate a slot in
1839            // `MaterializedViewCache`; a REFRESH repopulates that slot.
1840            QueryExpr::CreateView(ref q) => {
1841                let mut views = self.inner.views.write();
1842                if views.contains_key(&q.name) && !q.or_replace {
1843                    if q.if_not_exists {
1844                        return Ok(RuntimeQueryResult::ok_message(
1845                            query.to_string(),
1846                            &format!("view {} already exists — skipped", q.name),
1847                            "create_view",
1848                        ));
1849                    }
1850                    return Err(RedDBError::Internal(format!(
1851                        "view {} already exists",
1852                        q.name
1853                    )));
1854                }
1855                views.insert(q.name.clone(), Arc::new(q.clone()));
1856                drop(views);
1857
1858                // Materialized view: register cache slot (data is empty until REFRESH).
1859                if q.materialized {
1860                    use crate::storage::cache::result::{MaterializedViewDef, RefreshPolicy};
1861                    let refresh = match q.refresh_every_ms {
1862                        Some(ms) => RefreshPolicy::Periodic(std::time::Duration::from_millis(ms)),
1863                        None => RefreshPolicy::Manual,
1864                    };
1865                    let dependencies = collect_table_refs(&q.query);
1866                    let def = MaterializedViewDef {
1867                        name: q.name.clone(),
1868                        query: format!("<parsed view {}>", q.name),
1869                        dependencies: dependencies.clone(),
1870                        refresh,
1871                        retention_duration_ms: q.retention_duration_ms,
1872                    };
1873                    self.inner.materialized_views.write().register(def);
1874
1875                    // Issue #593 slice 9a — persist the descriptor to
1876                    // the system catalog so the definition survives a
1877                    // restart. Upsert semantics (delete-then-insert by
1878                    // name) keep the catalog free of duplicate rows
1879                    // across `CREATE OR REPLACE` churn.
1880                    let descriptor =
1881                        crate::runtime::continuous_materialized_view::MaterializedViewDescriptor {
1882                            name: q.name.clone(),
1883                            source_sql: query.to_string(),
1884                            source_collections: dependencies,
1885                            refresh_every_ms: q.refresh_every_ms,
1886                            retention_duration_ms: q.retention_duration_ms,
1887                        };
1888                    let store = self.inner.db.store();
1889                    crate::runtime::continuous_materialized_view::persist_descriptor(
1890                        store.as_ref(),
1891                        &descriptor,
1892                    )?;
1893
1894                    // Issue #594 slice 9b — provision a Table-shaped
1895                    // backing collection named after the view. The
1896                    // rewriter skips materialized views (see
1897                    // `rewrite_view_refs_inner`) so `SELECT FROM v`
1898                    // resolves to this collection directly. Empty
1899                    // until REFRESH wires through it in 9c.
1900                    self.ensure_materialized_view_backing(&q.name)?;
1901                }
1902                // Plan cache may have cached a plan that didn't know about this
1903                // view — invalidate so future references pick up the new binding.
1904                // Result cache gets flushed too: OR REPLACE must not serve a
1905                // prior execution of the obsolete body.
1906                self.invalidate_plan_cache();
1907                self.invalidate_result_cache();
1908
1909                Ok(RuntimeQueryResult::ok_message(
1910                    query.to_string(),
1911                    &format!(
1912                        "{}view {} created",
1913                        if q.materialized { "materialized " } else { "" },
1914                        q.name
1915                    ),
1916                    "create_view",
1917                ))
1918            }
1919            QueryExpr::DropView(ref q) => {
1920                let mut views = self.inner.views.write();
1921                let removed = views.remove(&q.name);
1922                let existed = removed.is_some();
1923                let removed_materialized =
1924                    removed.as_ref().map(|v| v.materialized).unwrap_or(false);
1925                drop(views);
1926                if q.materialized || existed {
1927                    // Try the materialised cache too — silent if absent.
1928                    self.inner.materialized_views.write().remove(&q.name);
1929                    // Issue #593 slice 9a — remove any persisted
1930                    // catalog row. Idempotent: a no-op when the view
1931                    // was never materialized (no row was ever written).
1932                    let store = self.inner.db.store();
1933                    crate::runtime::continuous_materialized_view::remove_by_name(
1934                        store.as_ref(),
1935                        &q.name,
1936                    )?;
1937                }
1938                // Issue #594 slice 9b — drop the backing collection
1939                // that was provisioned at CREATE time. Only mat views
1940                // ever had one; regular views never did.
1941                if removed_materialized || q.materialized {
1942                    self.drop_materialized_view_backing(&q.name)?;
1943                }
1944                // Drop any plan / result cache entries that baked the
1945                // view body into their QueryExpr.
1946                self.invalidate_plan_cache();
1947                self.invalidate_result_cache();
1948                if !existed && !q.if_exists {
1949                    return Err(RedDBError::Internal(format!(
1950                        "view {} does not exist",
1951                        q.name
1952                    )));
1953                }
1954                self.invalidate_plan_cache();
1955                Ok(RuntimeQueryResult::ok_message(
1956                    query.to_string(),
1957                    &format!("view {} dropped", q.name),
1958                    "drop_view",
1959                ))
1960            }
1961            QueryExpr::RefreshMaterializedView(ref q) => {
1962                // Look up the view definition, execute its underlying query,
1963                // and stash the serialized result in the materialised cache.
1964                let view = {
1965                    let views = self.inner.views.read();
1966                    views.get(&q.name).cloned()
1967                };
1968                let view = match view {
1969                    Some(v) => v,
1970                    None => {
1971                        return Err(RedDBError::Internal(format!(
1972                            "view {} does not exist",
1973                            q.name
1974                        )))
1975                    }
1976                };
1977                if !view.materialized {
1978                    return Err(RedDBError::Internal(format!(
1979                        "view {} is not materialized — REFRESH requires \
1980                         CREATE MATERIALIZED VIEW",
1981                        q.name
1982                    )));
1983                }
1984                // Execute the underlying query fresh.
1985                let started = std::time::Instant::now();
1986                let now_ms = std::time::SystemTime::now()
1987                    .duration_since(std::time::UNIX_EPOCH)
1988                    .map(|d| d.as_millis() as u64)
1989                    .unwrap_or(0);
1990                match self.execute_query_expr((*view.query).clone()) {
1991                    Ok(inner_result) => {
1992                        // Issue #595 slice 9c — atomically replace the
1993                        // backing collection's contents under a single
1994                        // WAL group. Concurrent SELECT from the view
1995                        // sees either the prior or new contents, never
1996                        // partial. A crash before the WAL commit lands
1997                        // leaves the prior contents intact on recovery.
1998                        let entities =
1999                            view_records_to_entities(&q.name, &inner_result.result.records);
2000                        let row_count = entities.len() as u64;
2001                        let store = self.inner.db.store();
2002                        let serialized_records = match store.refresh_collection(&q.name, entities) {
2003                            Ok(records) => records,
2004                            Err(err) => {
2005                                let duration_ms = started.elapsed().as_millis() as u64;
2006                                let msg = err.to_string();
2007                                self.inner
2008                                    .materialized_views
2009                                    .write()
2010                                    .record_refresh_failure(
2011                                        &q.name,
2012                                        msg.clone(),
2013                                        duration_ms,
2014                                        now_ms,
2015                                    );
2016                                return Err(RedDBError::Internal(format!(
2017                                    "REFRESH MATERIALIZED VIEW {}: {msg}",
2018                                    q.name
2019                                )));
2020                            }
2021                        };
2022
2023                        // Issue #596 slice 9d — emit a Refresh
2024                        // ChangeRecord into the logical-WAL spool so
2025                        // replicas deterministically replay the same
2026                        // backing-collection contents via
2027                        // `LogicalChangeApplier::apply_record`.
2028                        if self.inner.db.replication.is_some() {
2029                            let lsn = self.inner.cdc.emit(
2030                                crate::replication::cdc::ChangeOperation::Refresh,
2031                                &q.name,
2032                                0,
2033                                "refresh",
2034                            );
2035                            self.invalidate_result_cache_for_table(&q.name);
2036                            let timestamp = std::time::SystemTime::now()
2037                                .duration_since(std::time::UNIX_EPOCH)
2038                                .unwrap_or_default()
2039                                .as_millis() as u64;
2040                            let record = ChangeRecord::for_refresh(
2041                                lsn,
2042                                timestamp,
2043                                q.name.clone(),
2044                                serialized_records,
2045                            )
2046                            .with_term(self.current_replication_term());
2047                            self.stage_or_publish_logical_record(record)?;
2048                        }
2049
2050                        let duration_ms = started.elapsed().as_millis() as u64;
2051                        let serialized = format!("{:?}", inner_result.result);
2052                        self.inner
2053                            .materialized_views
2054                            .write()
2055                            .record_refresh_success(
2056                                &q.name,
2057                                serialized.into_bytes(),
2058                                row_count,
2059                                duration_ms,
2060                                now_ms,
2061                            );
2062                        // SELECT FROM v now reads through the rewriter
2063                        // skip into the backing collection — drop the
2064                        // result cache so prior empty-backing reads
2065                        // don't shadow the new contents.
2066                        self.invalidate_result_cache();
2067                        Ok(RuntimeQueryResult::ok_message(
2068                            query.to_string(),
2069                            &format!("materialized view {} refreshed", q.name),
2070                            "refresh_materialized_view",
2071                        ))
2072                    }
2073                    Err(err) => {
2074                        let duration_ms = started.elapsed().as_millis() as u64;
2075                        let msg = err.to_string();
2076                        self.inner
2077                            .materialized_views
2078                            .write()
2079                            .record_refresh_failure(&q.name, msg.clone(), duration_ms, now_ms);
2080                        Err(err)
2081                    }
2082                }
2083            }
2084            // Row Level Security (Phase 2.5 PG parity).
2085            //
2086            // Policies live in an in-memory registry keyed by (table, name).
2087            // Enforcement (AND-ing the policy's USING clause into every
2088            // query's WHERE for the table) arrives in Phase 2.5.2 via the
2089            // filter compiler; this dispatch only manages the catalog.
2090            QueryExpr::CreatePolicy(ref q) => {
2091                let key = (q.table.clone(), q.name.clone());
2092                self.inner
2093                    .rls_policies
2094                    .write()
2095                    .insert(key, Arc::new(q.clone()));
2096                self.invalidate_plan_cache();
2097                self.invalidate_result_cache();
2098                // Issue #120 — surface policy names in the
2099                // schema-vocabulary so AskPipeline (#121) can resolve
2100                // a policy reference back to its table.
2101                self.schema_vocabulary_apply(
2102                    crate::runtime::schema_vocabulary::DdlEvent::CreatePolicy {
2103                        collection: q.table.clone(),
2104                        policy: q.name.clone(),
2105                    },
2106                );
2107                Ok(RuntimeQueryResult::ok_message(
2108                    query.to_string(),
2109                    &format!("policy {} on {} created", q.name, q.table),
2110                    "create_policy",
2111                ))
2112            }
2113            QueryExpr::DropPolicy(ref q) => {
2114                let removed = self
2115                    .inner
2116                    .rls_policies
2117                    .write()
2118                    .remove(&(q.table.clone(), q.name.clone()))
2119                    .is_some();
2120                if !removed && !q.if_exists {
2121                    return Err(RedDBError::Internal(format!(
2122                        "policy {} on {} does not exist",
2123                        q.name, q.table
2124                    )));
2125                }
2126                self.invalidate_plan_cache();
2127                self.invalidate_result_cache();
2128                // Issue #120 — keep the schema-vocabulary policy
2129                // entry in sync.
2130                self.schema_vocabulary_apply(
2131                    crate::runtime::schema_vocabulary::DdlEvent::DropPolicy {
2132                        collection: q.table.clone(),
2133                        policy: q.name.clone(),
2134                    },
2135                );
2136                Ok(RuntimeQueryResult::ok_message(
2137                    query.to_string(),
2138                    &format!("policy {} on {} dropped", q.name, q.table),
2139                    "drop_policy",
2140                ))
2141            }
2142            // Foreign Data Wrappers (Phase 3.2 PG parity).
2143            //
2144            // CREATE SERVER / CREATE FOREIGN TABLE register into the shared
2145            // `ForeignTableRegistry`. The read path consults that registry
2146            // before dispatching a SELECT — when the table name matches a
2147            // registered foreign table, we forward the scan to the wrapper
2148            // and skip the normal collection lookup.
2149            //
2150            // Phase 3.2 is in-memory only; persistence across restarts is a
2151            // 3.2.2 follow-up that mirrors the view registry pattern.
2152            QueryExpr::CreateServer(ref q) => {
2153                use crate::storage::fdw::FdwOptions;
2154                let registry = Arc::clone(&self.inner.foreign_tables);
2155                if registry.server(&q.name).is_some() {
2156                    if q.if_not_exists {
2157                        return Ok(RuntimeQueryResult::ok_message(
2158                            query.to_string(),
2159                            &format!("server {} already exists — skipped", q.name),
2160                            "create_server",
2161                        ));
2162                    }
2163                    return Err(RedDBError::Internal(format!(
2164                        "server {} already exists",
2165                        q.name
2166                    )));
2167                }
2168                let mut opts = FdwOptions::new();
2169                for (k, v) in &q.options {
2170                    opts.values.insert(k.clone(), v.clone());
2171                }
2172                registry
2173                    .create_server(&q.name, &q.wrapper, opts)
2174                    .map_err(|e| RedDBError::Internal(e.to_string()))?;
2175                Ok(RuntimeQueryResult::ok_message(
2176                    query.to_string(),
2177                    &format!("server {} created (wrapper {})", q.name, q.wrapper),
2178                    "create_server",
2179                ))
2180            }
2181            QueryExpr::DropServer(ref q) => {
2182                let existed = self.inner.foreign_tables.drop_server(&q.name);
2183                if !existed && !q.if_exists {
2184                    return Err(RedDBError::Internal(format!(
2185                        "server {} does not exist",
2186                        q.name
2187                    )));
2188                }
2189                Ok(RuntimeQueryResult::ok_message(
2190                    query.to_string(),
2191                    &format!(
2192                        "server {} dropped{}",
2193                        q.name,
2194                        if q.cascade { " (cascade)" } else { "" }
2195                    ),
2196                    "drop_server",
2197                ))
2198            }
2199            QueryExpr::CreateForeignTable(ref q) => {
2200                use crate::storage::fdw::{FdwOptions, ForeignColumn, ForeignTable};
2201                let registry = Arc::clone(&self.inner.foreign_tables);
2202                if registry.foreign_table(&q.name).is_some() {
2203                    if q.if_not_exists {
2204                        return Ok(RuntimeQueryResult::ok_message(
2205                            query.to_string(),
2206                            &format!("foreign table {} already exists — skipped", q.name),
2207                            "create_foreign_table",
2208                        ));
2209                    }
2210                    return Err(RedDBError::Internal(format!(
2211                        "foreign table {} already exists",
2212                        q.name
2213                    )));
2214                }
2215                let mut opts = FdwOptions::new();
2216                for (k, v) in &q.options {
2217                    opts.values.insert(k.clone(), v.clone());
2218                }
2219                let columns: Vec<ForeignColumn> = q
2220                    .columns
2221                    .iter()
2222                    .map(|c| ForeignColumn {
2223                        name: c.name.clone(),
2224                        data_type: c.data_type.clone(),
2225                        not_null: c.not_null,
2226                    })
2227                    .collect();
2228                registry
2229                    .create_foreign_table(ForeignTable {
2230                        name: q.name.clone(),
2231                        server_name: q.server.clone(),
2232                        columns,
2233                        options: opts,
2234                    })
2235                    .map_err(|e| RedDBError::Internal(e.to_string()))?;
2236                self.invalidate_plan_cache();
2237                Ok(RuntimeQueryResult::ok_message(
2238                    query.to_string(),
2239                    &format!("foreign table {} created (server {})", q.name, q.server),
2240                    "create_foreign_table",
2241                ))
2242            }
2243            QueryExpr::DropForeignTable(ref q) => {
2244                let existed = self.inner.foreign_tables.drop_foreign_table(&q.name);
2245                if !existed && !q.if_exists {
2246                    return Err(RedDBError::Internal(format!(
2247                        "foreign table {} does not exist",
2248                        q.name
2249                    )));
2250                }
2251                self.invalidate_plan_cache();
2252                Ok(RuntimeQueryResult::ok_message(
2253                    query.to_string(),
2254                    &format!("foreign table {} dropped", q.name),
2255                    "drop_foreign_table",
2256                ))
2257            }
2258            // COPY table FROM 'path' (Phase 1.5 PG parity).
2259            //
2260            // Stream CSV rows through the shared `CsvImporter`. The collection
2261            // is auto-created on first insert (via `insert_auto`-style path);
2262            // VACUUM/ANALYZE afterwards is up to the caller.
2263            QueryExpr::CopyFrom(ref q) => {
2264                use crate::storage::import::{CsvConfig, CsvImporter};
2265                self.check_copy_from_privilege(&q.table)?;
2266                confine_copy_from_path(&q.path)?;
2267                let store = self.inner.db.store();
2268                let cfg = CsvConfig {
2269                    collection: q.table.clone(),
2270                    has_header: q.has_header,
2271                    delimiter: q.delimiter.map(|c| c as u8).unwrap_or(b','),
2272                    ..CsvConfig::default()
2273                };
2274                let importer = CsvImporter::new(cfg);
2275                let stats = importer
2276                    .import_file(&q.path, store.as_ref())
2277                    .map_err(|e| RedDBError::Internal(format!("COPY failed: {e}")))?;
2278                // Tables are written → invalidate cached plans / result cache.
2279                self.note_table_write(&q.table);
2280                Ok(RuntimeQueryResult::ok_message(
2281                    query.to_string(),
2282                    &format!(
2283                        "COPY imported {} rows into {} ({} errors skipped, {}ms)",
2284                        stats.records_imported, q.table, stats.errors_skipped, stats.duration_ms
2285                    ),
2286                    "copy_from",
2287                ))
2288            }
2289            // Maintenance commands (Phase 1.2 PG parity).
2290            //
2291            // - VACUUM [FULL] [table]: refreshes planner stats for the target
2292            //   collection(s) and — when FULL — triggers a full pager persist
2293            //   (flushes dirty pages + fsync). Also invalidates the result cache
2294            //   so subsequent reads re-execute against the freshly compacted
2295            //   storage. RedDB's segment/btree GC runs continuously via the
2296            //   background lifecycle; explicit space reclamation for sealed
2297            //   segments arrives with Phase 2.3 (MVCC + dead-tuple reclamation).
2298            // - ANALYZE [table]: reruns `analyze_collection` +
2299            //   `persist_table_stats` via `refresh_table_planner_stats` so the
2300            //   planner has fresh histograms, distinct estimates, null counts.
2301            //
2302            // Both commands accept an optional target; omitting the target
2303            // iterates every collection in the store.
2304            QueryExpr::MaintenanceCommand(ref cmd) => {
2305                use reddb_rql::ast::MaintenanceCommand as Mc;
2306                let store = self.inner.db.store();
2307                let (kind, msg) = match cmd {
2308                    Mc::Analyze { target } => {
2309                        let targets: Vec<String> = match target {
2310                            Some(t) => vec![t.clone()],
2311                            None => store.list_collections(),
2312                        };
2313                        for t in &targets {
2314                            self.refresh_table_planner_stats(t);
2315                        }
2316                        (
2317                            "analyze",
2318                            format!("ANALYZE refreshed stats for {} table(s)", targets.len()),
2319                        )
2320                    }
2321                    Mc::Vacuum { target, full } => {
2322                        let targets: Vec<String> = match target {
2323                            Some(t) => vec![t.clone()],
2324                            None => store.list_collections(),
2325                        };
2326                        let mut vacuum_stats =
2327                            crate::storage::unified::store::MvccVacuumStats::default();
2328                        for t in &targets {
2329                            let cutoff_xid = self.mvcc_vacuum_cutoff_xid_for(t)?;
2330                            let stats = store.vacuum_mvcc_history(t, cutoff_xid).map_err(|e| {
2331                                RedDBError::Internal(format!(
2332                                    "VACUUM MVCC history failed for {t}: {e}"
2333                                ))
2334                            })?;
2335                            if stats.reclaimed_versions > 0 {
2336                                self.rebuild_runtime_indexes_for_table(t)?;
2337                            }
2338                            vacuum_stats.add(&stats);
2339                        }
2340                        // The cutoff protects snapshots, not physical references.
2341                        // Aborted inserts can remain in this or another collection;
2342                        // forgetting their outcome would make them visible again.
2343                        // Stats refresh covers every target (same as ANALYZE).
2344                        for t in &targets {
2345                            self.refresh_table_planner_stats(t);
2346                        }
2347                        // FULL forces a pager persist (dirty-page flush + fsync).
2348                        // Regular VACUUM relies on the background writer / segment
2349                        // lifecycle so the command is non-blocking.
2350                        let persisted = if *full {
2351                            match store.persist() {
2352                                Ok(()) => true,
2353                                Err(e) => {
2354                                    return Err(RedDBError::Internal(format!(
2355                                        "VACUUM FULL persist failed: {e:?}"
2356                                    )));
2357                                }
2358                            }
2359                        } else {
2360                            false
2361                        };
2362                        // Result cache depended on pre-vacuum state.
2363                        self.invalidate_result_cache();
2364                        (
2365                            "vacuum",
2366                            format!(
2367                                "VACUUM{} processed {} table(s): scanned_versions={}, retained_versions={}, reclaimed_versions={}, retained_history_versions={}, reclaimed_history_versions={}, retained_tombstones={}, reclaimed_tombstones={}{}",
2368                                if *full { " FULL" } else { "" },
2369                                targets.len(),
2370                                vacuum_stats.scanned_versions,
2371                                vacuum_stats.retained_versions,
2372                                vacuum_stats.reclaimed_versions,
2373                                vacuum_stats.retained_history_versions,
2374                                vacuum_stats.reclaimed_history_versions,
2375                                vacuum_stats.retained_tombstones,
2376                                vacuum_stats.reclaimed_tombstones,
2377                                if persisted {
2378                                    " (pages flushed to disk)"
2379                                } else {
2380                                    ""
2381                                }
2382                            ),
2383                        )
2384                    }
2385                };
2386                Ok(RuntimeQueryResult::ok_message(
2387                    query.to_string(),
2388                    &msg,
2389                    kind,
2390                ))
2391            }
2392            // GRANT / REVOKE / ALTER USER (RBAC milestone).
2393            //
2394            // These hit the AuthStore directly. The statement frame /
2395            // privilege gate has already decided whether the caller may
2396            // even run the statement; here we just translate the AST into
2397            // AuthStore calls.
2398            QueryExpr::Grant(ref g) => self.execute_grant_statement(query, g),
2399            QueryExpr::Revoke(ref r) => self.execute_revoke_statement(query, r),
2400            QueryExpr::AlterUser(ref a) => self.execute_alter_user_statement(query, a),
2401            QueryExpr::CreateUser(ref u) => self.execute_create_user_statement(query, u),
2402            QueryExpr::CreateIamPolicy { ref id, ref json } => {
2403                self.execute_create_iam_policy(query, id, json)
2404            }
2405            QueryExpr::DropIamPolicy { ref id } => self.execute_drop_iam_policy(query, id),
2406            QueryExpr::AttachPolicy {
2407                ref policy_id,
2408                ref principal,
2409            } => self.execute_attach_policy(query, policy_id, principal),
2410            QueryExpr::DetachPolicy {
2411                ref policy_id,
2412                ref principal,
2413            } => self.execute_detach_policy(query, policy_id, principal),
2414            QueryExpr::ShowPolicies { ref filter } => {
2415                self.execute_show_policies(query, filter.as_ref())
2416            }
2417            QueryExpr::ShowEffectivePermissions {
2418                ref user,
2419                ref resource,
2420            } => self.execute_show_effective_permissions(query, user, resource.as_ref()),
2421            QueryExpr::SimulatePolicy {
2422                ref user,
2423                ref action,
2424                ref resource,
2425            } => self.execute_simulate_policy(query, user, action, resource),
2426            QueryExpr::LintPolicy { ref source } => self.execute_lint_policy(query, source),
2427            QueryExpr::MigratePolicyMode {
2428                ref target,
2429                dry_run,
2430            } => self.execute_migrate_policy_mode(query, target, dry_run),
2431            QueryExpr::CreateMigration(ref q) => self.execute_create_migration(query, q),
2432            QueryExpr::ApplyMigration(ref q) => self.execute_apply_migration(query, q),
2433            QueryExpr::RollbackMigration(ref q) => self.execute_rollback_migration(query, q),
2434            QueryExpr::ExplainMigration(ref q) => self.execute_explain_migration(query, q),
2435            _ => Err(RedDBError::Query(
2436                "unsupported command in runtime dispatcher".to_string(),
2437            )),
2438        };
2439
2440        if _query_budget.is_some() {
2441            super::query_budget::charge(0)?;
2442        }
2443        if !control_event_specs.is_empty() {
2444            let (outcome, reason) = match &query_result {
2445                Ok(_) => (crate::runtime::control_events::Outcome::Allowed, None),
2446                Err(err) => (control_event_outcome_for_error(err), Some(err.to_string())),
2447            };
2448            for spec in &control_event_specs {
2449                self.emit_control_event(
2450                    spec.kind,
2451                    outcome,
2452                    spec.action,
2453                    spec.resource.clone(),
2454                    reason.clone(),
2455                    spec.fields.clone(),
2456                )?;
2457            }
2458        }
2459
2460        if let (Some(plan), Ok(result)) = (&query_audit_plan, &query_result) {
2461            self.emit_query_audit(
2462                query,
2463                plan,
2464                query_audit_started.elapsed().as_millis() as u64,
2465                result,
2466            );
2467        }
2468
2469        // Cache SELECT results for 30s.
2470        // Skip: pre-serialized JSON (large clone), and result sets > 5 rows.
2471        // Large multi-row results (range scans, filtered scans) are rarely
2472        // repeated with the same literal values so the cache hit rate is near
2473        // zero while the clone cost (100 records × ~16 fields each) is high.
2474        // Aggregations (1 row) and point lookups (1 row) still benefit.
2475        if let Ok(ref result) = query_result {
2476            frame.write_result_cache(self, result, result_cache_scopes);
2477        }
2478
2479        query_result
2480    }
2481
2482    /// Execute a pre-parsed `QueryExpr` that has no accompanying SQL text,
2483    /// bypassing SQL parsing and the plan cache.
2484    ///
2485    /// Prefer [`Self::execute_prepared_query`] or
2486    /// [`Self::execute_query_with_params`]: they carry the statement text, so
2487    /// the frame's snapshot (including `AS OF`), coarse privilege class, lock
2488    /// intent, and result-cache key all describe the statement that actually
2489    /// runs. This entry exists for the nested in-statement callers — the CTE
2490    /// prelude, materialized-view refresh, and the inline graph TVF — which
2491    /// hold an expression the outer statement already parsed.
2492    ///
2493    /// Cost: this is no longer a "zero overhead" path. It builds and installs
2494    /// a full `StatementExecutionFrame` (tenant / config / secret / KV guards
2495    /// plus an MVCC snapshot), which is what buys it the same snapshot
2496    /// isolation as textual SQL. Nested calls inherit the enclosing
2497    /// statement's snapshot rather than minting a new one, and the frame opts
2498    /// out of the result cache because there is no stable text key.
2499    ///
2500    /// Keeps secret SELECT results masked, identical to `execute_query`.
2501    pub fn execute_query_expr(&self, expr: QueryExpr) -> RedDBResult<RuntimeQueryResult> {
2502        let frame = super::statement_frame::StatementExecutionFrame::build(
2503            self,
2504            super::statement_frame::StatementIdentity::Expr(&expr),
2505        )?;
2506        let _frame_guards = Box::new(frame.install(self));
2507        // View rewrite (Phase 2.1): substitute any `QueryExpr::Table(tq)`
2508        // whose `tq.table` matches a registered view with the view's
2509        // underlying query. Safe to call even when no views are registered.
2510        let expr = self.rewrite_view_refs(expr);
2511
2512        self.validate_model_operations_before_auth(&expr)?;
2513        // Granular RBAC privilege check. Runs before dispatch so a
2514        // denied caller never reaches storage. Fail-closed: any error
2515        // resolving the action / resource produces PermissionDenied.
2516        if let Err(err) = self.check_query_privilege(&expr) {
2517            return Err(RedDBError::Query(format!("permission denied: {err}")));
2518        }
2519
2520        frame.release_snapshot_for_maintenance(&expr);
2521        let statement = query_expr_name(&expr);
2522        let mode = detect_mode(statement);
2523        let query_str = statement;
2524
2525        self.dispatch_expr(expr, query_str, mode)
2526    }
2527
2528    pub(super) fn validate_model_operations_before_auth(
2529        &self,
2530        expr: &QueryExpr,
2531    ) -> RedDBResult<()> {
2532        self.validate_vault_table_access(expr)?;
2533        use crate::catalog::CollectionModel;
2534        use crate::runtime::ddl::polymorphic_resolver;
2535        use reddb_rql::ast::KvCommand;
2536
2537        let system_schema_target = match expr {
2538            QueryExpr::DropTable(q) => Some(q.name.as_str()),
2539            QueryExpr::DropGraph(q) => Some(q.name.as_str()),
2540            QueryExpr::DropVector(q) => Some(q.name.as_str()),
2541            QueryExpr::DropDocument(q) => Some(q.name.as_str()),
2542            QueryExpr::DropKv(q) => Some(q.name.as_str()),
2543            QueryExpr::DropCollection(q) => Some(q.name.as_str()),
2544            QueryExpr::Truncate(q) => Some(q.name.as_str()),
2545            _ => None,
2546        };
2547        if system_schema_target.is_some_and(crate::runtime::impl_ddl::is_system_schema_name) {
2548            return Err(RedDBError::Query("system schema is read-only".to_string()));
2549        }
2550
2551        let expected = match expr {
2552            QueryExpr::DropTable(q) => Some((q.name.as_str(), CollectionModel::Table)),
2553            QueryExpr::DropGraph(q) => Some((q.name.as_str(), CollectionModel::Graph)),
2554            QueryExpr::DropVector(q) => Some((q.name.as_str(), CollectionModel::Vector)),
2555            QueryExpr::DropDocument(q) => Some((q.name.as_str(), CollectionModel::Document)),
2556            QueryExpr::DropKv(q) => Some((q.name.as_str(), q.model)),
2557            QueryExpr::DropCollection(q) => q.model.map(|model| (q.name.as_str(), model)),
2558            QueryExpr::Truncate(q) => q.model.map(|model| (q.name.as_str(), model)),
2559            QueryExpr::KvCommand(cmd) => {
2560                let (collection, model) = match cmd {
2561                    KvCommand::Put {
2562                        collection, model, ..
2563                    }
2564                    | KvCommand::Get {
2565                        collection, model, ..
2566                    }
2567                    | KvCommand::Incr {
2568                        collection, model, ..
2569                    }
2570                    | KvCommand::Cas {
2571                        collection, model, ..
2572                    }
2573                    | KvCommand::List {
2574                        collection, model, ..
2575                    }
2576                    | KvCommand::Delete {
2577                        collection, model, ..
2578                    } => (collection.as_str(), *model),
2579                    KvCommand::Rotate { collection, .. }
2580                    | KvCommand::History { collection, .. }
2581                    | KvCommand::Purge { collection, .. } => {
2582                        (collection.as_str(), CollectionModel::Vault)
2583                    }
2584                    KvCommand::InvalidateTags { collection, .. } => {
2585                        (collection.as_str(), CollectionModel::Kv)
2586                    }
2587                    KvCommand::Watch {
2588                        collection, model, ..
2589                    } => (collection.as_str(), *model),
2590                    KvCommand::Reveal { collection, .. } => {
2591                        (collection.as_str(), CollectionModel::Vault)
2592                    }
2593                };
2594                Some((collection, model))
2595            }
2596            QueryExpr::ConfigCommand(cmd) => {
2597                self.validate_config_command_before_auth(cmd)?;
2598                None
2599            }
2600            _ => None,
2601        };
2602
2603        let Some((name, expected_model)) = expected else {
2604            return Ok(());
2605        };
2606        // Declared models are authoritative in the catalog snapshot. Resolve
2607        // just this contract instead of observing every row in every collection
2608        // for a point command. Keep the snapshot fallback for undeclared legacy
2609        // collections and orphaned contracts, preserving their inference rules.
2610        if let Some(contract) = self.inner.db.collection_contract_arc(name) {
2611            if self.inner.db.store().get_collection(name).is_some() {
2612                return polymorphic_resolver::ensure_model_match(
2613                    expected_model,
2614                    contract.declared_model,
2615                );
2616            }
2617        }
2618        let snapshot = self.inner.db.catalog_model_snapshot();
2619        let Some(actual_model) = snapshot
2620            .collections
2621            .iter()
2622            .find(|collection| collection.name == name)
2623            .map(|collection| collection.declared_model.unwrap_or(collection.model))
2624        else {
2625            return Ok(());
2626        };
2627        polymorphic_resolver::ensure_model_match(expected_model, actual_model)
2628    }
2629
2630    /// Walk a `QueryExpr` and replace `QueryExpr::Table(tq)` nodes whose
2631    /// `tq.table` matches a registered view name with the view's stored
2632    /// body. Recurses through joins so `SELECT ... FROM t JOIN myview ...`
2633    /// resolves correctly. Pure operation — no side effects.
2634    pub(super) fn rewrite_view_refs(&self, expr: QueryExpr) -> QueryExpr {
2635        // Fast path: no views registered → return original expression.
2636        if self.inner.views.read().is_empty() {
2637            return expr;
2638        }
2639        self.rewrite_view_refs_inner(expr)
2640    }
2641
2642    fn rewrite_view_refs_inner(&self, expr: QueryExpr) -> QueryExpr {
2643        use reddb_rql::ast::{Filter, TableSource};
2644        match expr {
2645            QueryExpr::Table(mut tq) => {
2646                // 1. If the TableSource is a subquery, recurse into it so
2647                //    `SELECT ... FROM (SELECT ... FROM myview) t` expands.
2648                //    The legacy `table` field (set to a synthetic
2649                //    "__subq_NNNN" sentinel) stays as-is so callers that
2650                //    read it keep compiling.
2651                if let Some(TableSource::Subquery(body)) = tq.source.take() {
2652                    tq.source = Some(TableSource::Subquery(Box::new(
2653                        self.rewrite_view_refs_inner(*body),
2654                    )));
2655                    return QueryExpr::Table(tq);
2656                }
2657
2658                // 2. Restore the source field (took it above for match).
2659                // When the source was `None` or `TableSource::Name(_)`, the
2660                // real lookup key is `tq.table` — check the view registry.
2661                let maybe_view = {
2662                    let views = self.inner.views.read();
2663                    views.get(&tq.table).cloned()
2664                };
2665                let Some(view) = maybe_view else {
2666                    return QueryExpr::Table(tq);
2667                };
2668
2669                // Issue #594 slice 9b — materialized views are read
2670                // from their backing collection, not by substituting
2671                // the body. Returning the TableQuery as-is lets the
2672                // normal table-read path resolve `SELECT FROM v`
2673                // against the collection provisioned at CREATE time.
2674                if view.materialized {
2675                    return QueryExpr::Table(tq);
2676                }
2677
2678                // Recurse into the view body — views may reference other
2679                // views. The recursion yields the final QueryExpr we need
2680                // to merge the outer's filter / limit / offset into.
2681                let inner_expr = self.rewrite_view_refs_inner((*view.query).clone());
2682
2683                // Phase 5: when the body is a Table we merge the outer
2684                // TableQuery's WHERE / LIMIT / OFFSET into it so stacked
2685                // views filter recursively. Non-table bodies (Search,
2686                // Ask, Vector, Graph, Hybrid) can't meaningfully combine
2687                // with an outer Table query today — return the body
2688                // verbatim; outer predicates are lost. Full projection
2689                // merge lands in Phase 5.2.
2690                match inner_expr {
2691                    QueryExpr::Table(mut inner_tq) => {
2692                        if let Some(outer_filter) = tq.filter.take() {
2693                            inner_tq.filter = Some(match inner_tq.filter.take() {
2694                                Some(existing) => {
2695                                    Filter::And(Box::new(existing), Box::new(outer_filter))
2696                                }
2697                                None => outer_filter,
2698                            });
2699                            // Keep the `Expr` form in lock-step with the
2700                            // merged `Filter`. The executor prefers
2701                            // `where_expr` and nulls `filter` when it is
2702                            // present (see `execute_query_inner`), so a
2703                            // stacked view whose outer predicate was only
2704                            // merged into `filter` would silently drop that
2705                            // predicate at eval time (#635).
2706                            inner_tq.where_expr = inner_tq
2707                                .filter
2708                                .as_ref()
2709                                .map(reddb_rql::sql_lowering::filter_to_expr);
2710                        }
2711                        if let Some(outer_limit) = tq.limit {
2712                            inner_tq.limit = Some(match inner_tq.limit {
2713                                Some(existing) => existing.min(outer_limit),
2714                                None => outer_limit,
2715                            });
2716                        }
2717                        if let Some(outer_offset) = tq.offset {
2718                            inner_tq.offset = Some(match inner_tq.offset {
2719                                Some(existing) => existing + outer_offset,
2720                                None => outer_offset,
2721                            });
2722                        }
2723                        QueryExpr::Table(inner_tq)
2724                    }
2725                    other => other,
2726                }
2727            }
2728            QueryExpr::Join(mut jq) => {
2729                jq.left = Box::new(self.rewrite_view_refs_inner(*jq.left));
2730                jq.right = Box::new(self.rewrite_view_refs_inner(*jq.right));
2731                QueryExpr::Join(jq)
2732            }
2733            // Other variants don't carry nested QueryExpr that can reference
2734            // a view by table name. Return as-is.
2735            other => other,
2736        }
2737    }
2738
2739    fn resolve_table_expr_subqueries(
2740        &self,
2741        mut table: TableQuery,
2742        frame: &dyn super::statement_frame::ReadFrame,
2743    ) -> RedDBResult<TableQuery> {
2744        // Only a `Subquery` source needs recursive resolution. `.take()`
2745        // would otherwise drop a `Name` / `Function` source on the floor
2746        // (the `if let` skips the body but the take already cleared it),
2747        // which silently broke `SELECT * FROM components(g)` — the TVF
2748        // dispatch downstream keys off `TableSource::Function` and never
2749        // fired. Restore any non-subquery source unchanged (issue #795).
2750        match table.source.take() {
2751            Some(TableSource::Subquery(inner)) => {
2752                let inner = self.resolve_select_expr_subqueries(*inner, frame)?;
2753                table.source = Some(TableSource::Subquery(Box::new(inner)));
2754            }
2755            other => table.source = other,
2756        }
2757
2758        let outer_scopes = relation_scopes_for_query(&QueryExpr::Table(table.clone()));
2759        for item in &mut table.select_items {
2760            if let reddb_rql::ast::SelectItem::Expr { expr, .. } = item {
2761                *expr = self.resolve_expr_subqueries(expr.clone(), &outer_scopes, frame)?;
2762            }
2763        }
2764        if let Some(where_expr) = table.where_expr.take() {
2765            table.where_expr =
2766                Some(self.resolve_expr_subqueries(where_expr, &outer_scopes, frame)?);
2767            table.filter = None;
2768        }
2769        if let Some(having_expr) = table.having_expr.take() {
2770            table.having_expr =
2771                Some(self.resolve_expr_subqueries(having_expr, &outer_scopes, frame)?);
2772            table.having = None;
2773        }
2774        for expr in &mut table.group_by_exprs {
2775            *expr = self.resolve_expr_subqueries(expr.clone(), &outer_scopes, frame)?;
2776        }
2777        for clause in &mut table.order_by {
2778            if let Some(expr) = clause.expr.take() {
2779                clause.expr = Some(self.resolve_expr_subqueries(expr, &outer_scopes, frame)?);
2780            }
2781        }
2782        Ok(table)
2783    }
2784
2785    fn resolve_select_expr_subqueries(
2786        &self,
2787        expr: QueryExpr,
2788        frame: &dyn super::statement_frame::ReadFrame,
2789    ) -> RedDBResult<QueryExpr> {
2790        match expr {
2791            QueryExpr::Table(table) => self
2792                .resolve_table_expr_subqueries(table, frame)
2793                .map(QueryExpr::Table),
2794            QueryExpr::Join(mut join) => {
2795                join.left = Box::new(self.resolve_select_expr_subqueries(*join.left, frame)?);
2796                join.right = Box::new(self.resolve_select_expr_subqueries(*join.right, frame)?);
2797                Ok(QueryExpr::Join(join))
2798            }
2799            other => Ok(other),
2800        }
2801    }
2802
2803    fn resolve_expr_subqueries(
2804        &self,
2805        expr: reddb_rql::ast::Expr,
2806        outer_scopes: &[String],
2807        frame: &dyn super::statement_frame::ReadFrame,
2808    ) -> RedDBResult<reddb_rql::ast::Expr> {
2809        use reddb_rql::ast::Expr;
2810
2811        match expr {
2812            Expr::Subquery { query, span } => {
2813                let values = self.execute_expr_subquery_values(query, outer_scopes, frame)?;
2814                if values.len() > 1 {
2815                    return Err(RedDBError::Query(
2816                        "scalar subquery returned more than one row".to_string(),
2817                    ));
2818                }
2819                Ok(Expr::Literal {
2820                    value: values.into_iter().next().unwrap_or(Value::Null),
2821                    span,
2822                })
2823            }
2824            Expr::BinaryOp { op, lhs, rhs, span } => Ok(Expr::BinaryOp {
2825                op,
2826                lhs: Box::new(self.resolve_expr_subqueries(*lhs, outer_scopes, frame)?),
2827                rhs: Box::new(self.resolve_expr_subqueries(*rhs, outer_scopes, frame)?),
2828                span,
2829            }),
2830            Expr::UnaryOp { op, operand, span } => Ok(Expr::UnaryOp {
2831                op,
2832                operand: Box::new(self.resolve_expr_subqueries(*operand, outer_scopes, frame)?),
2833                span,
2834            }),
2835            Expr::Cast {
2836                inner,
2837                target,
2838                span,
2839            } => Ok(Expr::Cast {
2840                inner: Box::new(self.resolve_expr_subqueries(*inner, outer_scopes, frame)?),
2841                target,
2842                span,
2843            }),
2844            Expr::FunctionCall { ref name, .. } if name == reddb_rql::ast::EXISTS_EXPR => Ok(expr),
2845            Expr::FunctionCall { name, args, span } => {
2846                let args = args
2847                    .into_iter()
2848                    .map(|arg| self.resolve_expr_subqueries(arg, outer_scopes, frame))
2849                    .collect::<RedDBResult<Vec<_>>>()?;
2850                Ok(Expr::FunctionCall { name, args, span })
2851            }
2852            Expr::WindowFunctionCall {
2853                name,
2854                args,
2855                mut window,
2856                span,
2857            } => {
2858                let args = args
2859                    .into_iter()
2860                    .map(|arg| self.resolve_expr_subqueries(arg, outer_scopes, frame))
2861                    .collect::<RedDBResult<Vec<_>>>()?;
2862                for expr in &mut window.partition_by {
2863                    *expr = self.resolve_expr_subqueries(expr.clone(), outer_scopes, frame)?;
2864                }
2865                for clause in &mut window.order_by {
2866                    clause.expr =
2867                        self.resolve_expr_subqueries(clause.expr.clone(), outer_scopes, frame)?;
2868                }
2869                Ok(Expr::WindowFunctionCall {
2870                    name,
2871                    args,
2872                    window,
2873                    span,
2874                })
2875            }
2876            Expr::Case {
2877                branches,
2878                else_,
2879                span,
2880            } => {
2881                let branches = branches
2882                    .into_iter()
2883                    .map(|(cond, value)| {
2884                        Ok((
2885                            self.resolve_expr_subqueries(cond, outer_scopes, frame)?,
2886                            self.resolve_expr_subqueries(value, outer_scopes, frame)?,
2887                        ))
2888                    })
2889                    .collect::<RedDBResult<Vec<_>>>()?;
2890                let else_ = else_
2891                    .map(|expr| self.resolve_expr_subqueries(*expr, outer_scopes, frame))
2892                    .transpose()?
2893                    .map(Box::new);
2894                Ok(Expr::Case {
2895                    branches,
2896                    else_,
2897                    span,
2898                })
2899            }
2900            Expr::IsNull {
2901                operand,
2902                negated,
2903                span,
2904            } => Ok(Expr::IsNull {
2905                operand: Box::new(self.resolve_expr_subqueries(*operand, outer_scopes, frame)?),
2906                negated,
2907                span,
2908            }),
2909            Expr::InList {
2910                target,
2911                values,
2912                negated,
2913                span,
2914            } => {
2915                let target =
2916                    Box::new(self.resolve_expr_subqueries(*target, outer_scopes, frame)?);
2917                let mut resolved = Vec::new();
2918                for value in values {
2919                    if let Expr::Subquery { query, .. } = value {
2920                        resolved.extend(
2921                            self.execute_expr_subquery_values(query, outer_scopes, frame)?
2922                                .into_iter()
2923                                .map(Expr::lit),
2924                        );
2925                    } else {
2926                        resolved.push(self.resolve_expr_subqueries(value, outer_scopes, frame)?);
2927                    }
2928                }
2929                Ok(Expr::InList {
2930                    target,
2931                    values: resolved,
2932                    negated,
2933                    span,
2934                })
2935            }
2936            Expr::Between {
2937                target,
2938                low,
2939                high,
2940                negated,
2941                span,
2942            } => Ok(Expr::Between {
2943                target: Box::new(self.resolve_expr_subqueries(*target, outer_scopes, frame)?),
2944                low: Box::new(self.resolve_expr_subqueries(*low, outer_scopes, frame)?),
2945                high: Box::new(self.resolve_expr_subqueries(*high, outer_scopes, frame)?),
2946                negated,
2947                span,
2948            }),
2949            other => Ok(other),
2950        }
2951    }
2952
2953    fn execute_expr_subquery_values(
2954        &self,
2955        subquery: reddb_rql::ast::ExprSubquery,
2956        outer_scopes: &[String],
2957        frame: &dyn super::statement_frame::ReadFrame,
2958    ) -> RedDBResult<Vec<Value>> {
2959        let query = *subquery.query;
2960        if query_references_outer_scope(&query, outer_scopes) {
2961            return Err(RedDBError::Query(
2962                "NOT_YET_SUPPORTED: correlated subqueries are not supported yet; track follow-up issue #470-correlated-subqueries".to_string(),
2963            ));
2964        }
2965        let query = self.rewrite_view_refs(query);
2966        let query = self.resolve_select_expr_subqueries(query, frame)?;
2967        let query = self.authorize_relational_select_expr(query, frame)?;
2968        let result = match query {
2969            QueryExpr::Table(table) => {
2970                execute_runtime_table_query(&self.inner.db, &table, Some(&self.inner.index_store))?
2971            }
2972            QueryExpr::Join(join) => execute_runtime_join_query(self, &join)?,
2973            other => {
2974                return Err(RedDBError::Query(format!(
2975                    "expression subquery must be a SELECT query, got {}",
2976                    query_expr_name(&other)
2977                )))
2978            }
2979        };
2980        first_column_values(result)
2981    }
2982
2983    fn execute_materialized_graph(
2984        &self,
2985        query: &str,
2986        mode: QueryMode,
2987        statement: &'static str,
2988        expr: &QueryExpr,
2989    ) -> RedDBResult<RuntimeQueryResult> {
2990        // Apply MVCC visibility + RLS gate while materialising the
2991        // graph: every node entity is screened against the source
2992        // collection's policy chain (basic and `Nodes`-targeted)
2993        // and dropped when the caller's tenant / role doesn't
2994        // admit it. Edges are pruned automatically because the
2995        // graph builder skips edges whose endpoints aren't in
2996        // `allowed_nodes`.
2997        let (graph, node_properties, edge_properties) = self.materialize_graph_with_rls()?;
2998        let result =
2999            crate::storage::query::unified::UnifiedExecutor::execute_on_with_graph_properties_checked(
3000                &graph,
3001                expr,
3002                node_properties,
3003                edge_properties,
3004                super::function_budget::graph_work_check(),
3005            )
3006            .map_err(|err| RedDBError::Query(err.to_string()))?;
3007
3008        Ok(RuntimeQueryResult {
3009            query: query.to_string(),
3010            mode,
3011            statement,
3012            engine: "materialized-graph",
3013            result,
3014            affected_rows: 0,
3015            statement_type: "select",
3016            bookmark: None,
3017            notice: None,
3018        })
3019    }
3020
3021    fn dispatch_expr(
3022        &self,
3023        expr: QueryExpr,
3024        query_str: &str,
3025        mode: QueryMode,
3026    ) -> RedDBResult<RuntimeQueryResult> {
3027        // Typed read plans only: mutation/transaction cleanup must never fail
3028        // because a read result or cooperative deadline budget was exhausted.
3029        let is_read = super::query_budget::is_materialized_read(&expr);
3030        let _budget = if is_read {
3031            Some(super::query_budget::Scope::enter(
3032                self.resource_limits(),
3033                &self.inner.query_budget_slots,
3034            )?)
3035        } else {
3036            None
3037        };
3038        let result = self.dispatch_expr_inner(expr, query_str, mode);
3039        if is_read {
3040            super::query_budget::charge(0)?;
3041        }
3042        let result = result?;
3043        super::query_budget::check_result(self.resource_limits(), &result)?;
3044        if is_read {
3045            super::query_budget::charge(0)?;
3046        }
3047        Ok(result)
3048    }
3049
3050    fn dispatch_expr_inner(
3051        &self,
3052        expr: QueryExpr,
3053        query_str: &str,
3054        mode: QueryMode,
3055    ) -> RedDBResult<RuntimeQueryResult> {
3056        let statement = query_expr_name(&expr);
3057        match expr {
3058            QueryExpr::Function(command) => self.execute_function(query_str, &command),
3059            QueryExpr::Graph(_) | QueryExpr::Path(_) => {
3060                self.execute_materialized_graph(query_str, mode, statement, &expr)
3061            }
3062            QueryExpr::Table(table) => {
3063                let scope = self.ai_scope();
3064                let table = self.resolve_table_expr_subqueries(
3065                    table,
3066                    &scope as &dyn super::statement_frame::ReadFrame,
3067                )?;
3068                // Table-valued functions (e.g. components(g)) dispatch to a
3069                // read-only executor before any catalog/virtual-table routing
3070                // (issue #795).
3071                if let Some(TableSource::Function {
3072                    name,
3073                    args,
3074                    named_args,
3075                }) = table.source.clone()
3076                {
3077                    return Ok(RuntimeQueryResult {
3078                        query: query_str.to_string(),
3079                        mode,
3080                        statement,
3081                        engine: "runtime-graph-tvf",
3082                        result: self.execute_table_function(&name, &args, &named_args)?,
3083                        affected_rows: 0,
3084                        statement_type: "select",
3085                        bookmark: None,
3086                        notice: None,
3087                    });
3088                }
3089                // Inline-graph TVF (issue #799) on the prepared-statement /
3090                // direct-expr path. Result caching is wired on the
3091                // `execute_query_inner` path; here we just compute and return.
3092                if let Some(TableSource::InlineGraphFunction {
3093                    name,
3094                    nodes,
3095                    edges,
3096                    named_args,
3097                }) = table.source.clone()
3098                {
3099                    return Ok(RuntimeQueryResult {
3100                        query: query_str.to_string(),
3101                        mode,
3102                        statement,
3103                        engine: "runtime-graph-tvf-inline",
3104                        result: self.execute_inline_graph_function(
3105                            &name,
3106                            &nodes,
3107                            &edges,
3108                            &named_args,
3109                        )?,
3110                        affected_rows: 0,
3111                        statement_type: "select",
3112                        bookmark: None,
3113                        notice: None,
3114                    });
3115                }
3116                if super::red_schema::is_virtual_table(&table.table) {
3117                    return Ok(RuntimeQueryResult {
3118                        query: query_str.to_string(),
3119                        mode,
3120                        statement,
3121                        engine: "runtime-red-schema",
3122                        result: super::red_schema::red_query(
3123                            self,
3124                            &table.table,
3125                            &table,
3126                            &scope as &dyn super::statement_frame::ReadFrame,
3127                        )?,
3128                        affected_rows: 0,
3129                        statement_type: "select",
3130                        bookmark: None,
3131                        notice: None,
3132                    });
3133                }
3134                // `<graph>.<output>` analytics virtual view (issue #800).
3135                if let Some(view_result) = self.try_resolve_analytics_view(
3136                    &table,
3137                    &scope as &dyn super::statement_frame::ReadFrame,
3138                )? {
3139                    return Ok(RuntimeQueryResult {
3140                        query: query_str.to_string(),
3141                        mode,
3142                        statement,
3143                        engine: "runtime-graph-analytics-view",
3144                        result: view_result,
3145                        affected_rows: 0,
3146                        statement_type: "select",
3147                        bookmark: None,
3148                        notice: None,
3149                    });
3150                }
3151                let Some(table_with_rls) = self.authorize_relational_table_select(
3152                    table,
3153                    &scope as &dyn super::statement_frame::ReadFrame,
3154                )?
3155                else {
3156                    return Ok(RuntimeQueryResult {
3157                        query: query_str.to_string(),
3158                        mode,
3159                        statement,
3160                        engine: "runtime-table-rls",
3161                        result: crate::storage::query::unified::UnifiedResult::empty(),
3162                        affected_rows: 0,
3163                        statement_type: "select",
3164                        bookmark: None,
3165                        notice: None,
3166                    });
3167                };
3168                Ok(RuntimeQueryResult {
3169                    query: query_str.to_string(),
3170                    mode,
3171                    statement,
3172                    engine: "runtime-table",
3173                    result: self.execute_table_with_having_exists(table_with_rls, &scope, None)?,
3174                    affected_rows: 0,
3175                    statement_type: "select",
3176                    bookmark: None,
3177                    notice: None,
3178                })
3179            }
3180            QueryExpr::Join(join) => {
3181                let scope = self.ai_scope();
3182                let Some(join_with_rls) = self.authorize_relational_join_select(
3183                    join,
3184                    &scope as &dyn super::statement_frame::ReadFrame,
3185                )?
3186                else {
3187                    return Ok(RuntimeQueryResult {
3188                        query: query_str.to_string(),
3189                        mode,
3190                        statement,
3191                        engine: "runtime-join-rls",
3192                        result: crate::storage::query::unified::UnifiedResult::empty(),
3193                        affected_rows: 0,
3194                        statement_type: "select",
3195                        bookmark: None,
3196                        notice: None,
3197                    });
3198                };
3199                Ok(RuntimeQueryResult {
3200                    query: query_str.to_string(),
3201                    mode,
3202                    statement,
3203                    engine: "runtime-join",
3204                    result: execute_runtime_join_query(self, &join_with_rls)?,
3205                    affected_rows: 0,
3206                    statement_type: "select",
3207                    bookmark: None,
3208                    notice: None,
3209                })
3210            }
3211            QueryExpr::Vector(vector) => Ok(RuntimeQueryResult {
3212                query: query_str.to_string(),
3213                mode,
3214                statement,
3215                engine: "runtime-vector",
3216                result: execute_runtime_vector_query(self, &vector)?,
3217                affected_rows: 0,
3218                statement_type: "select",
3219                bookmark: None,
3220                notice: None,
3221            }),
3222            QueryExpr::Hybrid(hybrid) => Ok(RuntimeQueryResult {
3223                query: query_str.to_string(),
3224                mode,
3225                statement,
3226                engine: "runtime-hybrid",
3227                result: execute_runtime_hybrid_query(self, &hybrid)?,
3228                affected_rows: 0,
3229                statement_type: "select",
3230                bookmark: None,
3231                notice: None,
3232            }),
3233            QueryExpr::Insert(ref insert) if super::red_schema::is_virtual_table(&insert.table) => {
3234                Err(RedDBError::Query(
3235                    super::red_schema::READ_ONLY_ERROR.to_string(),
3236                ))
3237            }
3238            QueryExpr::Update(ref update) if super::red_schema::is_virtual_table(&update.table) => {
3239                Err(RedDBError::Query(
3240                    super::red_schema::READ_ONLY_ERROR.to_string(),
3241                ))
3242            }
3243            QueryExpr::Delete(ref delete) if super::red_schema::is_virtual_table(&delete.table) => {
3244                Err(RedDBError::Query(
3245                    super::red_schema::READ_ONLY_ERROR.to_string(),
3246                ))
3247            }
3248            QueryExpr::Insert(ref insert) => self.execute_insert(query_str, insert),
3249            QueryExpr::Update(ref update) => self
3250                .with_deferred_store_wal_for_dml(self.update_may_emit_events(update), || {
3251                    self.execute_update(query_str, update)
3252                }),
3253            QueryExpr::Delete(ref delete) => self
3254                .with_deferred_store_wal_for_dml(self.delete_may_emit_events(delete), || {
3255                    self.execute_delete(query_str, delete)
3256                }),
3257            QueryExpr::QueueCommand(ref cmd) => self.with_deferred_store_wal_if_transaction(|| {
3258                self.execute_queue_command(query_str, cmd)
3259            }),
3260            QueryExpr::KvCommand(ref cmd) => self.execute_kv_command(query_str, cmd),
3261            QueryExpr::SearchCommand(ref cmd) => self.execute_search_command(query_str, cmd),
3262            QueryExpr::Ask(ref ask) => self.execute_ask(query_str, ask),
3263            _ => Err(RedDBError::Query(format!(
3264                "prepared-statement execution does not support {statement} statements"
3265            ))),
3266        }
3267    }
3268
3269    /// Dispatch a graph-collection table-valued function call in FROM
3270    /// position (e.g. `SELECT * FROM components(g)`).
3271    ///
3272    /// Validates the function name and arity here, materializes the whole
3273    /// active graph read-only, then runs the algorithm via the shared
3274    /// `dispatch_graph_algorithm` path. Never mutates the catalog or store.
3275    fn execute_table_function(
3276        &self,
3277        name: &str,
3278        args: &[String],
3279        named_args: &[(String, f64)],
3280    ) -> RedDBResult<crate::storage::query::unified::UnifiedResult> {
3281        if name.eq_ignore_ascii_case("red.diff") {
3282            return self.execute_vcs_diff_tvf(args, named_args);
3283        }
3284        if !is_graph_tvf_name(name) {
3285            return Err(RedDBError::Query(format!("unknown table function: {name}")));
3286        }
3287        // Every graph-collection TVF takes exactly one graph argument.
3288        if args.len() != 1 {
3289            return Err(RedDBError::Query(format!(
3290                "table function '{name}' takes exactly 1 graph argument, got {}",
3291                args.len()
3292            )));
3293        }
3294
3295        // Read-only materialization of the full active graph. Passing `None`
3296        // for the projection uses the full graph store. Like #795/#796, the
3297        // v0 form runs over the whole graph store regardless of the collection
3298        // argument value. Materialization never mutates any store.
3299        let (nodes, edges) = self.materialize_whole_graph_abstract()?;
3300        self.dispatch_graph_algorithm(name, nodes, edges, named_args)
3301    }
3302
3303    pub(crate) fn revive_versioned_updates_since(
3304        &self,
3305        conn_id: u64,
3306        stamper_xid: u64,
3307    ) -> RedDBResult<usize> {
3308        // Snapshot undo identities without retaining the journal while waiting
3309        // for topology. Writers take topology before recording their undo entry.
3310        let candidates = {
3311            let guard = self.inner.pending_versioned_updates.read();
3312            let Some(pending) = guard.get(&conn_id) else {
3313                return Ok(0);
3314            };
3315            pending
3316                .iter()
3317                .rev()
3318                .filter(|entry| entry.3 >= stamper_xid)
3319                .cloned()
3320                .collect::<Vec<_>>()
3321        };
3322        let mut reverted = 0usize;
3323        for candidate in candidates {
3324            let (collection, old_id, new_id, xid, previous_xmax) = &candidate;
3325            let topology_lock = self.index_store_ref().collection_topology_lock(collection);
3326            #[cfg(test)]
3327            self.index_store_ref().mutation_test_hook(
3328                collection,
3329                super::index_store::MutationTestPhase::BeforeUndoTopology,
3330            );
3331            let topology_guard = topology_lock.read();
3332            let mut guard = self.inner.pending_versioned_updates.write();
3333            let Some(pending) = guard.get_mut(&conn_id) else {
3334                continue;
3335            };
3336            // Revalidate after waiting. Remove only successfully restored entries;
3337            // an error leaves this entry and the remaining undo journal intact.
3338            let Some(position) = pending.iter().rposition(|entry| entry == &candidate) else {
3339                continue;
3340            };
3341            self.revive_versioned_update(
3342                collection,
3343                *old_id,
3344                *new_id,
3345                *xid,
3346                *previous_xmax,
3347                topology_guard,
3348            )?;
3349            pending.remove(position);
3350            reverted += 1;
3351            if pending.is_empty() {
3352                guard.remove(&conn_id);
3353            }
3354        }
3355        Ok(reverted)
3356    }
3357
3358    /// `EXPLAIN` is peeled off the statement text before parsing, so the
3359    /// planner ran on the inner statement with no privilege check at all:
3360    /// a read-only principal could plan any write and read the table's
3361    /// column list and row estimate back out of the plan. The plan needs
3362    /// exactly the privilege the statement it describes needs.
3363    fn check_explain_target_privilege(&self, inner_sql: &str) -> RedDBResult<()> {
3364        let parsed =
3365            reddb_rql::parser::parse(inner_sql).map_err(|e| RedDBError::Query(e.to_string()))?;
3366        self.check_query_privilege(&parsed.query)
3367            .map_err(|err| RedDBError::Query(format!("permission denied: {err}")))
3368    }
3369
3370    /// Wrap the planner's `RuntimeQueryExplain` as rows on a
3371    /// `RuntimeQueryResult` so callers over the SQL interface see the
3372    /// plan tree in the same shape a SELECT produces.
3373    ///
3374    /// Columns: `op`, `source`, `estimated_rows`, `estimated_cost`, `depth`.
3375    /// Nodes are walked depth-first; `depth` counts from 0 at the
3376    /// root so a text renderer can indent without re-walking.
3377    fn explain_as_rows(&self, raw_query: &str, inner_sql: &str) -> RedDBResult<RuntimeQueryResult> {
3378        self.check_explain_target_privilege(inner_sql)?;
3379        let explain = self.explain_query(inner_sql)?;
3380
3381        let mut columns = vec![
3382            "op".to_string(),
3383            "source".to_string(),
3384            "estimated_rows".to_string(),
3385            "estimated_cost".to_string(),
3386            "depth".to_string(),
3387        ];
3388
3389        let mut records: Vec<crate::storage::query::unified::UnifiedRecord> = Vec::new();
3390
3391        // Prepend `CteScan` markers when the query carried a leading
3392        // WITH clause. The CTE bodies are already inlined into the
3393        // main plan tree, but operators reading EXPLAIN need to see
3394        // which named CTEs were resolved — without this row the plan
3395        // would look indistinguishable from a hand-inlined query.
3396        for name in &explain.cte_materializations {
3397            use std::sync::Arc;
3398            let mut rec = crate::storage::query::unified::UnifiedRecord::default();
3399            rec.set_arc(Arc::from("op"), Value::text("CteScan".to_string()));
3400            rec.set_arc(Arc::from("source"), Value::text(name.clone()));
3401            rec.set_arc(Arc::from("estimated_rows"), Value::Float(0.0));
3402            rec.set_arc(Arc::from("estimated_cost"), Value::Float(0.0));
3403            rec.set_arc(Arc::from("depth"), Value::Integer(0));
3404            records.push(rec);
3405        }
3406
3407        let vector_details = explain.statement == "vector";
3408        if vector_details {
3409            columns.extend(["access_path_reason".to_string(), "index_hint".to_string()]);
3410        }
3411        walk_plan_node(&explain.logical_plan.root, 0, &mut records, vector_details);
3412
3413        let result = crate::storage::query::unified::UnifiedResult {
3414            columns,
3415            records,
3416            stats: Default::default(),
3417            pre_serialized_json: None,
3418        };
3419
3420        Ok(RuntimeQueryResult {
3421            query: raw_query.to_string(),
3422            mode: explain.mode,
3423            statement: "explain",
3424            engine: "runtime-explain",
3425            result,
3426            affected_rows: 0,
3427            statement_type: "select",
3428            bookmark: None,
3429            notice: None,
3430        })
3431    }
3432
3433    fn explain_analyze_vector_as_rows(
3434        &self,
3435        raw_query: &str,
3436        expr: QueryExpr,
3437    ) -> RedDBResult<RuntimeQueryResult> {
3438        let QueryExpr::Vector(query) = &expr else {
3439            return Err(RedDBError::Internal(
3440                "expected vector analysis target".to_string(),
3441            ));
3442        };
3443        let source = query.collection.clone();
3444        // The typed entry installs the full statement frame and privilege gate,
3445        // and cannot serve an earlier result-cache measurement as a fresh run.
3446        let execution = self.execute_query_expr(expr)?;
3447        let stats = execution.result.stats;
3448        let vector = stats.vector.as_ref().ok_or_else(|| {
3449            RedDBError::Internal("vector executor did not provide measurements".to_string())
3450        })?;
3451        let fields = vec![
3452            ("op", Value::text(vector.access_path.clone())),
3453            ("source", Value::text(source)),
3454            ("index_used", Value::Boolean(vector.index_used)),
3455            ("mode_requested", Value::text(vector.mode_requested.clone())),
3456            ("mode_executed", Value::text(vector.mode_executed.clone())),
3457            (
3458                "fallback_reason",
3459                vector
3460                    .fallback_reason
3461                    .as_ref()
3462                    .map_or(Value::Null, |reason| Value::text(reason.clone())),
3463            ),
3464            (
3465                "approximate_distance_evaluations",
3466                Value::UnsignedInteger(vector.approximate_distance_evaluations),
3467            ),
3468            (
3469                "peak_topk_entries",
3470                Value::UnsignedInteger(vector.peak_topk_entries),
3471            ),
3472            (
3473                "candidates_examined",
3474                Value::UnsignedInteger(vector.candidates_examined),
3475            ),
3476            (
3477                "metadata_rejected",
3478                Value::UnsignedInteger(vector.metadata_rejected),
3479            ),
3480            ("rls_rejected", Value::UnsignedInteger(vector.rls_rejected)),
3481            (
3482                "visibility_rejected",
3483                Value::UnsignedInteger(vector.visibility_rejected),
3484            ),
3485            (
3486                "exact_distance_evaluations",
3487                Value::UnsignedInteger(vector.exact_distance_evaluations),
3488            ),
3489            ("actual_rows", Value::UnsignedInteger(vector.rows_returned)),
3490            (
3491                "actual_ms",
3492                Value::Float(stats.exec_time_us as f64 / 1000.0),
3493            ),
3494            ("metrics_scope", Value::text("vector_pipeline")),
3495            (
3496                "operators",
3497                Value::Json(vector.operators_json().to_string().into_bytes()),
3498            ),
3499        ];
3500        let columns = fields.iter().map(|(name, _)| name.to_string()).collect();
3501        let mut record = crate::storage::query::unified::UnifiedRecord::default();
3502        for (name, value) in fields {
3503            record.set_owned(name.to_string(), value);
3504        }
3505        Ok(RuntimeQueryResult {
3506            query: raw_query.to_string(),
3507            mode: execution.mode,
3508            statement: "explain_analyze",
3509            engine: "runtime-explain-analyze",
3510            result: crate::storage::query::unified::UnifiedResult {
3511                columns,
3512                records: vec![record],
3513                stats,
3514                pre_serialized_json: None,
3515            },
3516            affected_rows: 0,
3517            statement_type: "select",
3518            bookmark: None,
3519            notice: None,
3520        })
3521    }
3522
3523    fn explain_analyze_as_rows(
3524        &self,
3525        raw_query: &str,
3526        inner_sql: &str,
3527    ) -> RedDBResult<RuntimeQueryResult> {
3528        if strip_keyword_ci(inner_sql.trim_start(), "VECTOR").is_some() {
3529            let expr = parse_multi(inner_sql).map_err(|err| RedDBError::Query(err.to_string()))?;
3530            if matches!(&expr, QueryExpr::Vector(_)) {
3531                return self.explain_analyze_vector_as_rows(raw_query, expr);
3532            }
3533        }
3534        if !starts_with_dml_keyword(inner_sql) {
3535            return Err(RedDBError::Query(
3536                "EXPLAIN ANALYZE currently supports INSERT, UPDATE, DELETE, and VECTOR SEARCH"
3537                    .to_string(),
3538            ));
3539        }
3540
3541        self.check_explain_target_privilege(inner_sql)?;
3542        let explain = self.explain_query(inner_sql)?;
3543        let conn_id = current_connection_id();
3544        if self.inner.transaction_state.in_transaction(conn_id) {
3545            return Err(RedDBError::Query(
3546                "EXPLAIN ANALYZE requires no active transaction".to_string(),
3547            ));
3548        }
3549
3550        self.execute_query_inner("BEGIN")?;
3551        let started = std::time::Instant::now();
3552        let execution = self.execute_query_inner(inner_sql);
3553        let elapsed_ms = started.elapsed().as_secs_f64() * 1000.0;
3554        let rollback = self.execute_query_inner("ROLLBACK");
3555
3556        let affected_rows = match execution {
3557            Ok(result) => result.affected_rows,
3558            Err(err) => {
3559                rollback?;
3560                return Err(err);
3561            }
3562        };
3563        rollback?;
3564
3565        let columns = vec![
3566            "op".to_string(),
3567            "source".to_string(),
3568            "estimated_rows".to_string(),
3569            "estimated_cost".to_string(),
3570            "actual_rows".to_string(),
3571            "actual_ms".to_string(),
3572            "depth".to_string(),
3573        ];
3574        let mut records = Vec::new();
3575        walk_analyze_plan_node(
3576            &explain.logical_plan.root,
3577            0,
3578            affected_rows,
3579            elapsed_ms,
3580            &mut records,
3581        );
3582
3583        let result = crate::storage::query::unified::UnifiedResult {
3584            columns,
3585            records,
3586            stats: Default::default(),
3587            pre_serialized_json: None,
3588        };
3589
3590        Ok(RuntimeQueryResult {
3591            query: raw_query.to_string(),
3592            mode: explain.mode,
3593            statement: "explain_analyze",
3594            engine: "runtime-explain-analyze",
3595            result,
3596            affected_rows: 0,
3597            statement_type: "select",
3598            bookmark: None,
3599            notice: None,
3600        })
3601    }
3602}
3603
3604fn redact_sql_for_slow_log(query: &str) -> String {
3605    let lowered = query.to_ascii_lowercase();
3606    if lowered.contains("secret") || lowered.contains("vault") {
3607        return "secret statement (SQL redacted)".to_string();
3608    }
3609    let credential_candidate = lowered.contains("password")
3610        && ((lowered.contains("create") && lowered.contains("user"))
3611            || (lowered.contains("alter") && lowered.contains("user")));
3612    if !credential_candidate {
3613        return query.to_string();
3614    }
3615    match parse_multi(query) {
3616        Ok(QueryExpr::CreateUser(stmt)) => {
3617            let target = UserId::from_parts(stmt.tenant.as_deref(), &stmt.username);
3618            format!("CREATE USER {target} PASSWORD '***' ROLE {}", stmt.role)
3619        }
3620        Ok(QueryExpr::AlterUser(stmt))
3621            if stmt
3622                .attributes
3623                .iter()
3624                .any(|attr| matches!(attr, reddb_rql::ast::AlterUserAttribute::Password(_))) =>
3625        {
3626            let target = UserId::from_parts(stmt.tenant.as_deref(), &stmt.username);
3627            format!("ALTER USER {target} PASSWORD '***'")
3628        }
3629        Ok(_) => "credential statement (SQL redacted)".to_string(),
3630        Err(_) => "credential statement (SQL redacted)".to_string(),
3631    }
3632}
3633
3634fn strip_explain_analyze_prefix(sql: &str) -> Option<&str> {
3635    let rest = strip_keyword_ci(sql.trim_start(), "EXPLAIN")?.trim_start();
3636    Some(strip_keyword_ci(rest, "ANALYZE")?.trim_start()).filter(|inner| !inner.is_empty())
3637}
3638
3639fn strip_keyword_ci<'a>(sql: &'a str, keyword: &str) -> Option<&'a str> {
3640    // `get` is None past the end or inside a multi-byte character, where
3641    // `split_at` would panic (and a release build aborts on panic).
3642    let head = sql.get(..keyword.len())?;
3643    let rest = &sql[keyword.len()..];
3644    if !head.eq_ignore_ascii_case(keyword) {
3645        return None;
3646    }
3647    if rest
3648        .chars()
3649        .next()
3650        .is_some_and(|ch| !ch.is_ascii_whitespace())
3651    {
3652        return None;
3653    }
3654    Some(rest)
3655}
3656
3657fn starts_with_dml_keyword(sql: &str) -> bool {
3658    let trimmed = sql.trim_start();
3659    let head_end = trimmed
3660        .find(|ch: char| ch.is_ascii_whitespace())
3661        .unwrap_or(trimmed.len());
3662    let head = &trimmed[..head_end];
3663    head.eq_ignore_ascii_case("INSERT")
3664        || head.eq_ignore_ascii_case("UPDATE")
3665        || head.eq_ignore_ascii_case("DELETE")
3666}
3667
3668fn walk_plan_node(
3669    node: &crate::storage::query::planner::CanonicalLogicalNode,
3670    depth: usize,
3671    out: &mut Vec<crate::storage::query::unified::UnifiedRecord>,
3672    vector_details: bool,
3673) {
3674    use std::sync::Arc;
3675    let mut rec = crate::storage::query::unified::UnifiedRecord::default();
3676    rec.set_arc(Arc::from("op"), Value::text(node.operator.clone()));
3677    rec.set_arc(
3678        Arc::from("source"),
3679        node.source.clone().map(Value::text).unwrap_or(Value::Null),
3680    );
3681    rec.set_arc(
3682        Arc::from("estimated_rows"),
3683        Value::Float(node.estimated_rows),
3684    );
3685    rec.set_arc(
3686        Arc::from("estimated_cost"),
3687        Value::Float(node.operator_cost),
3688    );
3689    rec.set_arc(Arc::from("depth"), Value::Integer(depth as i64));
3690    if vector_details {
3691        for name in ["access_path_reason", "index_hint"] {
3692            rec.set_owned(
3693                name.to_string(),
3694                node.details
3695                    .get(name)
3696                    .cloned()
3697                    .map(Value::text)
3698                    .unwrap_or(Value::Null),
3699            );
3700        }
3701    }
3702    out.push(rec);
3703    for child in &node.children {
3704        walk_plan_node(child, depth + 1, out, vector_details);
3705    }
3706}
3707
3708fn walk_analyze_plan_node(
3709    node: &crate::storage::query::planner::CanonicalLogicalNode,
3710    depth: usize,
3711    affected_rows: u64,
3712    elapsed_ms: f64,
3713    out: &mut Vec<crate::storage::query::unified::UnifiedRecord>,
3714) {
3715    use std::sync::Arc;
3716    let mut rec = crate::storage::query::unified::UnifiedRecord::default();
3717    rec.set_arc(Arc::from("op"), Value::text(node.operator.clone()));
3718    rec.set_arc(
3719        Arc::from("source"),
3720        node.source.clone().map(Value::text).unwrap_or(Value::Null),
3721    );
3722    rec.set_arc(
3723        Arc::from("estimated_rows"),
3724        Value::Float(node.estimated_rows),
3725    );
3726    rec.set_arc(
3727        Arc::from("estimated_cost"),
3728        Value::Float(node.operator_cost),
3729    );
3730    rec.set_arc(
3731        Arc::from("actual_rows"),
3732        Value::UnsignedInteger(if depth == 0 { affected_rows } else { 0 }),
3733    );
3734    rec.set_arc(
3735        Arc::from("actual_ms"),
3736        Value::Float(if depth == 0 { elapsed_ms } else { 0.0 }),
3737    );
3738    rec.set_arc(Arc::from("depth"), Value::Integer(depth as i64));
3739    out.push(rec);
3740
3741    for child in &node.children {
3742        walk_analyze_plan_node(child, depth + 1, 0, 0.0, out);
3743    }
3744}
3745
3746#[cfg(test)]
3747mod declared_model_validation_tests {
3748    use super::*;
3749    use crate::catalog::CollectionModel;
3750    use crate::storage::no_malloc_hot_paths::measure_allocations;
3751    use reddb_rql::ast::KvCommand;
3752
3753    fn get(collection: &str) -> QueryExpr {
3754        QueryExpr::KvCommand(KvCommand::Get {
3755            model: CollectionModel::Kv,
3756            collection: collection.into(),
3757            key: "item".into(),
3758        })
3759    }
3760
3761    #[test]
3762    fn declared_model_validation_keeps_mismatches_and_observes_contract_changes() {
3763        let runtime = RedDBRuntime::in_memory().expect("runtime");
3764        runtime
3765            .execute_query("KV PUT declared.item = 1")
3766            .expect("seed");
3767        runtime
3768            .validate_model_operations_before_auth(&get("declared"))
3769            .expect("KV contract");
3770        let db = runtime.db();
3771        for (model, name) in [
3772            (CollectionModel::Table, "table"),
3773            (CollectionModel::Mixed, "mixed"),
3774        ] {
3775            let mut contract = db.collection_contract("declared").expect("contract");
3776            contract.declared_model = model;
3777            db.save_collection_contract(contract)
3778                .expect("replace contract");
3779            let error = runtime
3780                .validate_model_operations_before_auth(&get("declared"))
3781                .expect_err("mismatch");
3782            assert_eq!(
3783                error.to_string(),
3784                format!("INVALID_OPERATION: model mismatch: expected kv, got {name}")
3785            );
3786        }
3787    }
3788
3789    #[test]
3790    fn declared_model_validation_preserves_legacy_inference_and_missing_collections() {
3791        let runtime = RedDBRuntime::in_memory().expect("runtime");
3792        let db = runtime.db();
3793        let store = db.store();
3794        store
3795            .create_collection("legacy")
3796            .expect("legacy collection");
3797        store
3798            .get_collection("legacy")
3799            .expect("manager")
3800            .insert(crate::storage::UnifiedEntity::table_row(
3801                crate::storage::EntityId::new(1),
3802                "legacy",
3803                1,
3804                Vec::new(),
3805            ))
3806            .expect("uncontracted table row");
3807        assert!(db.collection_contract("legacy").is_none());
3808        let error = runtime
3809            .validate_model_operations_before_auth(&get("legacy"))
3810            .expect_err("inferred table");
3811        assert!(error
3812            .to_string()
3813            .contains("model mismatch: expected kv, got table"));
3814        runtime
3815            .validate_model_operations_before_auth(&get("missing"))
3816            .expect("missing stays deferred to execution");
3817    }
3818
3819    #[test]
3820    fn declared_model_validation_does_not_treat_orphan_contracts_as_collections() {
3821        let runtime = RedDBRuntime::in_memory().expect("runtime");
3822        runtime
3823            .execute_query("KV PUT declared.item = 1")
3824            .expect("seed");
3825        let db = runtime.db();
3826        let mut contract = db.collection_contract("declared").expect("contract");
3827        contract.name = "orphan".into();
3828        contract.declared_model = CollectionModel::Table;
3829        db.save_collection_contract(contract)
3830            .expect("orphan contract");
3831        assert!(db.store().get_collection("orphan").is_none());
3832        runtime
3833            .validate_model_operations_before_auth(&get("orphan"))
3834            .expect("no physical collection to validate");
3835    }
3836
3837    #[test]
3838    fn declared_model_validation_allocates_nothing_with_unrelated_collections() {
3839        let runtime = RedDBRuntime::in_memory().expect("runtime");
3840        runtime
3841            .execute_query("KV PUT declared.item = 1")
3842            .expect("seed");
3843        let expr = get("declared");
3844        for unrelated in [0, 64] {
3845            let db = runtime.db();
3846            let store = db.store();
3847            for index in 0..unrelated {
3848                let name = format!("unrelated_{index}");
3849                store
3850                    .create_collection(&name)
3851                    .expect("unrelated collection");
3852            }
3853            runtime
3854                .validate_model_operations_before_auth(&expr)
3855                .expect("warm contract cache");
3856            let (result, count) =
3857                measure_allocations(|| runtime.validate_model_operations_before_auth(&expr));
3858            result.expect("declared KV");
3859            assert_eq!(
3860                count.allocs, 0,
3861                "validation must only borrow the target contract"
3862            );
3863        }
3864    }
3865}
3866
3867#[cfg(test)]
3868mod multibyte_sql_tests {
3869    use super::*;
3870
3871    #[test]
3872    fn explain_analyze_prefix_ignores_multibyte_text_at_the_keyword_boundary() {
3873        // `strip_keyword_ci` used `split_at(keyword.len())`, which panics when
3874        // that byte offset is inside a multi-byte character.
3875        for pad in 0..16 {
3876            for wide in ["é", "日", "😀"] {
3877                let sql = format!("{}{wide}llo", "a".repeat(pad));
3878                assert_eq!(strip_explain_analyze_prefix(&sql), None, "{sql:?}");
3879            }
3880        }
3881        assert_eq!(
3882            strip_explain_analyze_prefix("explain  analyze DELETE FROM t"),
3883            Some("DELETE FROM t")
3884        );
3885    }
3886
3887    /// One malformed or unusual statement must never take the process down:
3888    /// release builds abort on panic, so any panic reachable from
3889    /// `execute_query` is a remote denial of service. Put a multi-byte
3890    /// character at every byte offset a keyword matcher might slice at.
3891    #[test]
3892    fn multibyte_sql_never_panics_execute_query() {
3893        let rt = RedDBRuntime::in_memory().expect("in-memory runtime");
3894        let seeds = [
3895            "",
3896            "SELECT ",
3897            "SELECT '",
3898            "EXPLAIN ",
3899            "EXPLAIN ANALYZE ",
3900            "CHECKPOINT ",
3901            "CHECKOUT ",
3902            "RESET ",
3903            "MERGE ",
3904            "CHERRY PICK ",
3905            "REVERT ",
3906            "RESOLVE CONFLICT ",
3907            "INSERT INTO t VALUES ('",
3908        ];
3909        let mut panicked = Vec::new();
3910        for seed in seeds {
3911            for pad in 0..16 {
3912                for wide in ["é", "日", "😀"] {
3913                    let sql = format!("{seed}{}{wide}llo", "a".repeat(pad));
3914                    let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
3915                        let _ = rt.execute_query(&sql);
3916                    }));
3917                    if outcome.is_err() {
3918                        panicked.push(sql);
3919                    }
3920                }
3921            }
3922        }
3923        assert!(
3924            panicked.is_empty(),
3925            "execute_query panicked on {} statement(s), first: {:?}",
3926            panicked.len(),
3927            panicked.first()
3928        );
3929    }
3930}
3931
3932#[cfg(test)]
3933mod inline_graph_tvf_tests {
3934    use super::*;
3935
3936    fn scopes_for(sql: &str) -> HashSet<String> {
3937        let expr = reddb_rql::parser::parse(sql).expect("parse").query;
3938        query_expr_result_cache_scopes(&expr)
3939    }
3940
3941    #[test]
3942    fn inline_tvf_cache_scopes_include_source_collections() {
3943        // The result-cache key for the inline form must derive from the
3944        // `nodes`/`edges` source collections so a write to either invalidates
3945        // the cached result (issue #799).
3946        let scopes = scopes_for(
3947            "SELECT * FROM components(nodes => (SELECT id FROM hosts), edges => (SELECT src, dst FROM links))",
3948        );
3949        assert!(scopes.contains("hosts"), "nodes source scoped: {scopes:?}");
3950        assert!(scopes.contains("links"), "edges source scoped: {scopes:?}");
3951    }
3952
3953    #[test]
3954    fn graph_collection_tvf_cache_scope_is_graph_argument() {
3955        // The graph-collection form still materializes the active graph, but
3956        // result-cache invalidation is scoped to the named graph argument so
3957        // INSERT INTO g NODE/EDGE invalidates cached TVF rows.
3958        let scopes = scopes_for("SELECT * FROM components(g)");
3959        assert!(scopes.contains("g"), "collection form scoped: {scopes:?}");
3960    }
3961
3962    #[test]
3963    fn abstract_degree_centrality_counts_undirected_endpoints() {
3964        let nodes = vec!["a".to_string(), "b".to_string(), "c".to_string()];
3965        let edges = vec![
3966            ("a".to_string(), "b".to_string(), 1.0_f32),
3967            ("b".to_string(), "c".to_string(), 1.0_f32),
3968        ];
3969        let degrees = abstract_degree_centrality(&nodes, &edges);
3970        assert_eq!(
3971            degrees,
3972            vec![
3973                ("a".to_string(), 1),
3974                ("b".to_string(), 2),
3975                ("c".to_string(), 1),
3976            ]
3977        );
3978    }
3979}
3980
3981/// Vault keys the engine itself owns. `SET SECRET` / `DELETE SECRET` share
3982/// the vault KV space with the IAM policy blobs, the attachment tables and
3983/// the `SECRET()` column master key; letting a principal with `secret:write`
3984/// overwrite them is an escalation (allow-all policy after restart) or a
3985/// permanent data loss (rotated AES key). Provider credentials under
3986/// `red.secret.ai.*` stay writable — that is the documented use.
3987fn reject_engine_internal_vault_key(key: &str) -> RedDBResult<()> {
3988    let lowered = key.to_ascii_lowercase();
3989    let internal = lowered == "red.secret.aes_key"
3990        || lowered.starts_with("red.iam.")
3991        || lowered.starts_with("red.acl.")
3992        || lowered.starts_with("red.vault.");
3993    if internal {
3994        return Err(RedDBError::Query(format!(
3995            "`{key}` is an engine-internal vault key and cannot be set or deleted through SET/DELETE SECRET"
3996        )));
3997    }
3998    Ok(())
3999}
4000
4001/// Optional confinement for `COPY … FROM '<path>'`. When
4002/// `REDDB_COPY_IMPORT_ROOT` is set, the (canonicalised) source path must live
4003/// under that directory; otherwise the statement is refused. Unset keeps the
4004/// historical behaviour (any readable file, admin-only via the privilege
4005/// gate).
4006fn confine_copy_from_path(path: &str) -> RedDBResult<()> {
4007    let Ok(root) = std::env::var("REDDB_COPY_IMPORT_ROOT") else {
4008        return Ok(());
4009    };
4010    let root = std::fs::canonicalize(&root).map_err(|e| {
4011        RedDBError::Query(format!(
4012            "REDDB_COPY_IMPORT_ROOT `{root}` is not usable: {e}"
4013        ))
4014    })?;
4015    let resolved = std::fs::canonicalize(path)
4016        .map_err(|e| RedDBError::Query(format!("COPY FROM `{path}`: {e}")))?;
4017    if !resolved.starts_with(&root) || !resolved.is_file() {
4018        return Err(RedDBError::Query(format!(
4019            "COPY FROM `{path}` is outside the configured import root"
4020        )));
4021    }
4022    Ok(())
4023}
4024
4025#[cfg(test)]
4026mod result_cache_execution_tests {
4027    use super::*;
4028
4029    const QUERY: &str = "SELECT SUM(n) AS n FROM result_cache_probe";
4030
4031    fn runtime_with_rows(cache_enabled: bool) -> RedDBRuntime {
4032        let runtime = RedDBRuntime::in_memory().expect("runtime");
4033        runtime
4034            .execute_query("CREATE TABLE result_cache_probe (id INT, n INT)")
4035            .expect("create table");
4036        runtime
4037            .execute_query(
4038                "INSERT INTO result_cache_probe (id, n) VALUES (1, 10), (2, 20), (3, 30)",
4039            )
4040            .expect("seed rows");
4041        runtime
4042            .execute_query(&format!(
4043                "SET CONFIG runtime.result_cache.enabled = {cache_enabled}"
4044            ))
4045            .expect("configure result cache");
4046        runtime
4047    }
4048
4049    fn aggregate_value(runtime: &RedDBRuntime) -> i64 {
4050        let result = runtime.execute_query(QUERY).expect("aggregate query");
4051        match result.result.records[0].get("n") {
4052            Some(reddb_types::Value::Integer(value)) => *value,
4053            other => panic!("expected integer aggregate, got {other:?}"),
4054        }
4055    }
4056
4057    #[test]
4058    fn hot_hit_bypasses_query_execution_pipeline() {
4059        let runtime = runtime_with_rows(true);
4060        reset_result_cache_miss_executions();
4061        let before = runtime.result_cache_metrics();
4062
4063        assert_eq!(aggregate_value(&runtime), 60);
4064        assert_eq!(result_cache_miss_executions(), 1);
4065        assert_eq!(aggregate_value(&runtime), 60);
4066
4067        let after = runtime.result_cache_metrics();
4068        assert_eq!(
4069            result_cache_miss_executions(),
4070            1,
4071            "hit re-entered the executor"
4072        );
4073        assert_eq!(after.0 - before.0, 1, "second read must be a cache hit");
4074        assert_eq!(after.1 - before.1, 1, "first read must populate the cache");
4075    }
4076
4077    #[test]
4078    fn disabled_cache_executes_every_read() {
4079        let runtime = runtime_with_rows(false);
4080        reset_result_cache_miss_executions();
4081        let before = runtime.result_cache_metrics();
4082
4083        assert_eq!(aggregate_value(&runtime), 60);
4084        assert_eq!(aggregate_value(&runtime), 60);
4085
4086        assert_eq!(result_cache_miss_executions(), 2);
4087        assert_eq!(
4088            runtime.result_cache_metrics(),
4089            before,
4090            "disabled cache must not report lookups"
4091        );
4092    }
4093
4094    #[test]
4095    fn table_write_forces_one_reexecution_then_hits_again() {
4096        let runtime = runtime_with_rows(true);
4097        assert_eq!(aggregate_value(&runtime), 60);
4098        assert_eq!(aggregate_value(&runtime), 60);
4099        runtime
4100            .execute_query("INSERT INTO result_cache_probe (id, n) VALUES (4, 40)")
4101            .expect("mutate cached table");
4102        reset_result_cache_miss_executions();
4103        let before = runtime.result_cache_metrics();
4104
4105        assert_eq!(aggregate_value(&runtime), 100);
4106        assert_eq!(result_cache_miss_executions(), 1);
4107        assert_eq!(aggregate_value(&runtime), 100);
4108
4109        let after = runtime.result_cache_metrics();
4110        assert_eq!(result_cache_miss_executions(), 1);
4111        assert_eq!(after.0 - before.0, 1, "post-write result must become hot");
4112        assert_eq!(
4113            after.1 - before.1,
4114            1,
4115            "write must invalidate the old result"
4116        );
4117    }
4118}
4119
4120#[cfg(test)]
4121mod security_gate_tests {
4122    use super::*;
4123    use crate::auth::store::AuthStore;
4124    use crate::auth::{AuthConfig, Role};
4125
4126    /// Clears the thread-local identity on drop so one test's principal
4127    /// never leaks into the next on a shared thread.
4128    struct IdentityGuard;
4129
4130    impl IdentityGuard {
4131        fn install(username: &str, role: Role) -> Self {
4132            set_current_auth_identity(username.to_string(), role);
4133            Self
4134        }
4135    }
4136
4137    impl Drop for IdentityGuard {
4138        fn drop(&mut self) {
4139            clear_current_auth_identity();
4140        }
4141    }
4142
4143    struct ScopedIdentityGuard;
4144
4145    impl ScopedIdentityGuard {
4146        fn install(tenant: &str, username: &str, role: Role) -> Self {
4147            crate::runtime::execution_context::set_current_auth_principal(
4148                crate::auth::UserId::scoped(tenant, username),
4149                role,
4150            );
4151            set_current_tenant(tenant.to_string());
4152            Self
4153        }
4154    }
4155
4156    impl Drop for ScopedIdentityGuard {
4157        fn drop(&mut self) {
4158            clear_current_auth_identity();
4159            clear_current_tenant();
4160        }
4161    }
4162
4163    fn runtime_with_user(username: &str, role: Role) -> RedDBRuntime {
4164        let store = std::sync::Arc::new(AuthStore::new(AuthConfig {
4165            enabled: true,
4166            session_ttl_secs: 60,
4167            require_auth: true,
4168            auto_encrypt_storage: false,
4169            vault_enabled: false,
4170            cert: Default::default(),
4171            oauth: Default::default(),
4172        }));
4173        store.create_user(username, "pw", role).expect("user");
4174        let runtime =
4175            RedDBRuntime::with_options(crate::api::RedDBOptions::in_memory()).expect("runtime");
4176        runtime.set_auth_store(store);
4177        runtime
4178    }
4179
4180    fn runtime_with_store(username: &str, role: Role) -> (RedDBRuntime, std::sync::Arc<AuthStore>) {
4181        let store = std::sync::Arc::new(AuthStore::new(AuthConfig {
4182            enabled: true,
4183            session_ttl_secs: 60,
4184            require_auth: true,
4185            auto_encrypt_storage: false,
4186            vault_enabled: false,
4187            cert: Default::default(),
4188            oauth: Default::default(),
4189        }));
4190        store.create_user(username, "pw", role).expect("user");
4191        let runtime =
4192            RedDBRuntime::with_options(crate::api::RedDBOptions::in_memory()).expect("runtime");
4193        runtime.set_auth_store(std::sync::Arc::clone(&store));
4194        (runtime, store)
4195    }
4196
4197    #[test]
4198    fn tenant_credential_cannot_override_credential_scope() {
4199        use crate::runtime::within_clause::{FieldOverride, ScopeOverride};
4200
4201        let store = std::sync::Arc::new(AuthStore::new(AuthConfig {
4202            enabled: true,
4203            require_auth: true,
4204            ..AuthConfig::default()
4205        }));
4206        store
4207            .create_user_in_tenant(Some("acme"), "admin", "pw", Role::Admin)
4208            .expect("tenant admin");
4209        let runtime =
4210            RedDBRuntime::with_options(crate::api::RedDBOptions::in_memory()).expect("runtime");
4211        runtime.set_auth_store(store);
4212        let _identity = ScopedIdentityGuard::install("acme", "admin", Role::Admin);
4213
4214        runtime
4215            .execute_query("WITHIN TENANT 'acme' SELECT 1")
4216            .expect("own tenant remains valid");
4217        for sql in [
4218            "WITHIN TENANT 'globex' SELECT 1",
4219            "WITHIN TENANT NULL SELECT 1",
4220            "WITHIN TENANT 'acme' USER 'other' SELECT 1",
4221            "WITHIN TENANT 'acme' AS ROLE 'read' SELECT 1",
4222        ] {
4223            assert!(runtime.execute_query(sql).is_err(), "must reject {sql}");
4224        }
4225        assert!(runtime
4226            .execute_query_with_scope(
4227                "SELECT 1",
4228                ScopeOverride {
4229                    tenant: FieldOverride::Set("globex".to_string()),
4230                    ..ScopeOverride::default()
4231                },
4232            )
4233            .is_err());
4234
4235        set_current_connection_id(44_201);
4236        runtime.execute_query("BEGIN").expect("begin");
4237        assert!(runtime.execute_query("SET LOCAL TENANT 'globex'").is_err());
4238        runtime.execute_query("ROLLBACK").expect("rollback");
4239        clear_current_connection_id();
4240    }
4241
4242    #[test]
4243    fn tenant_admin_sql_user_lifecycle_is_tenant_bounded() {
4244        let store = std::sync::Arc::new(AuthStore::new(AuthConfig {
4245            enabled: true,
4246            require_auth: true,
4247            ..AuthConfig::default()
4248        }));
4249        store
4250            .create_user_in_tenant(Some("acme"), "admin", "pw", Role::Admin)
4251            .expect("tenant admin");
4252        let runtime =
4253            RedDBRuntime::with_options(crate::api::RedDBOptions::in_memory()).expect("runtime");
4254        runtime.set_auth_store(std::sync::Arc::clone(&store));
4255        let _identity = ScopedIdentityGuard::install("acme", "admin", Role::Admin);
4256
4257        runtime
4258            .execute_query("CREATE USER acme.alice PASSWORD 'pw' ROLE read")
4259            .expect("same-tenant create");
4260        assert!(runtime
4261            .execute_query("CREATE USER globex.alice PASSWORD 'pw' ROLE read")
4262            .is_err());
4263        assert!(runtime
4264            .execute_query("ALTER USER globex.alice PASSWORD 'owned'")
4265            .is_err());
4266        let cross_tenant_allow = crate::auth::policies::Policy::from_json_str(
4267            r#"{
4268                "id":"tenant-cross-user",
4269                "version":1,
4270                "statements":[{
4271                    "effect":"allow",
4272                    "actions":["user:create","user:password:change"],
4273                    "resources":["user:tenant/globex/*"]
4274                }]
4275            }"#,
4276        )
4277        .expect("cross-tenant policy");
4278        store.put_policy(cross_tenant_allow).expect("put policy");
4279        store
4280            .attach_policy(
4281                crate::auth::store::PrincipalRef::User(crate::auth::UserId::scoped(
4282                    "acme", "admin",
4283                )),
4284                "tenant-cross-user",
4285            )
4286            .expect("attach policy");
4287        assert!(runtime
4288            .execute_query("CREATE USER globex.bob PASSWORD 'pw' ROLE read")
4289            .is_err());
4290        assert!(store.get_user(Some("globex"), "alice").is_none());
4291        assert!(store.get_user(Some("globex"), "bob").is_none());
4292    }
4293
4294    #[test]
4295    fn slow_log_redacts_user_password_statements() {
4296        for sql in [
4297            "CREATE USER alice PASSWORD 'super-secret' ROLE admin",
4298            "CREATE USER acme.alice PASSWORD 'super-secret' ROLE read",
4299            "ALTER USER alice PASSWORD 'super-secret'",
4300            "AlTeR UsEr acme.alice PaSsWoRd 'super-secret'",
4301            "EXPLAIN CREATE USER alice PASSWORD 'super-secret' ROLE read",
4302            "EXPLAIN ALTER USER alice PASSWORD 'super-secret'",
4303            "ALTER USER alice PASSWORD 'unterminated",
4304        ] {
4305            let redacted = redact_sql_for_slow_log(sql);
4306            assert!(!redacted.contains("super-secret"), "leaked from {sql}");
4307            assert!(!redacted.contains("unterminated"), "leaked from {sql}");
4308        }
4309        assert_eq!(
4310            redact_sql_for_slow_log("SELECT password FROM accounts"),
4311            "SELECT password FROM accounts"
4312        );
4313    }
4314
4315    #[test]
4316    fn nested_reads_need_select_on_the_inner_table() {
4317        use crate::auth::privileges::{Action, GrantPrincipal, Resource};
4318        use crate::auth::UserId;
4319        let (runtime, store) = runtime_with_store("ro", Role::Read);
4320        runtime
4321            .execute_query("CREATE TABLE gate_open (a INTEGER)")
4322            .expect("create");
4323        runtime
4324            .execute_query("CREATE TABLE gate_closed (b INTEGER)")
4325            .expect("create");
4326        // One explicit grant switches the legacy fallback off, so `ro`
4327        // may read exactly `gate_open`.
4328        store
4329            .grant(
4330                &UserId::from_parts(None, "admin"),
4331                Role::Admin,
4332                GrantPrincipal::User(UserId::from_parts(None, "ro")),
4333                Resource::table_from_name("gate_open"),
4334                vec![Action::Select],
4335                false,
4336                None,
4337            )
4338            .expect("grant");
4339        let _identity = IdentityGuard::install("ro", Role::Read);
4340        runtime
4341            .execute_query("SELECT * FROM (SELECT a FROM gate_open) s")
4342            .expect("derived table over a granted table is fine");
4343        // The outer statement names only the synthetic subquery table, so
4344        // the inner table used to be read with no check at all.
4345        for sql in [
4346            "SELECT * FROM (SELECT b FROM gate_closed) s",
4347            "SELECT a FROM gate_open WHERE a IN (SELECT b FROM gate_closed)",
4348        ] {
4349            let err = runtime
4350                .execute_query(sql)
4351                .expect_err("nested read of an ungranted table must be refused");
4352            assert!(
4353                err.to_string().contains("permission denied"),
4354                "{sql}: unexpected error: {err}"
4355            );
4356        }
4357    }
4358
4359    #[test]
4360    fn policy_listings_are_self_or_policy_management() {
4361        let (runtime, store) = runtime_with_store("ro", Role::Read);
4362        store.create_user("other", "pw", Role::Read).expect("user");
4363        let _identity = IdentityGuard::install("ro", Role::Read);
4364        runtime
4365            .execute_query("SHOW EFFECTIVE PERMISSIONS FOR ro")
4366            .expect("a principal may inspect its own permissions");
4367        let err = runtime
4368            .execute_query("SHOW EFFECTIVE PERMISSIONS FOR other")
4369            .expect_err("inspecting another principal is policy management");
4370        assert!(
4371            err.to_string().contains("permission denied"),
4372            "unexpected error: {err}"
4373        );
4374    }
4375
4376    #[test]
4377    fn secret_columns_stay_masked_for_readers_without_secret_read() {
4378        use reddb_types::Value;
4379        let (runtime, store) = runtime_with_store("ro", Role::Read);
4380        store.create_user("root", "pw", Role::Admin).expect("admin");
4381        store.ensure_vault_secret_key();
4382        runtime
4383            .execute_query(
4384                "INSERT INTO creds_gate (name, token) VALUES ('stripe', SECRET('sk_live_abc'))",
4385            )
4386            .expect("insert");
4387
4388        let token_for = |username: &str, role: Role| {
4389            let _identity = IdentityGuard::install(username, role);
4390            let result = runtime
4391                .execute_query("SELECT name, token FROM creds_gate")
4392                .expect("select");
4393            result.result.records[0]
4394                .get("token")
4395                .cloned()
4396                .expect("token column")
4397        };
4398        // Ordinary SELECT stays masked for every role. Plaintext retrieval
4399        // requires an explicit reveal operation.
4400        assert!(
4401            matches!(token_for("ro", Role::Read), Value::Secret(_)),
4402            "a read-role principal must see the column masked"
4403        );
4404        assert!(matches!(token_for("root", Role::Admin), Value::Secret(_)));
4405    }
4406
4407    #[test]
4408    fn store_wide_operations_need_the_admin_tier() {
4409        let runtime = runtime_with_user("bob", Role::Write);
4410        let _identity = IdentityGuard::install("bob", Role::Write);
4411        // These fell through the gate's wildcard arm, so a write-role
4412        // principal could scrub or vacuum the store.
4413        for sql in ["VACUUM", "SCRUB"] {
4414            let err = runtime
4415                .execute_query(sql)
4416                .expect_err("store-wide operation must be refused for a non-admin");
4417            assert!(
4418                err.to_string().contains("permission denied"),
4419                "{sql}: unexpected error: {err}"
4420            );
4421        }
4422    }
4423
4424    #[test]
4425    fn explain_needs_the_privilege_of_the_statement_it_plans() {
4426        let runtime = runtime_with_user("ro", Role::Read);
4427        let _identity = IdentityGuard::install("ro", Role::Read);
4428        runtime
4429            .execute_query("EXPLAIN SELECT 1 AS one")
4430            .expect("planning a read is a read");
4431        // EXPLAIN used to bypass the gate entirely, so a read-only
4432        // principal could plan any write and read the schema back.
4433        let err = runtime
4434            .execute_query("EXPLAIN INSERT INTO gate_t (a) VALUES (1)")
4435            .expect_err("planning a write needs the write privilege");
4436        assert!(
4437            err.to_string().contains("permission denied"),
4438            "unexpected EXPLAIN error: {err}"
4439        );
4440    }
4441
4442    #[test]
4443    fn copy_from_a_server_path_is_admin_only() {
4444        let runtime = runtime_with_user("bob", Role::Write);
4445        let _identity = IdentityGuard::install("bob", Role::Write);
4446        // `COPY … FROM '<path>'` opens a file on the *server*, so a
4447        // write-role principal used to be able to read /proc/self/environ
4448        // (admin token, vault certificate, cloud keys) into a table.
4449        let err = runtime
4450            .execute_query("COPY leak FROM '/etc/hostname'")
4451            .expect_err("COPY FROM must be refused for a non-admin");
4452        assert!(
4453            err.to_string().contains("permission denied"),
4454            "unexpected COPY error: {err}"
4455        );
4456    }
4457
4458    #[test]
4459    fn vcs_history_rewrites_are_admin_only() {
4460        let runtime = runtime_with_user("bob", Role::Write);
4461        let _identity = IdentityGuard::install("bob", Role::Write);
4462        // VCS commands were dispatched before the statement frame was built,
4463        // so `RESET HARD TO` ran with no privilege check at all.
4464        let err = runtime
4465            .execute_query("RESET HARD TO 'deadbeef'")
4466            .expect_err("RESET must be refused for a non-admin");
4467        assert!(
4468            err.to_string().contains("permission denied"),
4469            "unexpected RESET error: {err}"
4470        );
4471    }
4472
4473    #[test]
4474    fn ai_provider_config_writes_are_admin_only() {
4475        let runtime = runtime_with_user("bob", Role::Write);
4476        let _identity = IdentityGuard::install("bob", Role::Write);
4477        // This namespace decides which vault secret is sent, as a bearer, to
4478        // which host — the exfiltration primitive behind the SET CONFIG gap.
4479        let err = runtime
4480            .execute_query(
4481                "SET CONFIG ai.providers.openai.tokens.default.secret_ref = 'red.secret.aes_key'",
4482            )
4483            .expect_err("AI provider config must be refused for a non-admin");
4484        assert!(
4485            err.to_string().contains("permission denied"),
4486            "unexpected SET CONFIG error: {err}"
4487        );
4488    }
4489
4490    #[test]
4491    fn engine_internal_vault_keys_are_not_writable_through_set_secret() {
4492        let runtime = runtime_with_user("root", Role::Admin);
4493        let _identity = IdentityGuard::install("root", Role::Admin);
4494        // Even an admin must not overwrite the IAM policy blob (an allow-all
4495        // policy would survive a restart) or the `SECRET()` master key
4496        // (rotating it destroys every encrypted column value).
4497        for key in [
4498            "red.iam.policies",
4499            "red.iam.attachments.users",
4500            "red.secret.aes_key",
4501        ] {
4502            let err = runtime
4503                .execute_query(&format!("SET SECRET {key} = 'x'"))
4504                .expect_err("engine-internal vault key must be refused");
4505            assert!(
4506                err.to_string().contains("engine-internal"),
4507                "unexpected error for {key}: {err}"
4508            );
4509        }
4510    }
4511}