Skip to main content

reddb_server/runtime/
statement_frame.rs

1use std::cell::RefCell;
2use std::collections::HashSet;
3use std::rc::Rc;
4use std::sync::Arc;
5
6use super::impl_core::{
7    collections_referenced, current_auth_identity, current_connection_id, current_tenant,
8    has_with_prefix, intent_lock_modes_for, peek_top_level_as_of_with_table,
9    query_has_volatile_builtin, query_is_ask_statement, ConfigSnapshotGuard, CurrentSnapshotGuard,
10    KvStoreGuard, SecretStoreGuard, SnapshotContext, TxLocalTenantGuard,
11};
12use super::{RedDBRuntime, RuntimeQueryResult, RuntimeResultCacheEntry};
13use crate::api::{RedDBError, RedDBResult};
14use crate::auth::Role;
15use crate::storage::query::ast::QueryExpr;
16use crate::storage::query::modes::{detect_mode, parse_multi, QueryMode};
17use crate::storage::transaction::snapshot::{Snapshot, Xid};
18
19/// Coarse privilege classification for a statement, computed once at
20/// frame-build time from the SQL text. Mirrors the three-role auth
21/// model (`Role::Read < Role::Write < Role::Admin`) so the frame can
22/// answer "can this identity run this statement?" without re-walking
23/// the parsed `QueryExpr` at every call site.
24///
25/// `None` means the statement does not touch the privilege gate at
26/// all (transaction control, SET, SHOW). Such statements must remain
27/// runnable under any authenticated identity.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub(crate) enum Privilege {
30    /// Read-only data access (SELECT, EXPLAIN, SHOW). Satisfied by
31    /// any role from `Role::Read` upward.
32    Read,
33    /// Mutation of user data or schema author DDL (INSERT, UPDATE,
34    /// DELETE, CREATE/ALTER/DROP TABLE, CREATE MIGRATION). Requires
35    /// at least `Role::Write`.
36    Write,
37    /// Authority statements — GRANT, REVOKE, ALTER USER, APPLY /
38    /// ROLLBACK MIGRATION, IAM policy mutation. Requires `Role::Admin`.
39    Admin,
40    /// Statement does not consult the privilege gate (BEGIN, COMMIT,
41    /// ROLLBACK, SET, SHOW with no data exposure). Always permitted
42    /// for any authenticated identity.
43    None,
44}
45
46impl Privilege {
47    /// `true` iff `role` is sufficient to execute a statement carrying
48    /// this required privilege. Encodes the standard `Read ⊆ Write ⊆
49    /// Admin` containment used by the auth fallback path.
50    pub(crate) fn is_satisfied_by(self, role: Role) -> bool {
51        match self {
52            Self::None => true,
53            Self::Read => role.can_read(),
54            Self::Write => role.can_write(),
55            Self::Admin => role.can_admin(),
56        }
57    }
58}
59
60/// Coarse lock intent for a statement, computed once at frame-build
61/// time. Maps onto the storage-layer's `LockMode` matrix downstream
62/// but stays decoupled here so the runtime can answer "does this
63/// statement need the lock manager at all?" without a `use storage::`
64/// at every call site.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub(crate) enum LockIntent {
67    /// No collection-level lock needed (transaction control, SET,
68    /// SHOW, EXPLAIN). The lock-acquisition path can short-circuit.
69    None,
70    /// Reader-style intent: SELECT, joins, graph / queue / search
71    /// reads. Maps to `(IS, IS)` at the storage layer.
72    Shared,
73    /// Writer- or DDL-style intent: INSERT/UPDATE/DELETE (`(IX, IX)`)
74    /// and CREATE/ALTER/DROP (`(IX, X)`). Both are surfaced as
75    /// `Exclusive` at this granularity — call sites that need the
76    /// finer distinction still consult `intent_lock_modes_for`.
77    Exclusive,
78}
79
80/// Small, stable Interface that *represents* a read statement's
81/// execution context. Every read caller that needs to know "under
82/// what scope / identity / snapshot am I running, and is there an
83/// AS OF floor in effect?" consults this trait — never the
84/// underlying thread-locals or runtime fields directly.
85///
86/// The deletion test: removing this trait would force the four
87/// concerns it exposes back into ad-hoc lookups at every read
88/// callsite (`current_tenant()`, `current_auth_identity()`,
89/// `capture_current_snapshot()`, AS OF re-parsing). The trait
90/// concentrates them in one place so future changes (per-statement
91/// logging, audit, scope policy) have a single seam to extend.
92pub(crate) trait ReadFrame {
93    /// Effective tenant scope for the statement after WITHIN /
94    /// SET LOCAL TENANT / SET TENANT resolution. `None` means
95    /// "no tenant bound" (RLS deny-default applies).
96    fn effective_scope(&self) -> Option<&str>;
97
98    /// Authenticated identity observed at frame-build time, if any.
99    /// Returns `(username, role)` so callers can render audit lines
100    /// or feed RLS policy lookups without re-reading thread-locals.
101    fn identity(&self) -> Option<(&str, Role)>;
102
103    /// MVCC snapshot the statement reads against. For autocommit
104    /// this is a fresh snapshot; inside an active transaction it
105    /// is the txn's snapshot; under AS OF it is the resolved
106    /// historical xid.
107    fn snapshot(&self) -> &Snapshot;
108
109    /// AS OF xid floor when AS OF was applied for this statement,
110    /// `None` for live reads. Useful for downstream callers that
111    /// want to gate behaviour on historical-read mode without
112    /// re-parsing the query.
113    fn as_of_floor(&self) -> Option<Xid>;
114
115    /// Stable result-cache key for the statement (already mixes
116    /// effective tenant + identity).
117    fn cache_key(&self) -> &str;
118
119    /// Whether the statement is safe to serve from / populate the
120    /// result cache. Combines two underlying signals:
121    ///
122    ///   * the query does not call a volatile builtin (e.g. `NOW()`,
123    ///     `RANDOM()`, `UUID()`), which would change between calls,
124    ///   * the connection is not inside an active transaction with
125    ///     uncommitted writes that other readers shouldn't observe.
126    ///
127    /// SELECT cache callsites (read + write) consult this method
128    /// instead of re-deriving safety from globals or poking the
129    /// frame's private fields. Removing it would force every cache
130    /// callsite to re-run `query_has_volatile_builtin` plus
131    /// `result_cache_safe(conn_id)` inline.
132    fn should_cache_result(&self) -> bool;
133
134    /// Coarse privilege class the statement requires, computed once
135    /// at frame-build time from the SQL prefix. Read/write dispatch
136    /// sites consult this instead of re-classifying the parsed
137    /// `QueryExpr` inline at every callsite.
138    ///
139    /// Removing this method would force every privilege gate to
140    /// recompute the (action, resource) classification from the
141    /// parsed expression and re-check the role hierarchy inline.
142    fn required_privilege(&self) -> Privilege;
143
144    /// Coarse collection-level lock intent the statement implies.
145    /// `None` lets the lock-acquisition path short-circuit without
146    /// touching the lock manager.
147    ///
148    /// Removing this method would force the lock-acquisition path
149    /// to always invoke `intent_lock_modes_for` (which itself walks
150    /// the parsed expression) even for transaction-control / SET /
151    /// SHOW statements that need no collection lock at all.
152    fn lock_intent(&self) -> LockIntent;
153
154    /// Set of collection ids the calling identity is allowed to
155    /// observe under the active `(tenant, role)` scope. Computed once
156    /// at frame-build time via the `AuthStore` visible-collections
157    /// cache (see `auth::scope_cache`) and used by `AuthorizedSearch`
158    /// to pre-filter SEARCH SIMILAR / SEARCH CONTEXT candidate sets
159    /// before any similarity score is computed (issue #119).
160    ///
161    /// `None` means the frame was built without an auth store wired —
162    /// embedded / single-tenant tests run that way. AI search call
163    /// sites refuse to proceed with `None`, which is the deny-default
164    /// the issue requires; pure SELECT paths fall back to the existing
165    /// per-row RLS gate.
166    fn visible_collections(&self) -> Option<&std::collections::HashSet<String>>;
167}
168
169/// Cheap first-word classification of a SQL statement, used at
170/// frame-build time to derive `Privilege` + `LockIntent` without
171/// re-parsing the query. Matches the keywords that the legacy
172/// inline checks in `RedDBRuntime::check_query_privilege` and
173/// `intent_lock_modes_for` already key on.
174fn statement_kind(query: &str) -> &'static str {
175    let trimmed = query.trim_start();
176    // Skip a leading line / block comment so the classifier doesn't
177    // misread `/* ... */ SELECT ...` as an unknown statement.
178    let trimmed = if let Some(rest) = trimmed.strip_prefix("--") {
179        rest.split_once('\n')
180            .map(|(_, r)| r)
181            .unwrap_or("")
182            .trim_start()
183    } else {
184        trimmed
185    };
186    let mut tokens = trimmed.split(|c: char| c.is_whitespace() || c == '(' || c == ';');
187    let first = tokens.next().unwrap_or("");
188    let second = tokens.next().unwrap_or("");
189    if first.eq_ignore_ascii_case("KV") {
190        if second.eq_ignore_ascii_case("GET")
191            || second.eq_ignore_ascii_case("LIST")
192            || second.eq_ignore_ascii_case("WATCH")
193        {
194            return "read";
195        }
196        return "write";
197    }
198    if first.eq_ignore_ascii_case("VAULT") {
199        if second.eq_ignore_ascii_case("LIST")
200            || second.eq_ignore_ascii_case("WATCH")
201            || second.eq_ignore_ascii_case("HISTORY")
202        {
203            return "read";
204        }
205        return "write";
206    }
207    // ASCII-uppercase compare without allocating: SQL keywords are ASCII.
208    let mut buf = [0u8; 16];
209    let bytes = first.as_bytes();
210    let n = bytes.len().min(buf.len());
211    for i in 0..n {
212        buf[i] = bytes[i].to_ascii_uppercase();
213    }
214    match &buf[..n] {
215        b"SELECT" | b"WITH" | b"SHOW" | b"EXPLAIN" | b"DESCRIBE" | b"DESC" | b"RANK"
216        | b"APPROX" | b"APPROXIMATE" | b"ZRANK" | b"ZRANGE" | b"LIST" | b"WATCH" | b"GET"
217        | b"HISTORY" => "read",
218        b"INSERT" | b"UPDATE" | b"DELETE" | b"UPSERT" | b"MERGE" | b"COPY" | b"TRUNCATE" => "write",
219        b"CREATE" | b"ALTER" | b"DROP" | b"REINDEX" | b"VACUUM" | b"ANALYZE" => "ddl",
220        b"GRANT" | b"REVOKE" => "admin",
221        b"BEGIN" | b"START" | b"COMMIT" | b"ROLLBACK" | b"SAVEPOINT" | b"RELEASE" | b"END"
222        | b"SET" | b"RESET" | b"PREPARE" | b"EXECUTE" | b"DEALLOCATE" | b"USE" => "control",
223        b"PUT" | b"INCR" | b"DECR" | b"ADD" | b"ROTATE" | b"PURGE" | b"UNSEAL" | b"INVALIDATE" => {
224            "write"
225        }
226        _ => "unknown",
227    }
228}
229
230fn classify_privilege(query: &str) -> Privilege {
231    match statement_kind(query) {
232        "read" => Privilege::Read,
233        "write" => Privilege::Write,
234        // DDL is gated at `Role::Write` in the legacy fallback (see
235        // `RedDBRuntime::check_query_privilege` for CreateTable et al.),
236        // so it classifies as Write here. APPLY / ROLLBACK MIGRATION and
237        // GRANT / REVOKE upgrade to Admin via finer checks at the call
238        // site — the frame surfaces only the coarse class.
239        "ddl" => Privilege::Write,
240        "admin" => Privilege::Admin,
241        _ => Privilege::None,
242    }
243}
244
245fn classify_lock_intent(query: &str) -> LockIntent {
246    match statement_kind(query) {
247        "read" => LockIntent::Shared,
248        "write" | "ddl" => LockIntent::Exclusive,
249        _ => LockIntent::None,
250    }
251}
252
253pub(super) struct StatementExecutionFrame {
254    tx_local_tenant: Option<Option<String>>,
255    snapshot: Snapshot,
256    own_xids: HashSet<Xid>,
257    cache_key: String,
258    is_volatile_query: bool,
259    cache_safe: bool,
260    /// Effective tenant captured at frame-build time after WITHIN /
261    /// SET LOCAL TENANT / SET TENANT resolution. Stored on the frame
262    /// so the `ReadFrame` Interface can return a borrow without
263    /// re-touching the thread-local stack.
264    effective_scope: Option<String>,
265    /// Auth identity captured at frame-build time. `None` for
266    /// embedded / anonymous callers.
267    identity: Option<(String, Role)>,
268    /// `Some(xid)` when AS OF resolved to a historical xid; `None`
269    /// for live reads.
270    as_of_floor: Option<Xid>,
271    /// True when the statement snapshot can require tuple versions that
272    /// current secondary indexes no longer contain.
273    requires_index_fallback: bool,
274    /// Privilege class required by the statement, derived from the
275    /// SQL text at frame-build time. Read/write dispatch sites
276    /// consult this instead of re-classifying the parsed expression.
277    required_privilege: Privilege,
278    /// Collection-level lock intent the statement implies. The
279    /// lock-acquisition path short-circuits when this is `None`.
280    lock_intent: LockIntent,
281    /// Set of collection ids the active `(tenant, role)` scope is
282    /// allowed to observe. Computed at frame-build time via the
283    /// `AuthStore` visibility cache and consumed by `AuthorizedSearch`
284    /// to gate SEARCH SIMILAR / SEARCH CONTEXT candidate sets before
285    /// scoring (issue #119). `None` when no auth store is wired
286    /// (embedded test mode) — AI search refuses on `None`.
287    visible_collections: Option<HashSet<String>>,
288    /// Per-owner buffer arena for query-result row chunks (#885). Owned
289    /// by the frame because the frame already owns the query lifecycle;
290    /// lent to the row-streaming path (`execute_runtime_table_query_in`)
291    /// so chunk buffers are reused across the statement's chunk-fetches
292    /// instead of allocated fresh per chunk. Reclaimed when the frame
293    /// drops at statement end — no `thread_local!` scratch, which would
294    /// be unsound under tokio's work-stealing runtime.
295    row_arena: Rc<RefCell<super::query_exec::RowBufferArena>>,
296}
297
298pub(super) struct StatementFrameGuards {
299    _tx_local_guard: TxLocalTenantGuard,
300    _config_snapshot_guard: ConfigSnapshotGuard,
301    _secret_store_guard: SecretStoreGuard,
302    _kv_store_guard: KvStoreGuard,
303    _snapshot_guard: CurrentSnapshotGuard,
304}
305
306pub(super) struct PreparedStatement {
307    pub(super) expr: QueryExpr,
308    pub(super) mode: QueryMode,
309}
310
311impl StatementExecutionFrame {
312    pub(super) fn build(runtime: &RedDBRuntime, query: &str) -> RedDBResult<Self> {
313        let conn_id = current_connection_id();
314        let tx_local_tenant = runtime.inner.tx_local_tenants.read().get(&conn_id).cloned();
315        let own_xids = runtime.own_transaction_xids(conn_id);
316        let (snapshot, as_of_floor) = runtime.statement_snapshot(query)?;
317        let requires_index_fallback =
318            as_of_floor.is_some() || runtime.inner.tx_contexts.read().contains_key(&conn_id);
319        let cache_key = result_cache_key(query);
320        let is_volatile_query = query_has_volatile_builtin(query) || query_is_ask_statement(query);
321        let cache_safe = runtime.result_cache_safe(conn_id);
322        // Capture identity + effective scope under the same
323        // thread-local view that the cache key was built from, so
324        // the Interface and the cache key agree on what "this
325        // statement" means.
326        let effective_scope = current_tenant();
327        let identity = current_auth_identity();
328
329        // Coarse classification of the statement, computed once from
330        // the SQL prefix so downstream callers don't re-derive it
331        // from the parsed `QueryExpr` at every privilege / lock site.
332        let required_privilege = classify_privilege(query);
333        let lock_intent = classify_lock_intent(query);
334
335        // Issue #119: resolve the visible-collections set for the
336        // active (tenant, role) scope. Only meaningful when an auth
337        // store is wired *and* an identity was captured — embedded
338        // anonymous callers fall back to `None`, and AI search call
339        // sites refuse on `None`.
340        let visible_collections = match (runtime.inner.auth_store.read().clone(), identity.as_ref())
341        {
342            (Some(store), Some((principal, role))) => {
343                let collections = runtime.inner.db.store().list_collections();
344                Some(store.visible_collections_for_scope(
345                    effective_scope.as_deref(),
346                    *role,
347                    principal,
348                    &collections,
349                ))
350            }
351            _ => None,
352        };
353
354        Ok(Self {
355            tx_local_tenant,
356            snapshot,
357            own_xids,
358            cache_key,
359            is_volatile_query,
360            cache_safe,
361            effective_scope,
362            identity,
363            as_of_floor,
364            requires_index_fallback,
365            required_privilege,
366            lock_intent,
367            visible_collections,
368            row_arena: Rc::new(RefCell::new(super::query_exec::RowBufferArena::new())),
369        })
370    }
371
372    /// Lend the frame's per-owner row-buffer arena (#885) to the
373    /// row-streaming path. Returns a cloned `Rc` handle; the frame remains
374    /// the owner and the arena is reclaimed when the frame drops at
375    /// statement end.
376    pub(super) fn row_arena(&self) -> Rc<RefCell<super::query_exec::RowBufferArena>> {
377        Rc::clone(&self.row_arena)
378    }
379
380    pub(super) fn install(&self, runtime: &RedDBRuntime) -> StatementFrameGuards {
381        StatementFrameGuards {
382            _tx_local_guard: TxLocalTenantGuard::install(self.tx_local_tenant.clone()),
383            _config_snapshot_guard: ConfigSnapshotGuard::install(Arc::clone(&runtime.inner.db)),
384            _secret_store_guard: SecretStoreGuard::install(runtime.inner.auth_store.read().clone()),
385            _kv_store_guard: KvStoreGuard::install(runtime.inner.auth_store.read().clone()),
386            _snapshot_guard: CurrentSnapshotGuard::install(SnapshotContext {
387                snapshot: self.snapshot.clone(),
388                manager: Arc::clone(&runtime.inner.snapshot_manager),
389                own_xids: self.own_xids.clone(),
390                requires_index_fallback: self.requires_index_fallback,
391            }),
392        }
393    }
394
395    pub(super) fn cache_key(&self) -> &str {
396        &self.cache_key
397    }
398
399    pub(super) fn can_read_result_cache(&self) -> bool {
400        // Delegates to the `ReadFrame` Interface so the volatile +
401        // active-tx safety decision lives in exactly one place.
402        <Self as ReadFrame>::should_cache_result(self)
403    }
404
405    pub(super) fn should_write_result_cache(&self, result: &RuntimeQueryResult) -> bool {
406        // Cache-safety (volatile builtin, active-tx writes) comes from
407        // the Interface; the rest are write-side payload heuristics
408        // (statement shape, result size) that aren't part of the
409        // safety contract.
410        <Self as ReadFrame>::should_cache_result(self)
411            && result.statement_type == "select"
412            && result.engine != "vault"
413            && result.engine != "runtime-rank"
414            // `QUEUE READ` is a stateful read: a delayed message
415            // (issue #722) becomes deliverable over time without a
416            // producer push to invalidate the cache, so a cached empty
417            // result would hide it. Skip caching entirely.
418            && result.statement != "queue_group_read"
419            && result.result.pre_serialized_json.is_none()
420            // Graph-analytics TVF output (issue #802) is deterministic and
421            // expensive to recompute, so it is cached at any row count. The
422            // ≤5-row heuristic only bounds payload size for ordinary SELECTs.
423            && (is_graph_tvf_engine(result.engine) || result.result.records.len() <= 5)
424    }
425
426    pub(super) fn read_result_cache(&self, runtime: &RedDBRuntime) -> Option<RuntimeQueryResult> {
427        if self.can_read_result_cache() {
428            runtime.get_result_cache_entry(self.cache_key())
429        } else {
430            None
431        }
432    }
433
434    pub(super) fn write_result_cache(
435        &self,
436        runtime: &RedDBRuntime,
437        result: &RuntimeQueryResult,
438        scopes: HashSet<String>,
439    ) {
440        if self.should_write_result_cache(result) {
441            runtime.put_result_cache_entry(
442                self.cache_key(),
443                RuntimeResultCacheEntry {
444                    result: result.clone(),
445                    cached_at: std::time::Instant::now(),
446                    scopes,
447                },
448            );
449        }
450    }
451
452    pub(super) fn prepare_cte(&self, query: &str) -> RedDBResult<Option<QueryExpr>> {
453        // Detected via cheap prefix check so non-CTE queries skip the
454        // full parse here. CTE-bearing queries bypass the plan cache
455        // and result cache (rare workload — perf optimization is a
456        // follow-up). Inlining substitutes every CTE reference with
457        // its body as a subquery in FROM, after which the existing
458        // subquery-in-FROM machinery handles execution. Recursive
459        // CTEs are rejected explicitly until fixpoint execution wires
460        // through the runtime.
461        if !has_with_prefix(query) {
462            return Ok(None);
463        }
464        let parsed = crate::storage::query::parser::parse(query)
465            .map_err(|err| RedDBError::Query(err.to_string()))?;
466        if parsed.with_clause.is_some() {
467            let rewritten = crate::storage::query::executors::inline_ctes(parsed)
468                .map_err(|err| RedDBError::Query(err.to_string()))?;
469            return Ok(Some(rewritten));
470        }
471        // No WITH after parse (the prefix matched something else like
472        // `WITHIN` that already routed elsewhere) — fall through to
473        // the normal path with the original query.
474        Ok(None)
475    }
476
477    pub(super) fn prepare_statement(
478        &self,
479        runtime: &RedDBRuntime,
480        query: &str,
481    ) -> RedDBResult<PreparedStatement> {
482        let mode = detect_mode(query);
483        if matches!(mode, QueryMode::Unknown) {
484            return Err(RedDBError::Query("unable to detect query mode".to_string()));
485        }
486
487        // ── Plan cache: reuse only exact-query ASTs ──
488        //
489        // DML statements (INSERT/UPDATE/DELETE) almost always have unique literal
490        // values, so caching them burns CPU on eviction bookkeeping (Vec::remove(0)
491        // shifts the entire LRU list) with zero hit rate. Skip the cache entirely
492        // Plan cache applies to statements whose shape can be
493        // normalised + rebound (`UPDATE t SET x=? WHERE _entity_id=?`
494        // reuses the same plan across thousands of varying literals).
495        // INSERT is still bypassed — its shape changes per column set
496        // and bulk paths don't go through here anyway.
497        let first_word = query
498            .trim()
499            .split_ascii_whitespace()
500            .next()
501            .unwrap_or("")
502            .to_ascii_uppercase();
503        let is_insert = first_word == "INSERT";
504        // #1370 — volatile queries ($config / $secret resolve mutable runtime
505        // state at execution time) must bypass the plan cache too. A cached
506        // optimized plan drops the live `$config` resolution, so a later
507        // `SET CONFIG` would be ignored and the query would serve a stale value.
508        // Re-parse fresh every time so the resolver runs against current state.
509        let bypass_plan_cache = is_insert || self.is_volatile_query;
510
511        // Fused normalize+extract: one byte-scan produces both the
512        // cache_key AND the literal bindings. Saves a second Lexer
513        // pass over the query text on every cache hit — dominant
514        // cost on tight UPDATE loops that hit the same shape
515        // thousands of times with varying literals.
516        let (cache_key, prescan_binds) = if bypass_plan_cache {
517            (String::new(), Vec::new())
518        } else {
519            crate::storage::query::planner::cache_key::normalize_and_extract(query)
520        };
521
522        let expr = if bypass_plan_cache {
523            // Bypass plan cache for INSERT — shape varies per query.
524            parse_multi(query).map_err(|err| RedDBError::Query(err.to_string()))?
525        } else {
526            // ── Hot path: read lock only (no writer serialization on cache hits) ──
527            //
528            // peek() is a non-mutating probe: no LRU promotion, no touch().
529            // This lets concurrent readers proceed without blocking each other.
530            // On hit we bind literals if needed and return immediately.
531            // Only on miss do we drop to a write lock to parse + insert.
532            let hit = {
533                let plan_cache = runtime.inner.query_cache.read();
534                plan_cache.peek(&cache_key).map(|cached| {
535                    let parameter_count = cached.parameter_count;
536                    let optimized = cached.plan.optimized.clone();
537                    let exact_query = cached.exact_query.clone();
538                    (parameter_count, optimized, exact_query)
539                })
540            };
541
542            if let Some((parameter_count, optimized, exact_query)) = hit {
543                if parameter_count > 0 {
544                    // Shape hit: use the binds extracted during normalise.
545                    let shape_binds = prescan_binds.clone();
546                    if let Some(bound) =
547                        crate::storage::query::planner::shape::bind_parameterized_query(
548                            &optimized,
549                            &shape_binds,
550                            parameter_count,
551                        )
552                    {
553                        bound
554                    } else if exact_query.as_deref() == Some(query) {
555                        // Bind failed but exact query matches — use as-is.
556                        optimized
557                    } else {
558                        // Bind failed and literals differ: re-parse fresh.
559                        parse_multi(query).map_err(|err| RedDBError::Query(err.to_string()))?
560                    }
561                } else {
562                    // No parameters means either there truly are no literals,
563                    // or this statement type does not participate in shape
564                    // parameterization (for example graph/queue commands).
565                    // Reusing a normalized-cache hit across a different exact
566                    // query can therefore leak stale literals into execution.
567                    if exact_query.as_deref() == Some(query) {
568                        optimized
569                    } else {
570                        parse_multi(query).map_err(|err| RedDBError::Query(err.to_string()))?
571                    }
572                }
573            } else {
574                // Cache miss — parse, parameterize, store.
575                let parsed =
576                    parse_multi(query).map_err(|err| RedDBError::Query(err.to_string()))?;
577                let (cached_expr, parameter_count) = if let Some(prepared) =
578                    crate::storage::query::planner::shape::parameterize_query_expr(&parsed)
579                {
580                    (prepared.shape, prepared.parameter_count)
581                } else {
582                    (parsed.clone(), 0)
583                };
584                {
585                    let mut pc = runtime.inner.query_cache.write();
586                    let plan = crate::storage::query::planner::QueryPlan::new(
587                        parsed.clone(),
588                        cached_expr,
589                        Default::default(),
590                    );
591                    pc.insert(
592                        cache_key.clone(),
593                        crate::storage::query::planner::CachedPlan::new(plan)
594                            .with_shape_key(cache_key.clone())
595                            .with_exact_query(query.to_string())
596                            .with_parameter_count(parameter_count),
597                    );
598                }
599                parsed
600            }
601        };
602
603        // Phase 5 PG parity: substitute any registered view name that
604        // appears in the expression with its stored body. Runs after
605        // parse and before dispatch so the SQL entrypoint gets the
606        // same view resolution `execute_query_expr` already does.
607        let expr = runtime.rewrite_view_refs(expr);
608
609        Ok(PreparedStatement { expr, mode })
610    }
611
612    pub(super) fn check_query_privilege(
613        &self,
614        runtime: &RedDBRuntime,
615        expr: &QueryExpr,
616    ) -> RedDBResult<()> {
617        // Frame-level coarse gate. We consult `required_privilege()`
618        // (computed once at frame-build) against the captured identity
619        // before the deep grant engine walks the parsed expression.
620        // The coarse gate cannot ALLOW anything the grant engine would
621        // deny — it only short-circuits the obvious "Role::Read tries
622        // INSERT" case so a downstream caller never has to redo this
623        // check inline. `Privilege::None` (transaction control / SET /
624        // SHOW) flows through unchanged; the grant engine treats those
625        // as bypass too.
626        if let Some((username, role)) = <Self as ReadFrame>::identity(self) {
627            let needed = <Self as ReadFrame>::required_privilege(self);
628            if !needed.is_satisfied_by(role) {
629                // Issue #205 — when the deep grant engine *also*
630                // denies, we treat this as an ordinary permission
631                // failure. But when an Admin-only statement reaches
632                // this gate without an auth_store wired (so the deep
633                // engine can't double-check), the coarse rejection is
634                // the only line of defence — emit an OperatorEvent so
635                // the operator notices an Admin-class statement was
636                // attempted with insufficient role.
637                if matches!(needed, Privilege::Admin) && runtime.inner.auth_store.read().is_none() {
638                    crate::telemetry::operator_event::OperatorEvent::AuthBypass {
639                        principal: username.to_string(),
640                        resource: format!("statement requiring {needed:?}"),
641                        detail: format!(
642                            "auth_store not wired; coarse gate is sole defence (role={role:?})"
643                        ),
644                    }
645                    .emit_global();
646                }
647                return Err(RedDBError::Query(format!(
648                    "permission denied: principal=`{username}` role=`{role:?}` lacks {needed:?} privilege"
649                )));
650            }
651        }
652        runtime
653            .check_query_privilege(expr)
654            .map_err(|err| RedDBError::Query(format!("permission denied: {err}")))
655    }
656
657    pub(super) fn prepare_dispatch(
658        &self,
659        runtime: &RedDBRuntime,
660        expr: &QueryExpr,
661    ) -> RedDBResult<Option<crate::runtime::locking::LockerGuard>> {
662        runtime.validate_model_operations_before_auth(expr)?;
663        self.check_query_privilege(runtime, expr)?;
664        Ok(self.acquire_intent_locks(runtime, expr))
665    }
666
667    pub(super) fn acquire_intent_locks(
668        &self,
669        runtime: &RedDBRuntime,
670        expr: &QueryExpr,
671    ) -> Option<crate::runtime::locking::LockerGuard> {
672        if !runtime.config_bool("concurrency.locking.enabled", true) {
673            return None;
674        }
675        // Frame-level short-circuit: if the statement carries no lock
676        // intent (transaction control, SET, SHOW), skip the lock
677        // manager entirely instead of letting `intent_lock_modes_for`
678        // walk the parsed expression to reach the same conclusion.
679        if matches!(<Self as ReadFrame>::lock_intent(self), LockIntent::None) {
680            return None;
681        }
682        intent_lock_modes_for(expr).map(|(global_mode, coll_mode)| {
683            let mut guard =
684                crate::runtime::locking::LockerGuard::new(runtime.inner.lock_manager.clone());
685            let _ = guard.acquire(crate::runtime::locking::Resource::Global, global_mode);
686            for collection in collections_referenced(expr) {
687                let _ = guard.acquire(
688                    crate::runtime::locking::Resource::Collection(collection),
689                    coll_mode,
690                );
691            }
692            guard
693        })
694    }
695}
696
697impl ReadFrame for StatementExecutionFrame {
698    fn effective_scope(&self) -> Option<&str> {
699        self.effective_scope.as_deref()
700    }
701
702    fn identity(&self) -> Option<(&str, Role)> {
703        self.identity.as_ref().map(|(u, r)| (u.as_str(), *r))
704    }
705
706    fn snapshot(&self) -> &Snapshot {
707        &self.snapshot
708    }
709
710    fn as_of_floor(&self) -> Option<Xid> {
711        self.as_of_floor
712    }
713
714    fn cache_key(&self) -> &str {
715        &self.cache_key
716    }
717
718    fn should_cache_result(&self) -> bool {
719        !self.is_volatile_query && self.cache_safe
720    }
721
722    fn required_privilege(&self) -> Privilege {
723        self.required_privilege
724    }
725
726    fn lock_intent(&self) -> LockIntent {
727        self.lock_intent
728    }
729
730    fn visible_collections(&self) -> Option<&HashSet<String>> {
731        self.visible_collections.as_ref()
732    }
733}
734
735/// Lightweight `ReadFrame` carrier used by AI command entry points
736/// (`SEARCH SIMILAR`, `SEARCH CONTEXT`, `ASK`).
737///
738/// Issue #119 calls this struct `EffectiveScope`. It bundles the
739/// `(tenant, identity, role, visible_collections, snapshot)` tuple so
740/// every AI runtime entry can pass *one* value to `AuthorizedSearch`
741/// instead of re-reading thread-locals at every call site.
742///
743/// Built via `RedDBRuntime::ai_scope()` which sources tenant + identity
744/// from the per-statement thread-locals (identical to how
745/// `StatementExecutionFrame::build` derives them) and resolves
746/// `visible_collections` via the `AuthStore` cache.
747pub struct EffectiveScope {
748    pub(crate) tenant: Option<String>,
749    pub(crate) identity: Option<(String, Role)>,
750    pub(crate) snapshot: Snapshot,
751    pub(crate) visible_collections: Option<HashSet<String>>,
752}
753
754impl EffectiveScope {
755    /// Capability check used by the AI runtime (`runtime/ai/ner.rs`)
756    /// to gate LLM-backed NER calls behind `ai:ner:read`.
757    ///
758    /// Placeholder for now: always returns `false`. The auth engine's
759    /// capability matrix is future work; until it lands, every routed
760    /// LLM-NER call denies at the gate and `extract_tokens_routed`'s
761    /// heuristic fallback fires (see `ask_pipeline::extract_tokens_routed`).
762    /// Documented in code so the wire-up is a one-line change once
763    /// the auth engine learns capabilities.
764    pub fn has_capability(&self, _capability: &str) -> bool {
765        false
766    }
767}
768
769impl ReadFrame for EffectiveScope {
770    fn effective_scope(&self) -> Option<&str> {
771        self.tenant.as_deref()
772    }
773    fn identity(&self) -> Option<(&str, Role)> {
774        self.identity.as_ref().map(|(u, r)| (u.as_str(), *r))
775    }
776    fn snapshot(&self) -> &Snapshot {
777        &self.snapshot
778    }
779    fn as_of_floor(&self) -> Option<Xid> {
780        None
781    }
782    fn cache_key(&self) -> &str {
783        ""
784    }
785    fn should_cache_result(&self) -> bool {
786        false
787    }
788    fn required_privilege(&self) -> Privilege {
789        Privilege::Read
790    }
791    fn lock_intent(&self) -> LockIntent {
792        LockIntent::Shared
793    }
794    fn visible_collections(&self) -> Option<&HashSet<String>> {
795        self.visible_collections.as_ref()
796    }
797}
798
799impl RedDBRuntime {
800    /// Build the AI command `EffectiveScope` from the current
801    /// statement thread-locals + auth store.
802    ///
803    /// Returns `None` for embedded callers (no auth store, no
804    /// identity) — `AuthorizedSearch` treats `None` as deny-default.
805    pub(crate) fn ai_scope(&self) -> EffectiveScope {
806        let tenant = super::impl_core::current_tenant();
807        let identity = super::impl_core::current_auth_identity();
808        let snapshot = self.current_snapshot();
809        let visible_collections = match (self.inner.auth_store.read().clone(), identity.as_ref()) {
810            (Some(store), Some((principal, role))) => {
811                let collections = self.inner.db.store().list_collections();
812                Some(store.visible_collections_for_scope(
813                    tenant.as_deref(),
814                    *role,
815                    principal,
816                    &collections,
817                ))
818            }
819            _ => None,
820        };
821        EffectiveScope {
822            tenant,
823            identity,
824            snapshot,
825            visible_collections,
826        }
827    }
828}
829
830/// Test fixtures for callers that need to drive `ReadFrame` without
831/// booting a runtime. Lives behind `cfg(test)` and `pub(crate)` so it
832/// only leaks across module boundaries inside the crate.
833#[cfg(test)]
834pub(crate) mod test_support {
835    use super::{LockIntent, Privilege, ReadFrame};
836    use crate::auth::Role;
837    use crate::storage::transaction::snapshot::{Snapshot, Xid};
838    use std::collections::HashSet;
839
840    /// A `ReadFrame` impl with hand-set fields. Used by
841    /// `authorized_search` tests to assert the deny-default and
842    /// scope-trim behaviour without going through frame construction.
843    pub(crate) struct FakeReadFrame {
844        pub tenant: Option<String>,
845        pub identity: Option<(String, Role)>,
846        pub snapshot: Snapshot,
847        pub visible: Option<HashSet<String>>,
848    }
849
850    impl FakeReadFrame {
851        pub(crate) fn without_scope() -> Self {
852            Self {
853                tenant: None,
854                identity: None,
855                snapshot: Snapshot {
856                    xid: 0,
857                    in_progress: HashSet::new(),
858                },
859                visible: None,
860            }
861        }
862
863        pub(crate) fn with_visible(visible: HashSet<String>) -> Self {
864            Self {
865                tenant: Some("acme".to_string()),
866                identity: Some(("alice".to_string(), Role::Read)),
867                snapshot: Snapshot {
868                    xid: 0,
869                    in_progress: HashSet::new(),
870                },
871                visible: Some(visible),
872            }
873        }
874    }
875
876    impl ReadFrame for FakeReadFrame {
877        fn effective_scope(&self) -> Option<&str> {
878            self.tenant.as_deref()
879        }
880        fn identity(&self) -> Option<(&str, Role)> {
881            self.identity.as_ref().map(|(u, r)| (u.as_str(), *r))
882        }
883        fn snapshot(&self) -> &Snapshot {
884            &self.snapshot
885        }
886        fn as_of_floor(&self) -> Option<Xid> {
887            None
888        }
889        fn cache_key(&self) -> &str {
890            ""
891        }
892        fn should_cache_result(&self) -> bool {
893            false
894        }
895        fn required_privilege(&self) -> Privilege {
896            Privilege::Read
897        }
898        fn lock_intent(&self) -> LockIntent {
899            LockIntent::Shared
900        }
901        fn visible_collections(&self) -> Option<&HashSet<String>> {
902            self.visible.as_ref()
903        }
904    }
905}
906
907impl RedDBRuntime {
908    fn own_transaction_xids(&self, conn_id: u64) -> HashSet<Xid> {
909        let mut set = HashSet::new();
910        if let Some(ctx) = self.inner.tx_contexts.read().get(&conn_id) {
911            set.insert(ctx.xid);
912            for (_, sub) in &ctx.savepoints {
913                set.insert(*sub);
914            }
915            for sub in &ctx.released_sub_xids {
916                set.insert(*sub);
917            }
918        }
919        set
920    }
921
922    /// Resolve the snapshot for the current statement, returning
923    /// the snapshot itself and (when AS OF is in effect) the
924    /// resolved xid floor. The floor is the same xid carried inside
925    /// `Snapshot.xid` for AS OF reads — exposing it separately lets
926    /// the `ReadFrame` Interface tell "live read" from "historical
927    /// read" without inferring from `in_progress.is_empty()`.
928    fn statement_snapshot(&self, query: &str) -> RedDBResult<(Snapshot, Option<Xid>)> {
929        match peek_top_level_as_of_with_table(query) {
930            Some((spec, Some(table))) => {
931                if !table.starts_with("red_") && !self.vcs_is_versioned(&table)? {
932                    return Err(RedDBError::InvalidConfig(format!(
933                        "AS OF requires a versioned collection — \
934                         `{table}` has not opted in. \
935                         Call vcs.set_versioned(\"{table}\", true) first."
936                    )));
937                }
938                let xid = self.vcs_resolve_as_of(spec)?;
939                Ok((
940                    Snapshot {
941                        xid,
942                        in_progress: HashSet::new(),
943                    },
944                    Some(xid),
945                ))
946            }
947            Some((spec, None)) => {
948                let xid = self.vcs_resolve_as_of(spec)?;
949                Ok((
950                    Snapshot {
951                        xid,
952                        in_progress: HashSet::new(),
953                    },
954                    Some(xid),
955                ))
956            }
957            None => Ok((self.current_snapshot(), None)),
958        }
959    }
960
961    fn result_cache_safe(&self, conn_id: u64) -> bool {
962        let has_active_xids = self.inner.snapshot_manager.oldest_active_xid().is_some();
963        let in_own_tx = self.inner.tx_contexts.read().contains_key(&conn_id);
964        !has_active_xids && !in_own_tx
965    }
966}
967
968/// Whether a result's `engine` tag is one of the graph-analytics TVF
969/// executors (issue #802). Graph-collection (`louvain(g)`) and inline
970/// (`louvain(nodes => …, edges => …)`) forms both produce deterministic
971/// algorithm output that is cached regardless of row count.
972fn is_graph_tvf_engine(engine: &str) -> bool {
973    matches!(engine, "runtime-graph-tvf" | "runtime-graph-tvf-inline")
974}
975
976fn result_cache_key(query: &str) -> String {
977    let tenant = current_tenant().unwrap_or_default();
978    let auth = current_auth_identity()
979        .map(|(user, role)| format!("{}|{:?}", user, role))
980        .unwrap_or_default();
981    if tenant.is_empty() && auth.is_empty() {
982        query.to_string()
983    } else {
984        format!("{query}\u{001e}{tenant}\u{001e}{auth}")
985    }
986}
987
988#[cfg(test)]
989mod tests {
990    use super::*;
991    use crate::api::RedDBOptions;
992    use crate::runtime::impl_core::{
993        clear_current_auth_identity, clear_current_tenant, set_current_auth_identity,
994        set_current_tenant,
995    };
996    use crate::runtime::RedDBRuntime;
997
998    fn fresh_runtime() -> RedDBRuntime {
999        RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("in-memory runtime")
1000    }
1001
1002    /// Ensure thread-local state from a prior test can't leak into
1003    /// the next one — tests in the same binary share the thread.
1004    fn reset_thread_locals() {
1005        clear_current_tenant();
1006        clear_current_auth_identity();
1007    }
1008
1009    #[test]
1010    fn autocommit_select_takes_live_snapshot() {
1011        reset_thread_locals();
1012        let rt = fresh_runtime();
1013        let frame =
1014            StatementExecutionFrame::build(&rt, "SELECT 1").expect("frame builds for SELECT 1");
1015
1016        // Live reads: no AS OF floor, snapshot bounded by the
1017        // manager's `peek_next_xid` so committed tuples are visible.
1018        let f: &dyn ReadFrame = &frame;
1019        assert!(f.as_of_floor().is_none(), "live read has no AS OF floor");
1020        assert!(
1021            f.snapshot().xid >= 1,
1022            "autocommit snapshot xid is bounded by peek_next_xid"
1023        );
1024    }
1025
1026    #[test]
1027    fn frame_captures_identity_and_scope() {
1028        reset_thread_locals();
1029        set_current_tenant("acme".to_string());
1030        set_current_auth_identity("alice".to_string(), Role::Write);
1031
1032        let rt = fresh_runtime();
1033        let frame = StatementExecutionFrame::build(&rt, "SELECT 1").expect("frame builds");
1034        let f: &dyn ReadFrame = &frame;
1035
1036        assert_eq!(f.effective_scope(), Some("acme"));
1037        let id = f.identity().expect("identity captured");
1038        assert_eq!(id.0, "alice");
1039        assert!(matches!(id.1, Role::Write));
1040
1041        // Cache key mixes scope + identity so two callers under
1042        // different tenants never share a cache slot.
1043        assert!(
1044            f.cache_key().contains("acme") && f.cache_key().contains("alice"),
1045            "cache key folds in scope + identity, got {:?}",
1046            f.cache_key()
1047        );
1048
1049        reset_thread_locals();
1050    }
1051
1052    #[test]
1053    fn as_of_rejects_non_versioned_user_collection() {
1054        reset_thread_locals();
1055        let rt = fresh_runtime();
1056
1057        // `not_versioned` is a plain user collection — the frame
1058        // builder must reject AS OF until the caller opts in via
1059        // `vcs.set_versioned`.
1060        let err = match StatementExecutionFrame::build(
1061            &rt,
1062            "SELECT * FROM not_versioned AS OF COMMIT 'deadbeef'",
1063        ) {
1064            Err(e) => e,
1065            Ok(_) => panic!("AS OF on non-versioned user collection rejected"),
1066        };
1067
1068        let msg = format!("{err}");
1069        assert!(
1070            msg.contains("AS OF requires a versioned collection"),
1071            "expected AS OF rejection, got: {msg}"
1072        );
1073    }
1074
1075    /// End-to-end proof that the SELECT path consumes a `ReadFrame`.
1076    ///
1077    /// Sets a tenant + identity via the public thread-local API the
1078    /// runtime uses for ambient scope, drives a real `SELECT` through
1079    /// `execute_query`, then inspects the result cache that the SELECT
1080    /// path populates via `frame.cache_key()`. The key only carries
1081    /// the tenant + identity *because* it was built through the frame —
1082    /// reverting the wiring to inline `current_tenant()` /
1083    /// `current_auth_identity()` reads would still pass this test, but
1084    /// dropping the frame entirely (so the SELECT path stopped touching
1085    /// `cache_key`) would break it.
1086    #[test]
1087    fn select_path_routes_through_frame_cache_key() {
1088        reset_thread_locals();
1089        set_current_tenant("acme".to_string());
1090        set_current_auth_identity("alice".to_string(), Role::Read);
1091
1092        let rt = fresh_runtime();
1093        let result = rt
1094            .execute_query("SELECT 1")
1095            .expect("SELECT 1 executes under tenant=acme/identity=alice");
1096        assert_eq!(result.statement_type, "select");
1097
1098        // The textual SELECT path builds a frame and
1099        // writes its result through `frame.cache_key()`. That key folds
1100        // tenant + identity in via `result_cache_key`, so finding "acme"
1101        // and "alice" inside any cached key proves the frame was the
1102        // seam used.
1103        let cache = rt.inner.result_cache.read();
1104        let any_keyed_with_scope = cache
1105            .0
1106            .keys()
1107            .any(|k| k.contains("acme") && k.contains("alice"));
1108        assert!(
1109            any_keyed_with_scope,
1110            "expected at least one result-cache key carrying tenant+identity, \
1111             got keys: {:?}",
1112            cache.0.keys().collect::<Vec<_>>()
1113        );
1114
1115        reset_thread_locals();
1116    }
1117
1118    /// A SELECT that calls a volatile builtin (here:
1119    /// `pg_advisory_unlock`, the volatile token the runtime currently
1120    /// recognises in `query_has_volatile_builtin`) must NOT populate
1121    /// the result cache. Any caller hitting the cache after this would
1122    /// see a stale answer for an inherently-volatile query, so the
1123    /// SELECT path gates writes through `frame.should_cache_result()`.
1124    ///
1125    /// Deletion test: removing `ReadFrame::should_cache_result`, or
1126    /// reverting the SELECT path to skip its safety gate, would let
1127    /// the result cache silently absorb this statement and break the
1128    /// assertion below.
1129    #[test]
1130    fn volatile_select_does_not_populate_result_cache() {
1131        reset_thread_locals();
1132        let rt = fresh_runtime();
1133
1134        // Frame-level invariant: the volatile-builtin signal collapses
1135        // `should_cache_result` to false even for an autocommit /
1136        // out-of-tx connection.
1137        let frame =
1138            StatementExecutionFrame::build(&rt, "SELECT pg_advisory_unlock(1)").expect("frame");
1139        let f: &dyn ReadFrame = &frame;
1140        assert!(
1141            !f.should_cache_result(),
1142            "volatile builtin must disable result-cache safety"
1143        );
1144
1145        // End-to-end: drive the volatile SELECT through `execute_query`
1146        // and confirm no entry was stamped under its cache key. Other
1147        // entries from prior tests sharing the binary may exist, so we
1148        // assert specifically on this query's key.
1149        let _ = rt
1150            .execute_query("SELECT pg_advisory_unlock(1)")
1151            .expect("volatile SELECT executes");
1152        let cache = rt.inner.result_cache.read();
1153        let key = result_cache_key("SELECT pg_advisory_unlock(1)");
1154        assert!(
1155            !cache.0.contains_key(&key),
1156            "volatile SELECT must not populate result cache, found key {key:?} in {:?}",
1157            cache.0.keys().collect::<Vec<_>>()
1158        );
1159
1160        reset_thread_locals();
1161    }
1162
1163    #[test]
1164    fn blob_cache_backend_populates_blob_path_without_legacy_write() {
1165        reset_thread_locals();
1166        let rt = fresh_runtime();
1167        rt.inner
1168            .db
1169            .store()
1170            .set_config_tree("runtime.result_cache.backend", &crate::json!("blob_cache"));
1171
1172        let result = rt.execute_query("SELECT 1").expect("SELECT 1 executes");
1173        assert_eq!(result.statement_type, "select");
1174
1175        let key = result_cache_key("SELECT 1");
1176        assert!(
1177            rt.inner
1178                .result_blob_cache
1179                .get("runtime.result_cache", &key)
1180                .is_some(),
1181            "blob backend should stamp the Blob Cache path"
1182        );
1183        assert!(rt.inner.result_blob_entries.read().0.contains_key(&key));
1184        assert!(
1185            !rt.inner.result_cache.read().0.contains_key(&key),
1186            "blob backend should not write the legacy map"
1187        );
1188    }
1189
1190    #[test]
1191    fn blob_cache_backend_keeps_volatile_select_out_of_blob_path() {
1192        reset_thread_locals();
1193        let rt = fresh_runtime();
1194        rt.inner
1195            .db
1196            .store()
1197            .set_config_tree("runtime.result_cache.backend", &crate::json!("blob_cache"));
1198
1199        let _ = rt
1200            .execute_query("SELECT pg_advisory_unlock(1)")
1201            .expect("volatile SELECT executes");
1202        let key = result_cache_key("SELECT pg_advisory_unlock(1)");
1203        assert!(
1204            rt.inner
1205                .result_blob_cache
1206                .get("runtime.result_cache", &key)
1207                .is_none(),
1208            "volatile SELECT must not populate blob result cache"
1209        );
1210        assert!(!rt.inner.result_blob_entries.read().0.contains_key(&key));
1211    }
1212
1213    #[test]
1214    fn shadow_backend_dual_writes_and_reports_no_divergence_on_equal_results() {
1215        reset_thread_locals();
1216        let rt = fresh_runtime();
1217        rt.inner
1218            .db
1219            .store()
1220            .set_config_tree("runtime.result_cache.backend", &crate::json!("shadow"));
1221
1222        let first = rt.execute_query("SELECT 1").expect("first SELECT");
1223        let second = rt.execute_query("SELECT 1").expect("cached SELECT");
1224        assert_eq!(first.result.len(), second.result.len());
1225
1226        let key = result_cache_key("SELECT 1");
1227        assert!(rt.inner.result_cache.read().0.contains_key(&key));
1228        assert!(rt.inner.result_blob_entries.read().0.contains_key(&key));
1229        assert_eq!(rt.result_cache_shadow_divergences(), 0);
1230        assert_eq!(
1231            crate::runtime::METRIC_CACHE_SHADOW_DIVERGENCE_TOTAL,
1232            "cache_shadow_divergence_total"
1233        );
1234    }
1235
1236    #[test]
1237    fn as_of_on_red_collection_records_floor() {
1238        reset_thread_locals();
1239        let rt = fresh_runtime();
1240
1241        // `red_*` collections always allow AS OF. The frame should
1242        // resolve to a concrete xid and surface it via the Interface.
1243        let frame =
1244            StatementExecutionFrame::build(&rt, "SELECT * FROM red_commits AS OF SNAPSHOT 1")
1245                .expect("AS OF SNAPSHOT 1 on red_commits resolves");
1246
1247        let f: &dyn ReadFrame = &frame;
1248        assert_eq!(
1249            f.as_of_floor(),
1250            Some(1),
1251            "AS OF SNAPSHOT 1 records xid=1 as the floor"
1252        );
1253        assert_eq!(f.snapshot().xid, 1);
1254        assert!(
1255            f.snapshot().in_progress.is_empty(),
1256            "historical reads have no in-progress set"
1257        );
1258    }
1259
1260    /// The frame classifies common SQL prefixes into the coarse
1261    /// `Privilege` / `LockIntent` buckets at build time. This test
1262    /// pins the mapping so a regression that silently re-routes
1263    /// (e.g. INSERT classified as Read) surfaces here, not at a
1264    /// downstream privilege gate.
1265    #[test]
1266    fn frame_classifies_privilege_and_lock_intent_from_prefix() {
1267        reset_thread_locals();
1268        let rt = fresh_runtime();
1269
1270        let cases = [
1271            ("SELECT 1", Privilege::Read, LockIntent::Shared),
1272            ("LIST KV settings", Privilege::Read, LockIntent::Shared),
1273            (
1274                "KV GET settings.feature",
1275                Privilege::Read,
1276                LockIntent::Shared,
1277            ),
1278            ("VAULT LIST secrets", Privilege::Read, LockIntent::Shared),
1279            (
1280                "INSERT INTO t (id) VALUES (1)",
1281                Privilege::Write,
1282                LockIntent::Exclusive,
1283            ),
1284            (
1285                "KV PUT settings.feature = 'on'",
1286                Privilege::Write,
1287                LockIntent::Exclusive,
1288            ),
1289            (
1290                "VAULT PUT secrets.api = 'x'",
1291                Privilege::Write,
1292                LockIntent::Exclusive,
1293            ),
1294            (
1295                "UPDATE t SET x = 1 WHERE id = 1",
1296                Privilege::Write,
1297                LockIntent::Exclusive,
1298            ),
1299            (
1300                "DELETE FROM t WHERE id = 1",
1301                Privilege::Write,
1302                LockIntent::Exclusive,
1303            ),
1304            (
1305                "CREATE TABLE foo (id INT)",
1306                Privilege::Write,
1307                LockIntent::Exclusive,
1308            ),
1309            ("BEGIN", Privilege::None, LockIntent::None),
1310            ("COMMIT", Privilege::None, LockIntent::None),
1311            ("SET timezone = 'UTC'", Privilege::None, LockIntent::None),
1312        ];
1313
1314        for (q, want_priv, want_lock) in cases {
1315            let frame = StatementExecutionFrame::build(&rt, q)
1316                .unwrap_or_else(|e| panic!("frame builds for {q:?}: {e}"));
1317            let f: &dyn ReadFrame = &frame;
1318            assert_eq!(f.required_privilege(), want_priv, "privilege for {q:?}");
1319            assert_eq!(f.lock_intent(), want_lock, "lock intent for {q:?}");
1320        }
1321    }
1322
1323    /// Deletion-test for `ReadFrame::required_privilege`: a SELECT
1324    /// driven through `execute_query` under an identity whose role
1325    /// doesn't satisfy the frame's coarse `Read` privilege gets
1326    /// denied with the frame's signal.
1327    ///
1328    /// We test the gate by classifying an INSERT (which the frame
1329    /// reports as `Privilege::Write`) under `Role::Read` — the only
1330    /// pair the legacy fallback would also reject, but here the
1331    /// rejection comes through `frame.check_query_privilege` BEFORE
1332    /// the parsed-expression walker runs. Removing
1333    /// `required_privilege` (or the `is_satisfied_by` consult inside
1334    /// `check_query_privilege`) would force the deny path back to the
1335    /// inline `RedDBRuntime::check_query_privilege` walker — but the
1336    /// auth_store gate up there is bypassed when no auth_store is
1337    /// wired (embedded test mode), so this test would FLIP from
1338    /// denied to permitted and break the assertion below.
1339    #[test]
1340    fn insert_under_read_role_denied_via_frame_privilege() {
1341        reset_thread_locals();
1342        set_current_auth_identity("alice".to_string(), Role::Read);
1343
1344        let rt = fresh_runtime();
1345        // Bypass parser by reaching into the frame directly: the
1346        // frame derives privilege from the SQL prefix without
1347        // needing an auth_store wired up. Driving end-to-end via
1348        // `execute_query` would also reject (no table `t`), but for
1349        // a different reason — we want to pin the privilege seam.
1350        let frame = StatementExecutionFrame::build(&rt, "INSERT INTO t (id) VALUES (1)")
1351            .expect("frame builds for INSERT");
1352        let f: &dyn ReadFrame = &frame;
1353        assert_eq!(
1354            f.required_privilege(),
1355            Privilege::Write,
1356            "INSERT classified as Write"
1357        );
1358        let id = f.identity().expect("identity captured");
1359        assert!(
1360            !f.required_privilege().is_satisfied_by(id.1),
1361            "Role::Read does not satisfy Privilege::Write — frame must deny"
1362        );
1363
1364        // End-to-end: the frame's `check_query_privilege` sees the
1365        // (Read role, Write privilege) mismatch and denies before
1366        // dispatch. We drive a synthetic `QueryExpr::Table` because
1367        // the SELECT/INSERT parser would happen to also fail, and we
1368        // want the failure to come from the privilege seam.
1369        use crate::storage::query::ast::{QueryExpr, TableQuery};
1370        let expr = QueryExpr::Table(TableQuery::new("t"));
1371        let err = frame
1372            .check_query_privilege(&rt, &expr)
1373            .expect_err("denied via frame's coarse privilege gate");
1374        let msg = format!("{err}");
1375        assert!(
1376            msg.contains("permission denied") && msg.contains("Write"),
1377            "expected frame-level Write deny, got: {msg}"
1378        );
1379
1380        reset_thread_locals();
1381    }
1382
1383    /// End-to-end proof that the frame-owned row-buffer arena (#885) is
1384    /// wired into the SELECT path and produces observable results
1385    /// byte-identical to the per-request-allocation baseline.
1386    ///
1387    /// A table with more rows than the streaming high-water mark
1388    /// (`DEFAULT_HIGH_WATER_MARK`) forces the `execute_runtime_table_query_in`
1389    /// path to assemble many chunks, each leasing/recycling the frame
1390    /// arena's single chunk buffer. Driving it through `execute_query`
1391    /// (which builds a `StatementExecutionFrame` and lends its arena)
1392    /// must return every inserted row, in order — exactly what the
1393    /// allocate-per-chunk path returned. A bug in the arena wiring
1394    /// (dropped rows, bled rows, mis-ordering) would surface here.
1395    #[test]
1396    fn large_select_through_frame_arena_returns_all_rows_in_order() {
1397        reset_thread_locals();
1398        let rt = fresh_runtime();
1399        rt.execute_query("CREATE TABLE big (id INT)")
1400            .expect("create table");
1401
1402        // > DEFAULT_HIGH_WATER_MARK (1024) rows so the streaming channel
1403        // spans multiple chunks and the arena buffer is reused.
1404        const N: usize = 2_500;
1405        for start in (0..N).step_by(250) {
1406            let end = (start + 250).min(N);
1407            let values = (start..end)
1408                .map(|i| format!("({i})"))
1409                .collect::<Vec<_>>()
1410                .join(", ");
1411            rt.execute_query(&format!("INSERT INTO big (id) VALUES {values}"))
1412                .unwrap_or_else(|err| panic!("insert rows {start}..{end}: {err:?}"));
1413        }
1414
1415        let result = rt
1416            .execute_query("SELECT id FROM big ORDER BY id")
1417            .expect("large SELECT executes through the frame arena path");
1418        assert_eq!(result.statement_type, "select");
1419        assert_eq!(
1420            result.result.records.len(),
1421            N,
1422            "every inserted row streams back through the arena-backed channel"
1423        );
1424        for (i, record) in result.result.records.iter().enumerate() {
1425            assert_eq!(
1426                record.get("id"),
1427                Some(&crate::storage::schema::Value::Integer(i as i64)),
1428                "row {i} is byte-identical to the per-request-allocation baseline"
1429            );
1430        }
1431
1432        reset_thread_locals();
1433    }
1434
1435    /// Transport adapters may decode their wire-specific parameter value
1436    /// shapes, but SQL parsing/binding must stay behind the runtime's
1437    /// statement entrypoint. This pins the deeper seam introduced for
1438    /// parameterized query execution: HTTP, JSON-RPC, RedWire, PG wire,
1439    /// and gRPC all call `RedDBRuntime::execute_query_with_params`, which
1440    /// installs a real `StatementExecutionFrame` before dispatch.
1441    #[test]
1442    fn parameterized_transport_adapters_delegate_binding_to_runtime() {
1443        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
1444        let adapters = [
1445            "src/server/handlers_query.rs",
1446            "src/rpc_stdio.rs",
1447            "src/wire/redwire/session.rs",
1448            "src/wire/postgres/server.rs",
1449            "src/grpc.rs",
1450        ];
1451
1452        for relative in adapters {
1453            let path = manifest_dir.join(relative);
1454            let text = std::fs::read_to_string(&path)
1455                .unwrap_or_else(|err| panic!("read {}: {err}", path.display()));
1456            assert!(
1457                text.contains("execute_query_with_params"),
1458                "{relative} should delegate parameterized query execution to the runtime"
1459            );
1460            assert!(
1461                !text.contains("user_params::bind"),
1462                "{relative} must not bind SQL params in the transport adapter"
1463            );
1464        }
1465    }
1466
1467    /// Deletion-test for `ReadFrame::lock_intent`: a transaction
1468    /// control statement carries `LockIntent::None` and the
1469    /// `acquire_intent_locks` path returns `None` without consulting
1470    /// `intent_lock_modes_for`. Removing the method (or its consult
1471    /// site in `acquire_intent_locks`) would force the lock-mode
1472    /// helper to walk a fabricated parsed expression to reach the
1473    /// same conclusion — but the assertion that no guard is allocated
1474    /// for a `BEGIN` frame would still hold, so we additionally pin
1475    /// the classifier mapping above to make the deletion observable.
1476    #[test]
1477    fn control_statement_skips_intent_locks_via_frame() {
1478        reset_thread_locals();
1479        let rt = fresh_runtime();
1480
1481        let frame = StatementExecutionFrame::build(&rt, "BEGIN").expect("frame builds for BEGIN");
1482        let f: &dyn ReadFrame = &frame;
1483        assert_eq!(f.lock_intent(), LockIntent::None);
1484
1485        // Drive `acquire_intent_locks` against a fabricated SELECT
1486        // expression that WOULD normally yield `(IS, IS)`; the frame's
1487        // `lock_intent() == None` short-circuit must still suppress
1488        // the guard.
1489        use crate::storage::query::ast::{QueryExpr, TableQuery};
1490        let expr = QueryExpr::Table(TableQuery::new("t"));
1491        let guard = frame.acquire_intent_locks(&rt, &expr);
1492        assert!(
1493            guard.is_none(),
1494            "BEGIN frame's lock_intent=None must short-circuit lock acquisition"
1495        );
1496    }
1497}