Skip to main content

reddb_server/runtime/
impl_core.rs

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