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::execution_context::capture_current_snapshot;
7use super::impl_core::{
8    collections_referenced, current_auth_identity, current_connection_id, current_tenant,
9    has_with_prefix, intent_lock_modes_for, peek_top_level_as_of_with_table,
10    query_has_volatile_builtin, query_is_ask_statement, ConfigSnapshotGuard, CurrentSnapshotGuard,
11    KvStoreGuard, SecretStoreGuard, SnapshotContext, TxLocalTenantGuard,
12};
13use super::{RedDBRuntime, RuntimeQueryResult, RuntimeResultCacheEntry};
14use crate::api::{RedDBError, RedDBResult};
15use crate::auth::Role;
16use crate::storage::transaction::snapshot::{Snapshot, SnapshotRetentionGuard, Xid};
17use reddb_rql::ast::QueryExpr;
18use reddb_rql::modes::{detect_mode, parse_multi, QueryMode};
19
20/// Coarse privilege classification for a statement, computed once at
21/// frame-build time from the SQL text. Mirrors the three-role auth
22/// model (`Role::Read < Role::Write < Role::Admin`) so the frame can
23/// answer "can this identity run this statement?" without re-walking
24/// the parsed `QueryExpr` at every call site.
25///
26/// `None` means the statement does not touch the privilege gate at
27/// all (transaction control, SET, SHOW). Such statements must remain
28/// runnable under any authenticated identity.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub(crate) enum Privilege {
31    /// Read-only data access (SELECT, EXPLAIN, SHOW). Satisfied by
32    /// any role from `Role::Read` upward.
33    Read,
34    /// Mutation of user data or schema author DDL (INSERT, UPDATE,
35    /// DELETE, CREATE/ALTER/DROP TABLE, CREATE MIGRATION). Requires
36    /// at least `Role::Write`.
37    Write,
38    /// Authority statements — GRANT, REVOKE, ALTER USER, APPLY /
39    /// ROLLBACK MIGRATION, IAM policy mutation. Requires `Role::Admin`.
40    Admin,
41    /// Statement does not consult the privilege gate (BEGIN, COMMIT,
42    /// ROLLBACK, SET, SHOW with no data exposure). Always permitted
43    /// for any authenticated identity.
44    None,
45}
46
47impl Privilege {
48    /// `true` iff `role` is sufficient to execute a statement carrying
49    /// this required privilege. Encodes the standard `Read ⊆ Write ⊆
50    /// Admin` containment used by the auth fallback path.
51    pub(crate) fn is_satisfied_by(self, role: Role) -> bool {
52        match self {
53            Self::None => true,
54            Self::Read => role.can_read(),
55            Self::Write => role.can_write(),
56            Self::Admin => role.can_admin(),
57        }
58    }
59}
60
61/// Coarse lock intent for a statement, computed once at frame-build
62/// time. Maps onto the storage-layer's `LockMode` matrix downstream
63/// but stays decoupled here so the runtime can answer "does this
64/// statement need the lock manager at all?" without a `use storage::`
65/// at every call site.
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub(crate) enum LockIntent {
68    /// No collection-level lock needed (transaction control, SET,
69    /// SHOW, EXPLAIN). The lock-acquisition path can short-circuit.
70    None,
71    /// Reader-style intent: SELECT, joins, graph / queue / search
72    /// reads. Maps to `(IS, IS)` at the storage layer.
73    Shared,
74    /// Writer- or DDL-style intent: INSERT/UPDATE/DELETE (`(IX, IX)`)
75    /// and CREATE/ALTER/DROP (`(IX, X)`). Both are surfaced as
76    /// `Exclusive` at this granularity — call sites that need the
77    /// finer distinction still consult `intent_lock_modes_for`.
78    Exclusive,
79}
80
81/// Small, stable Interface that *represents* a read statement's
82/// execution context. Every read caller that needs to know "under
83/// what scope / identity / snapshot am I running, and is there an
84/// AS OF floor in effect?" consults this trait — never the
85/// underlying thread-locals or runtime fields directly.
86///
87/// The deletion test: removing this trait would force the four
88/// concerns it exposes back into ad-hoc lookups at every read
89/// callsite (`current_tenant()`, `current_auth_identity()`,
90/// `capture_current_snapshot()`, AS OF re-parsing). The trait
91/// concentrates them in one place so future changes (per-statement
92/// logging, audit, scope policy) have a single seam to extend.
93pub(crate) trait ReadFrame {
94    /// Effective tenant scope for the statement after WITHIN /
95    /// SET LOCAL TENANT / SET TENANT resolution. `None` means
96    /// "no tenant bound" (RLS deny-default applies).
97    fn effective_scope(&self) -> Option<&str>;
98
99    /// Authenticated identity observed at frame-build time, if any.
100    /// Returns `(username, role)` so callers can render audit lines
101    /// or feed RLS policy lookups without re-reading thread-locals.
102    fn identity(&self) -> Option<(&str, Role)>;
103
104    /// MVCC snapshot the statement reads against. For autocommit
105    /// this is a fresh snapshot; inside an active transaction it
106    /// is the txn's snapshot; under AS OF it is the resolved
107    /// historical xid.
108    fn snapshot(&self) -> &Snapshot;
109
110    /// Complete visibility context, including the reader's savepoint writes.
111    fn snapshot_context(&self, runtime: &RedDBRuntime) -> SnapshotContext {
112        SnapshotContext {
113            snapshot: self.snapshot().clone(),
114            manager: runtime.inner.transaction_state.snapshot_manager(),
115            own_xids: HashSet::new(),
116            requires_index_fallback: true,
117            serializable_reader: None,
118        }
119    }
120
121    /// AS OF xid floor when AS OF was applied for this statement,
122    /// `None` for live reads. Useful for downstream callers that
123    /// want to gate behaviour on historical-read mode without
124    /// re-parsing the query.
125    fn as_of_floor(&self) -> Option<Xid>;
126
127    /// Stable result-cache key for the statement (already mixes
128    /// effective tenant + identity).
129    fn cache_key(&self) -> &str;
130
131    /// Whether the statement is safe to serve from / populate the
132    /// result cache. Combines two underlying signals:
133    ///
134    ///   * the query does not call a volatile builtin (e.g. `NOW()`,
135    ///     `RANDOM()`, `UUID()`), which would change between calls,
136    ///   * the connection is not inside an active transaction with
137    ///     uncommitted writes that other readers shouldn't observe.
138    ///
139    /// SELECT cache callsites (read + write) consult this method
140    /// instead of re-deriving safety from globals or poking the
141    /// frame's private fields. Removing it would force every cache
142    /// callsite to re-run `query_has_volatile_builtin` plus
143    /// `result_cache_safe(conn_id)` inline.
144    fn should_cache_result(&self) -> bool;
145
146    /// Coarse privilege class the statement requires, computed once
147    /// at frame-build time from the SQL prefix. Read/write dispatch
148    /// sites consult this instead of re-classifying the parsed
149    /// `QueryExpr` inline at every callsite.
150    ///
151    /// Removing this method would force every privilege gate to
152    /// recompute the (action, resource) classification from the
153    /// parsed expression and re-check the role hierarchy inline.
154    fn required_privilege(&self) -> Privilege;
155
156    /// Coarse collection-level lock intent the statement implies.
157    /// `None` lets the lock-acquisition path short-circuit without
158    /// touching the lock manager.
159    ///
160    /// Removing this method would force the lock-acquisition path
161    /// to always invoke `intent_lock_modes_for` (which itself walks
162    /// the parsed expression) even for transaction-control / SET /
163    /// SHOW statements that need no collection lock at all.
164    fn lock_intent(&self) -> LockIntent;
165
166    /// Set of collection ids the calling identity is allowed to
167    /// observe under the active `(tenant, role)` scope. Computed once
168    /// at frame-build time via the `AuthStore` visible-collections
169    /// cache (see `auth::scope_cache`) and used by `AuthorizedSearch`
170    /// to pre-filter SEARCH SIMILAR / SEARCH CONTEXT candidate sets
171    /// before any similarity score is computed (issue #119).
172    ///
173    /// `None` means the frame was built without an auth store wired —
174    /// embedded / single-tenant tests run that way. AI search call
175    /// sites refuse to proceed with `None`, which is the deny-default
176    /// the issue requires; pure SELECT paths fall back to the existing
177    /// per-row RLS gate.
178    fn visible_collections(&self) -> Option<&std::collections::HashSet<String>>;
179}
180
181/// Cheap first-word classification of a SQL statement, used at
182/// frame-build time to derive `Privilege` + `LockIntent` without
183/// re-parsing the query. Matches the keywords that the legacy
184/// inline checks in `RedDBRuntime::check_query_privilege` and
185/// `intent_lock_modes_for` already key on.
186/// Whether [`statement_kind`] reads `query` as a mutating statement.
187/// The Request seam uses it to keep its pre-write commit-policy check off
188/// read paths.
189pub(crate) fn statement_is_write(query: &str) -> bool {
190    statement_kind(query) == "write"
191}
192
193fn statement_kind(query: &str) -> &'static str {
194    let trimmed = query.trim_start();
195    // Skip a leading line / block comment so the classifier doesn't
196    // misread `/* ... */ SELECT ...` as an unknown statement.
197    let trimmed = if let Some(rest) = trimmed.strip_prefix("--") {
198        rest.split_once('\n')
199            .map(|(_, r)| r)
200            .unwrap_or("")
201            .trim_start()
202    } else {
203        trimmed
204    };
205    let mut tokens = trimmed.split(|c: char| c.is_whitespace() || c == '(' || c == ';');
206    let first = tokens.next().unwrap_or("");
207    let second = tokens.next().unwrap_or("");
208    if first.eq_ignore_ascii_case("KV") {
209        if second.eq_ignore_ascii_case("GET")
210            || second.eq_ignore_ascii_case("LIST")
211            || second.eq_ignore_ascii_case("WATCH")
212        {
213            return "read";
214        }
215        return "write";
216    }
217    if first.eq_ignore_ascii_case("VAULT") {
218        if second.eq_ignore_ascii_case("GET")
219            || second.eq_ignore_ascii_case("REVEAL")
220            || second.eq_ignore_ascii_case("UNSEAL")
221            || second.eq_ignore_ascii_case("LIST")
222            || second.eq_ignore_ascii_case("WATCH")
223            || second.eq_ignore_ascii_case("HISTORY")
224        {
225            return "read";
226        }
227        return "write";
228    }
229    // ASCII-uppercase compare without allocating: SQL keywords are ASCII.
230    let mut buf = [0u8; 16];
231    let bytes = first.as_bytes();
232    let n = bytes.len().min(buf.len());
233    for i in 0..n {
234        buf[i] = bytes[i].to_ascii_uppercase();
235    }
236    match &buf[..n] {
237        b"SELECT" | b"WITH" | b"SHOW" | b"EXPLAIN" | b"DESCRIBE" | b"DESC" | b"RANK"
238        | b"APPROX" | b"APPROXIMATE" | b"ZRANK" | b"ZRANGE" | b"LIST" | b"WATCH" | b"GET"
239        | b"HISTORY" | b"REVEAL" | b"UNSEAL" => "read",
240        b"INSERT" | b"UPDATE" | b"DELETE" | b"UPSERT" | b"MERGE" | b"COPY" | b"TRUNCATE" => "write",
241        b"CREATE" | b"ALTER" | b"DROP" | b"PROMOTE" | b"REINDEX" | b"VACUUM" | b"ANALYZE" => "ddl",
242        b"GRANT" | b"REVOKE" => "admin",
243        b"BEGIN" | b"START" | b"COMMIT" | b"ROLLBACK" | b"SAVEPOINT" | b"RELEASE" | b"END"
244        | b"SET" | b"RESET" | b"PREPARE" | b"EXECUTE" | b"DEALLOCATE" | b"USE" => "control",
245        b"PUT" | b"INCR" | b"DECR" | b"ADD" | b"ROTATE" | b"PURGE" | b"INVALIDATE" => "write",
246        _ => "unknown",
247    }
248}
249
250/// Refuse a pre-parsed expression that carries a top-level `AS OF`.
251///
252/// `AS OF` is resolved from the statement text (`AsOfSpec` -> commit /
253/// branch / tag / timestamp -> xid) and `TableQuery::as_of` is consumed
254/// nowhere in the runtime or scan path. An expression-only frame
255/// therefore cannot honour it, and installing a live snapshot for a
256/// historical read would answer with current rows presented as history.
257/// Fail loudly instead; callers that have the text (`execute_query`,
258/// `execute_prepared_query`, `execute_query_with_params`) resolve it
259/// correctly. Mirrors `peek_top_level_as_of_with_table`, which likewise
260/// only recognises a top-level `AS OF`.
261fn reject_unresolvable_as_of(expr: &QueryExpr) -> RedDBResult<()> {
262    let QueryExpr::Table(table) = expr else {
263        return Ok(());
264    };
265    if table.as_of.is_none() {
266        return Ok(());
267    }
268    Err(RedDBError::InvalidOperation(
269        "AS OF cannot be resolved from a pre-parsed expression — \
270         execute the statement text (execute_query / execute_prepared_query / \
271         execute_query_with_params) so the historical snapshot is resolved"
272            .to_string(),
273    ))
274}
275
276fn classify_privilege(query: &str) -> Privilege {
277    match statement_kind(query) {
278        "read" => Privilege::Read,
279        "write" => Privilege::Write,
280        // DDL is gated at `Role::Write` in the legacy fallback (see
281        // `RedDBRuntime::check_query_privilege` for CreateTable et al.),
282        // so it classifies as Write here. APPLY / ROLLBACK MIGRATION and
283        // GRANT / REVOKE upgrade to Admin via finer checks at the call
284        // site — the frame surfaces only the coarse class.
285        "ddl" => Privilege::Write,
286        "admin" => Privilege::Admin,
287        _ => Privilege::None,
288    }
289}
290
291fn classify_lock_intent(query: &str) -> LockIntent {
292    match statement_kind(query) {
293        "read" => LockIntent::Shared,
294        "write" | "ddl" => LockIntent::Exclusive,
295        _ => LockIntent::None,
296    }
297}
298
299pub(super) struct StatementExecutionFrame {
300    tx_local_tenant: Option<Option<String>>,
301    snapshot: Snapshot,
302    snapshot_retention: RefCell<Option<SnapshotRetentionGuard>>,
303    own_xids: HashSet<Xid>,
304    serializable_reader: Option<Xid>,
305    cache_key: String,
306    is_volatile_query: bool,
307    cache_safe: bool,
308    /// Effective tenant captured at frame-build time after WITHIN /
309    /// SET LOCAL TENANT / SET TENANT resolution. Stored on the frame
310    /// so the `ReadFrame` Interface can return a borrow without
311    /// re-touching the thread-local stack.
312    effective_scope: Option<String>,
313    /// Auth identity captured at frame-build time. `None` for
314    /// embedded / anonymous callers.
315    identity: Option<(String, Role)>,
316    /// `Some(xid)` when AS OF resolved to a historical xid; `None`
317    /// for live reads.
318    as_of_floor: Option<Xid>,
319    /// True when the statement snapshot can require tuple versions that
320    /// current secondary indexes no longer contain.
321    requires_index_fallback: bool,
322    /// Privilege class required by the statement, derived from the
323    /// SQL text at frame-build time. Read/write dispatch sites
324    /// consult this instead of re-classifying the parsed expression.
325    required_privilege: Privilege,
326    /// Collection-level lock intent the statement implies. The
327    /// lock-acquisition path short-circuits when this is `None`.
328    lock_intent: LockIntent,
329    /// Set of collection ids the active `(tenant, role)` scope is
330    /// allowed to observe. Computed at frame-build time via the
331    /// `AuthStore` visibility cache and consumed by `AuthorizedSearch`
332    /// to gate SEARCH SIMILAR / SEARCH CONTEXT candidate sets before
333    /// scoring (issue #119). `None` when no auth store is wired
334    /// (embedded test mode) — AI search refuses on `None`.
335    visible_collections: Option<HashSet<String>>,
336    /// Per-owner buffer arena for query-result row chunks (#885). Owned
337    /// by the frame because the frame already owns the query lifecycle;
338    /// lent to the row-streaming path (`execute_runtime_table_query_in`)
339    /// so chunk buffers are reused across the statement's chunk-fetches
340    /// instead of allocated fresh per chunk. Reclaimed when the frame
341    /// drops at statement end — no `thread_local!` scratch, which would
342    /// be unsound under tokio's work-stealing runtime.
343    row_arena: Rc<RefCell<super::query_exec::RowBufferArena>>,
344}
345
346pub(super) struct StatementFrameGuards {
347    _tx_local_guard: TxLocalTenantGuard,
348    _config_snapshot_guard: ConfigSnapshotGuard,
349    _secret_store_guard: SecretStoreGuard,
350    _kv_store_guard: KvStoreGuard,
351    _snapshot_guard: CurrentSnapshotGuard,
352}
353
354pub(super) struct PreparedStatement {
355    pub(super) expr: QueryExpr,
356    pub(super) mode: QueryMode,
357}
358
359/// What a `StatementExecutionFrame` is built from.
360///
361/// The frame derives the statement snapshot (including any `AS OF`
362/// floor), the coarse privilege class, the lock intent, the volatility
363/// flag, and the result-cache key from its input. Feeding it anything
364/// other than the statement itself makes every one of those describe a
365/// different statement than the one that runs, so the input is named
366/// explicitly here rather than being "some string".
367#[derive(Clone, Copy)]
368pub(super) enum StatementIdentity<'a> {
369    /// The statement's SQL text. All five derivations are exact.
370    Text(&'a str),
371    /// A pre-parsed expression with no accompanying text — the nested
372    /// in-statement callers (CTE prelude, materialized-view refresh,
373    /// inline graph TVF) hold an expression the outer statement already
374    /// parsed.
375    ///
376    /// Text-derived facts are not guessed from a kind label: there is no
377    /// stable cache key (a label would collide across every statement of
378    /// the same kind), and the coarse privilege / lock short-circuits are
379    /// left at `None` so the deep grant engine stays the gate. `AS OF` is
380    /// rejected up front by `build` because it cannot be resolved without
381    /// the text.
382    Expr(&'a QueryExpr),
383}
384
385impl<'a> StatementIdentity<'a> {
386    /// SQL text when the frame was built from text, `""` otherwise. Used
387    /// for the text-derived classifications, all of which degrade to the
388    /// deliberately inert `unknown` / `None` classes on the expr path.
389    fn text(&self) -> &'a str {
390        match self {
391            Self::Text(query) => query,
392            Self::Expr(_) => "",
393        }
394    }
395}
396
397impl StatementExecutionFrame {
398    pub(super) fn build(
399        runtime: &RedDBRuntime,
400        identity_source: StatementIdentity<'_>,
401    ) -> RedDBResult<Self> {
402        let query = identity_source.text();
403        if let StatementIdentity::Expr(expr) = identity_source {
404            reject_unresolvable_as_of(expr)?;
405        }
406        let conn_id = current_connection_id();
407        let tx_local_tenant = runtime.inner.transaction_state.local_tenant(conn_id);
408        let tx_context = runtime.inner.transaction_state.context(conn_id);
409        let own_xids = own_transaction_xids(tx_context.as_ref());
410        let serializable_reader = tx_context
411            .as_ref()
412            .filter(|ctx| {
413                ctx.isolation == crate::storage::transaction::IsolationLevel::Serializable
414            })
415            .map(|ctx| ctx.xid);
416        let (snapshot, as_of_floor, snapshot_retention) =
417            runtime.statement_snapshot(query, identity_source)?;
418        let requires_index_fallback = as_of_floor.is_some() || tx_context.is_some();
419        let (cache_key, is_volatile_query) = match identity_source {
420            StatementIdentity::Text(_) => (
421                result_cache_key(query),
422                query_has_volatile_builtin(query) || query_is_ask_statement(query),
423            ),
424            // No text means no stable key, so the frame opts out of the
425            // result cache on both sides: an empty key is never read from
426            // or written to, and `is_volatile_query` is set so
427            // `should_cache_result` refuses regardless of the key.
428            StatementIdentity::Expr(_) => (String::new(), true),
429        };
430        let cache_safe = runtime.result_cache_safe(conn_id);
431        // Capture identity + effective scope under the same
432        // thread-local view that the cache key was built from, so
433        // the Interface and the cache key agree on what "this
434        // statement" means.
435        let effective_scope = current_tenant();
436        let identity = current_auth_identity();
437
438        // Coarse classification of the statement, computed once from
439        // the SQL prefix so downstream callers don't re-derive it
440        // from the parsed `QueryExpr` at every privilege / lock site.
441        // On the expr path `query` is empty, so both classify as the
442        // inert `None` class: the coarse gate can only deny, never
443        // allow (see `check_query_privilege`), so declining to
444        // short-circuit leaves the deep grant engine as the gate.
445        let required_privilege = classify_privilege(query);
446        let lock_intent = classify_lock_intent(query);
447
448        // Issue #119: resolve the visible-collections set for the
449        // active (tenant, role) scope. Only meaningful when an auth
450        // store is wired *and* an identity was captured — embedded
451        // anonymous callers fall back to `None`, and AI search call
452        // sites refuse on `None`.
453        let visible_collections = match (runtime.inner.auth_store.read().clone(), identity.as_ref())
454        {
455            (Some(store), Some((principal, role))) => {
456                let collections = runtime.inner.db.store().list_collections();
457                Some(store.visible_collections_for_scope(
458                    effective_scope.as_deref(),
459                    *role,
460                    principal,
461                    &collections,
462                ))
463            }
464            _ => None,
465        };
466
467        Ok(Self {
468            tx_local_tenant,
469            snapshot,
470            snapshot_retention: RefCell::new(Some(snapshot_retention)),
471            own_xids,
472            serializable_reader,
473            cache_key,
474            is_volatile_query,
475            cache_safe,
476            effective_scope,
477            identity,
478            as_of_floor,
479            requires_index_fallback,
480            required_privilege,
481            lock_intent,
482            visible_collections,
483            row_arena: Rc::new(RefCell::new(super::query_exec::RowBufferArena::new())),
484        })
485    }
486
487    /// Lend the frame's per-owner row-buffer arena (#885) to the
488    /// row-streaming path. Returns a cloned `Rc` handle; the frame remains
489    /// the owner and the arena is reclaimed when the frame drops at
490    /// statement end.
491    pub(super) fn row_arena(&self) -> Rc<RefCell<super::query_exec::RowBufferArena>> {
492        Rc::clone(&self.row_arena)
493    }
494
495    pub(super) fn install(&self, runtime: &RedDBRuntime) -> StatementFrameGuards {
496        StatementFrameGuards {
497            _tx_local_guard: TxLocalTenantGuard::install(self.tx_local_tenant.clone()),
498            _config_snapshot_guard: ConfigSnapshotGuard::install(
499                Arc::clone(&runtime.inner.db),
500                runtime.inner.auth_store.read().clone(),
501            ),
502            _secret_store_guard: SecretStoreGuard::install(runtime),
503            _kv_store_guard: KvStoreGuard::install(runtime.inner.auth_store.read().clone()),
504            _snapshot_guard: CurrentSnapshotGuard::install(SnapshotContext {
505                snapshot: self.snapshot.clone(),
506                manager: runtime.inner.transaction_state.snapshot_manager(),
507                own_xids: self.own_xids.clone(),
508                requires_index_fallback: self.requires_index_fallback,
509                serializable_reader: self.serializable_reader,
510            }),
511        }
512    }
513
514    pub(super) fn cache_key(&self) -> &str {
515        &self.cache_key
516    }
517
518    pub(super) fn can_read_result_cache(&self) -> bool {
519        // Delegates to the `ReadFrame` Interface so the volatile +
520        // active-tx safety decision lives in exactly one place.
521        <Self as ReadFrame>::should_cache_result(self)
522    }
523
524    pub(super) fn should_write_result_cache(&self, result: &RuntimeQueryResult) -> bool {
525        // Cache-safety (volatile builtin, active-tx writes) comes from
526        // the Interface; the rest are write-side payload heuristics
527        // (statement shape, result size) that aren't part of the
528        // safety contract.
529        <Self as ReadFrame>::should_cache_result(self)
530            && result.statement_type == "select"
531            && result.engine != "vault"
532            && result.engine != "runtime-rank"
533            // `QUEUE READ` is a stateful read: a delayed message
534            // (issue #722) becomes deliverable over time without a
535            // producer push to invalidate the cache, so a cached empty
536            // result would hide it. Skip caching entirely.
537            && result.statement != "queue_group_read"
538            // SCRUB is a stateful read too: the background form advances
539            // a pacing cursor per tick (a cached tick would replay the
540            // summary and never advance), and even a full pass must
541            // re-read the file to see new corruption. Never cache.
542            && result.engine != "runtime-scrub"
543            && result.result.pre_serialized_json.is_none()
544            // Graph-analytics TVF output (issue #802) is deterministic and
545            // expensive to recompute, so it is cached at any row count. The
546            // ≤5-row heuristic only bounds payload size for ordinary SELECTs.
547            && (is_graph_tvf_engine(result.engine) || result.result.records.len() <= 5)
548    }
549
550    pub(super) fn read_result_cache(&self, runtime: &RedDBRuntime) -> Option<RuntimeQueryResult> {
551        if runtime.resource_limits().read_execution_limits_enabled() {
552            return None;
553        }
554        if self.can_read_result_cache() {
555            runtime
556                .get_result_cache_entry(self.cache_key())
557                .map(|mut result| {
558                    if let Some(vector) = result.result.stats.vector.as_mut() {
559                        vector.cache_hit = true;
560                    }
561                    result
562                })
563        } else {
564            None
565        }
566    }
567
568    pub(super) fn write_result_cache(
569        &self,
570        runtime: &RedDBRuntime,
571        result: &RuntimeQueryResult,
572        scopes: HashSet<String>,
573    ) {
574        if self.should_write_result_cache(result) {
575            runtime.put_result_cache_entry(
576                self.cache_key(),
577                RuntimeResultCacheEntry {
578                    result: result.clone(),
579                    cached_at: std::time::Instant::now(),
580                    scopes,
581                },
582            );
583        }
584    }
585
586    pub(super) fn prepare_cte(&self, query: &str) -> RedDBResult<Option<QueryExpr>> {
587        // Detected via cheap prefix check so non-CTE queries skip the
588        // full parse here. CTE-bearing queries bypass the plan cache
589        // and result cache (rare workload — perf optimization is a
590        // follow-up). Inlining substitutes every CTE reference with
591        // its body as a subquery in FROM, after which the existing
592        // subquery-in-FROM machinery handles execution. Recursive
593        // CTEs are rejected explicitly until fixpoint execution wires
594        // through the runtime.
595        if !has_with_prefix(query) {
596            return Ok(None);
597        }
598        let parsed =
599            reddb_rql::parser::parse(query).map_err(|err| RedDBError::Query(err.to_string()))?;
600        if parsed.with_clause.is_some() {
601            let rewritten = crate::storage::query::executors::inline_ctes(parsed)
602                .map_err(|err| RedDBError::Query(err.to_string()))?;
603            return Ok(Some(rewritten));
604        }
605        // No WITH after parse (the prefix matched something else like
606        // `WITHIN` that already routed elsewhere) — fall through to
607        // the normal path with the original query.
608        Ok(None)
609    }
610
611    pub(super) fn prepare_statement(
612        &self,
613        runtime: &RedDBRuntime,
614        query: &str,
615    ) -> RedDBResult<PreparedStatement> {
616        let mode = detect_mode(query);
617        if matches!(mode, QueryMode::Unknown) {
618            return Err(RedDBError::Query("unable to detect query mode".to_string()));
619        }
620
621        // ── Plan cache: reuse only exact-query ASTs ──
622        //
623        // DML statements (INSERT/UPDATE/DELETE) almost always have unique literal
624        // values, so caching them burns CPU on eviction bookkeeping (Vec::remove(0)
625        // shifts the entire LRU list) with zero hit rate. Skip the cache entirely
626        // Plan cache applies to statements whose shape can be
627        // normalised + rebound (`UPDATE t SET x=? WHERE _entity_id=?`
628        // reuses the same plan across thousands of varying literals).
629        // INSERT is still bypassed — its shape changes per column set
630        // and bulk paths don't go through here anyway.
631        let first_word = query
632            .trim()
633            .split_ascii_whitespace()
634            .next()
635            .unwrap_or("")
636            .to_ascii_uppercase();
637        let is_insert = first_word == "INSERT";
638        // #1370 — volatile queries ($config / $secret resolve mutable runtime
639        // state at execution time) must bypass the plan cache too. A cached
640        // optimized plan drops the live `$config` resolution, so a later
641        // `SET CONFIG` would be ignored and the query would serve a stale value.
642        // Re-parse fresh every time so the resolver runs against current state.
643        let bypass_plan_cache = is_insert || self.is_volatile_query;
644
645        // Fused normalize+extract: one byte-scan produces both the
646        // cache_key AND the literal bindings. Saves a second Lexer
647        // pass over the query text on every cache hit — dominant
648        // cost on tight UPDATE loops that hit the same shape
649        // thousands of times with varying literals.
650        let (cache_key, prescan_binds) = if bypass_plan_cache {
651            (String::new(), Vec::new())
652        } else {
653            crate::storage::query::planner::cache_key::normalize_and_extract(query)
654        };
655
656        let expr = if bypass_plan_cache {
657            // Bypass plan cache for INSERT — shape varies per query.
658            parse_multi(query).map_err(|err| RedDBError::Query(err.to_string()))?
659        } else {
660            // ── Hot path: read lock only (no writer serialization on cache hits) ──
661            //
662            // peek() is a non-mutating probe: no LRU promotion, no touch().
663            // This lets concurrent readers proceed without blocking each other.
664            // On hit we bind literals if needed and return immediately.
665            // Only on miss do we drop to a write lock to parse + insert.
666            let hit = {
667                let plan_cache = runtime.inner.query_cache.read();
668                plan_cache.peek(&cache_key).map(|cached| {
669                    let parameter_count = cached.parameter_count;
670                    let optimized = cached.plan.optimized.clone();
671                    let exact_query = cached.exact_query.clone();
672                    (parameter_count, optimized, exact_query)
673                })
674            };
675
676            if let Some((parameter_count, optimized, exact_query)) = hit {
677                if parameter_count > 0 {
678                    // Shape hit: use the binds extracted during normalise.
679                    let shape_binds = prescan_binds.clone();
680                    if let Some(bound) =
681                        crate::storage::query::planner::shape::bind_parameterized_query(
682                            &optimized,
683                            &shape_binds,
684                            parameter_count,
685                        )
686                    {
687                        bound
688                    } else {
689                        // A failed bind leaves placeholders in the cached AST,
690                        // even for the same exact SQL. Never execute it unbound.
691                        parse_multi(query).map_err(|err| RedDBError::Query(err.to_string()))?
692                    }
693                } else {
694                    // No parameters means either there truly are no literals,
695                    // or this statement type does not participate in shape
696                    // parameterization (for example graph/queue commands).
697                    // Reusing a normalized-cache hit across a different exact
698                    // query can therefore leak stale literals into execution.
699                    if exact_query.as_deref() == Some(query) {
700                        optimized
701                    } else {
702                        parse_multi(query).map_err(|err| RedDBError::Query(err.to_string()))?
703                    }
704                }
705            } else {
706                // Cache miss — parse, parameterize, store.
707                let parsed =
708                    parse_multi(query).map_err(|err| RedDBError::Query(err.to_string()))?;
709                let (cached_expr, parameter_count) = if let Some(prepared) =
710                    crate::storage::query::planner::shape::parameterize_query_expr(&parsed)
711                {
712                    (prepared.shape, prepared.parameter_count)
713                } else {
714                    (parsed.clone(), 0)
715                };
716                {
717                    let mut pc = runtime.inner.query_cache.write();
718                    let plan = crate::storage::query::planner::QueryPlan::new(
719                        parsed.clone(),
720                        cached_expr,
721                        Default::default(),
722                    );
723                    pc.insert(
724                        cache_key.clone(),
725                        crate::storage::query::planner::CachedPlan::new(plan)
726                            .with_shape_key(cache_key.clone())
727                            .with_exact_query(query.to_string())
728                            .with_parameter_count(parameter_count),
729                    );
730                }
731                parsed
732            }
733        };
734
735        // Phase 5 PG parity: substitute any registered view name that
736        // appears in the expression with its stored body. Runs after
737        // parse and before dispatch so the SQL entrypoint gets the
738        // same view resolution `execute_query_expr` already does.
739        let expr = runtime.rewrite_view_refs(expr);
740
741        Ok(PreparedStatement { expr, mode })
742    }
743
744    pub(super) fn check_query_privilege(
745        &self,
746        runtime: &RedDBRuntime,
747        expr: &QueryExpr,
748    ) -> RedDBResult<()> {
749        // Frame-level coarse gate. We consult `required_privilege()`
750        // (computed once at frame-build) against the captured identity
751        // before the deep grant engine walks the parsed expression.
752        // The coarse gate cannot ALLOW anything the grant engine would
753        // deny — it only short-circuits the obvious "Role::Read tries
754        // INSERT" case so a downstream caller never has to redo this
755        // check inline. `Privilege::None` (transaction control / SET /
756        // SHOW) flows through unchanged; the grant engine treats those
757        // as bypass too.
758        if let Some((username, role)) = <Self as ReadFrame>::identity(self) {
759            let needed = <Self as ReadFrame>::required_privilege(self);
760            if !needed.is_satisfied_by(role) {
761                // Issue #205 — when the deep grant engine *also*
762                // denies, we treat this as an ordinary permission
763                // failure. But when an Admin-only statement reaches
764                // this gate without an auth_store wired (so the deep
765                // engine can't double-check), the coarse rejection is
766                // the only line of defence — emit an OperatorEvent so
767                // the operator notices an Admin-class statement was
768                // attempted with insufficient role.
769                if matches!(needed, Privilege::Admin) && runtime.inner.auth_store.read().is_none() {
770                    crate::telemetry::operator_event::OperatorEvent::AuthBypass {
771                        principal: username.to_string(),
772                        resource: format!("statement requiring {needed:?}"),
773                        detail: format!(
774                            "auth_store not wired; coarse gate is sole defence (role={role:?})"
775                        ),
776                    }
777                    .emit_global();
778                }
779                return Err(RedDBError::Query(format!(
780                    "permission denied: principal=`{username}` role=`{role:?}` lacks {needed:?} privilege"
781                )));
782            }
783        }
784        runtime
785            .check_query_privilege(expr)
786            .map_err(|err| RedDBError::Query(format!("permission denied: {err}")))
787    }
788
789    pub(super) fn prepare_dispatch(
790        &self,
791        runtime: &RedDBRuntime,
792        expr: &QueryExpr,
793    ) -> RedDBResult<Option<crate::runtime::locking::LockerGuard>> {
794        runtime.validate_model_operations_before_auth(expr)?;
795        self.check_query_privilege(runtime, expr)?;
796        self.release_snapshot_for_maintenance(expr);
797        self.acquire_intent_locks(runtime, expr)
798    }
799
800    pub(super) fn release_snapshot_for_maintenance(&self, expr: &QueryExpr) {
801        if matches!(
802            expr,
803            QueryExpr::MaintenanceCommand(reddb_rql::ast::MaintenanceCommand::Vacuum { .. })
804        ) {
805            // VACUUM inspects physical versions rather than reading its own
806            // statement snapshot. Its temporary pin would otherwise inhibit
807            // reclamation, especially with unused reserved autocommit xids.
808            // Outer/nested reader frames keep their independent pins.
809            self.snapshot_retention.borrow_mut().take();
810        }
811    }
812
813    pub(super) fn acquire_intent_locks(
814        &self,
815        runtime: &RedDBRuntime,
816        expr: &QueryExpr,
817    ) -> RedDBResult<Option<crate::runtime::locking::LockerGuard>> {
818        use crate::runtime::lock_manager::LockMode;
819        use crate::runtime::locking::{LockerGuard, Resource};
820
821        if !runtime.config_bool("concurrency.locking.enabled", true) {
822            return Ok(None);
823        }
824        // Frame-level short-circuit: if the statement carries no lock
825        // intent (transaction control, SET, SHOW), skip the lock
826        // manager entirely instead of letting `intent_lock_modes_for`
827        // walk the parsed expression to reach the same conclusion.
828        if matches!(<Self as ReadFrame>::lock_intent(self), LockIntent::None) {
829            return Ok(None);
830        }
831        let Some((global_mode, coll_mode)) = intent_lock_modes_for(expr) else {
832            return Ok(None);
833        };
834        // A failed acquire (timeout, deadlock) used to be discarded and the
835        // statement ran unlocked (#2376). Fail it instead; the client retries.
836        let acquire = |guard: &mut LockerGuard, resource: Resource, mode: LockMode| {
837            guard.acquire(resource.clone(), mode).map_err(|err| {
838                RedDBError::Query(format!(
839                    "could not acquire {mode:?} lock on {resource:?}: {err}; retry the statement"
840                ))
841            })
842        };
843        let mut guard = LockerGuard::new(runtime.inner.lock_manager.clone());
844        acquire(&mut guard, Resource::Global, global_mode)?;
845        // DDL takes X on its own collection, but every DDL also rewrites
846        // shared catalog state the collection lock does not cover: the
847        // system collections, the physical metadata and a full-store
848        // `persist()`. Serialise all DDL on the catalog (#2376).
849        if coll_mode == LockMode::Exclusive {
850            acquire(&mut guard, Resource::Catalog, LockMode::Exclusive)?;
851        }
852        for collection in collections_referenced(expr) {
853            acquire(&mut guard, Resource::Collection(collection), coll_mode)?;
854        }
855        Ok(Some(guard))
856    }
857}
858
859impl ReadFrame for StatementExecutionFrame {
860    fn snapshot_context(&self, runtime: &RedDBRuntime) -> SnapshotContext {
861        SnapshotContext {
862            snapshot: self.snapshot.clone(),
863            manager: runtime.inner.transaction_state.snapshot_manager(),
864            own_xids: self.own_xids.clone(),
865            requires_index_fallback: self.requires_index_fallback,
866            serializable_reader: self.serializable_reader,
867        }
868    }
869
870    fn effective_scope(&self) -> Option<&str> {
871        self.effective_scope.as_deref()
872    }
873
874    fn identity(&self) -> Option<(&str, Role)> {
875        self.identity.as_ref().map(|(u, r)| (u.as_str(), *r))
876    }
877
878    fn snapshot(&self) -> &Snapshot {
879        &self.snapshot
880    }
881
882    fn as_of_floor(&self) -> Option<Xid> {
883        self.as_of_floor
884    }
885
886    fn cache_key(&self) -> &str {
887        &self.cache_key
888    }
889
890    fn should_cache_result(&self) -> bool {
891        !self.is_volatile_query && self.cache_safe
892    }
893
894    fn required_privilege(&self) -> Privilege {
895        self.required_privilege
896    }
897
898    fn lock_intent(&self) -> LockIntent {
899        self.lock_intent
900    }
901
902    fn visible_collections(&self) -> Option<&HashSet<String>> {
903        self.visible_collections.as_ref()
904    }
905}
906
907/// Lightweight `ReadFrame` carrier used by AI command entry points
908/// (`SEARCH SIMILAR`, `SEARCH CONTEXT`, `ASK`).
909///
910/// Issue #119 calls this struct `EffectiveScope`. It bundles the
911/// `(tenant, identity, role, visible_collections, snapshot)` tuple so
912/// every AI runtime entry can pass *one* value to `AuthorizedSearch`
913/// instead of re-reading thread-locals at every call site.
914///
915/// Built via `RedDBRuntime::ai_scope()` which sources tenant + identity
916/// from the per-statement thread-locals (identical to how
917/// `StatementExecutionFrame::build` derives them) and resolves
918/// `visible_collections` via the `AuthStore` cache.
919pub struct EffectiveScope {
920    pub(crate) captured_snapshot: Option<SnapshotContext>,
921    pub(crate) tenant: Option<String>,
922    pub(crate) identity: Option<(String, Role)>,
923    pub(crate) snapshot: Snapshot,
924    pub(crate) visible_collections: Option<HashSet<String>>,
925}
926
927impl EffectiveScope {
928    /// Capability check used by the AI runtime (`runtime/ai/ner.rs`)
929    /// to gate LLM-backed NER calls behind `ai:ner:read`.
930    ///
931    /// Placeholder for now: always returns `false`. The auth engine's
932    /// capability matrix is future work; until it lands, every routed
933    /// LLM-NER call denies at the gate and `extract_tokens_routed`'s
934    /// heuristic fallback fires (see `ask_pipeline::extract_tokens_routed`).
935    /// Documented in code so the wire-up is a one-line change once
936    /// the auth engine learns capabilities.
937    pub fn has_capability(&self, _capability: &str) -> bool {
938        false
939    }
940}
941
942impl ReadFrame for EffectiveScope {
943    fn snapshot_context(&self, runtime: &RedDBRuntime) -> SnapshotContext {
944        self.captured_snapshot
945            .clone()
946            .unwrap_or_else(|| SnapshotContext {
947                snapshot: self.snapshot.clone(),
948                manager: runtime.inner.transaction_state.snapshot_manager(),
949                own_xids: HashSet::new(),
950                requires_index_fallback: true,
951                serializable_reader: None,
952            })
953    }
954
955    fn effective_scope(&self) -> Option<&str> {
956        self.tenant.as_deref()
957    }
958    fn identity(&self) -> Option<(&str, Role)> {
959        self.identity.as_ref().map(|(u, r)| (u.as_str(), *r))
960    }
961    fn snapshot(&self) -> &Snapshot {
962        &self.snapshot
963    }
964    fn as_of_floor(&self) -> Option<Xid> {
965        None
966    }
967    fn cache_key(&self) -> &str {
968        ""
969    }
970    fn should_cache_result(&self) -> bool {
971        false
972    }
973    fn required_privilege(&self) -> Privilege {
974        Privilege::Read
975    }
976    fn lock_intent(&self) -> LockIntent {
977        LockIntent::Shared
978    }
979    fn visible_collections(&self) -> Option<&HashSet<String>> {
980        self.visible_collections.as_ref()
981    }
982}
983
984fn own_transaction_xids(
985    ctx: Option<&crate::storage::transaction::snapshot::TxnContext>,
986) -> HashSet<Xid> {
987    let mut set = HashSet::new();
988    if let Some(ctx) = ctx {
989        set.insert(ctx.xid);
990        for (_, sub) in &ctx.savepoints {
991            set.insert(*sub);
992        }
993        for sub in &ctx.released_sub_xids {
994            set.insert(*sub);
995        }
996    }
997    set
998}
999
1000impl RedDBRuntime {
1001    /// Build the AI command `EffectiveScope` from the current
1002    /// statement thread-locals + auth store.
1003    ///
1004    /// Returns `None` for embedded callers (no auth store, no
1005    /// identity) — `AuthorizedSearch` treats `None` as deny-default.
1006    pub(crate) fn ai_scope(&self) -> EffectiveScope {
1007        let tenant = super::impl_core::current_tenant();
1008        let identity = super::impl_core::current_auth_identity();
1009        let captured_snapshot = super::execution_context::capture_current_snapshot();
1010        let snapshot = captured_snapshot.as_ref().map_or_else(
1011            || self.current_snapshot(),
1012            |context| context.snapshot.clone(),
1013        );
1014        let visible_collections = match (self.inner.auth_store.read().clone(), identity.as_ref()) {
1015            (Some(store), Some((principal, role))) => {
1016                let collections = self.inner.db.store().list_collections();
1017                Some(store.visible_collections_for_scope(
1018                    tenant.as_deref(),
1019                    *role,
1020                    principal,
1021                    &collections,
1022                ))
1023            }
1024            _ => None,
1025        };
1026        EffectiveScope {
1027            captured_snapshot,
1028            tenant,
1029            identity,
1030            snapshot,
1031            visible_collections,
1032        }
1033    }
1034}
1035
1036/// Test fixtures for callers that need to drive `ReadFrame` without
1037/// booting a runtime. Lives behind `cfg(test)` and `pub(crate)` so it
1038/// only leaks across module boundaries inside the crate.
1039#[cfg(test)]
1040pub(crate) mod test_support {
1041    use super::{LockIntent, Privilege, ReadFrame};
1042    use crate::auth::Role;
1043    use crate::storage::transaction::snapshot::{Snapshot, Xid};
1044    use std::collections::HashSet;
1045
1046    /// A `ReadFrame` impl with hand-set fields. Used by
1047    /// `authorized_search` tests to assert the deny-default and
1048    /// scope-trim behaviour without going through frame construction.
1049    pub(crate) struct FakeReadFrame {
1050        pub tenant: Option<String>,
1051        pub identity: Option<(String, Role)>,
1052        pub snapshot: Snapshot,
1053        pub visible: Option<HashSet<String>>,
1054    }
1055
1056    impl FakeReadFrame {
1057        pub(crate) fn without_scope() -> Self {
1058            Self {
1059                tenant: None,
1060                identity: None,
1061                snapshot: Snapshot {
1062                    xid: 0,
1063                    in_progress: HashSet::new(),
1064                },
1065                visible: None,
1066            }
1067        }
1068
1069        pub(crate) fn with_visible(visible: HashSet<String>) -> Self {
1070            Self {
1071                tenant: Some("acme".to_string()),
1072                identity: Some(("alice".to_string(), Role::Read)),
1073                snapshot: Snapshot {
1074                    xid: 0,
1075                    in_progress: HashSet::new(),
1076                },
1077                visible: Some(visible),
1078            }
1079        }
1080    }
1081
1082    impl ReadFrame for FakeReadFrame {
1083        fn effective_scope(&self) -> Option<&str> {
1084            self.tenant.as_deref()
1085        }
1086        fn identity(&self) -> Option<(&str, Role)> {
1087            self.identity.as_ref().map(|(u, r)| (u.as_str(), *r))
1088        }
1089        fn snapshot(&self) -> &Snapshot {
1090            &self.snapshot
1091        }
1092        fn as_of_floor(&self) -> Option<Xid> {
1093            None
1094        }
1095        fn cache_key(&self) -> &str {
1096            ""
1097        }
1098        fn should_cache_result(&self) -> bool {
1099            false
1100        }
1101        fn required_privilege(&self) -> Privilege {
1102            Privilege::Read
1103        }
1104        fn lock_intent(&self) -> LockIntent {
1105            LockIntent::Shared
1106        }
1107        fn visible_collections(&self) -> Option<&HashSet<String>> {
1108            self.visible.as_ref()
1109        }
1110    }
1111}
1112
1113impl RedDBRuntime {
1114    /// Resolve the snapshot for the current statement, returning
1115    /// the snapshot itself and (when AS OF is in effect) the
1116    /// resolved xid floor. The floor is the same xid carried inside
1117    /// `Snapshot.xid` for AS OF reads — exposing it separately lets
1118    /// the `ReadFrame` Interface tell "live read" from "historical
1119    /// read" without inferring from `in_progress.is_empty()`.
1120    ///
1121    /// A live read nested inside an already-installed frame inherits that
1122    /// frame's snapshot instead of minting a fresh one — but only when it
1123    /// is genuinely *part of* that statement, which is exactly what
1124    /// [`StatementIdentity::Expr`] means. A CTE prelude, a
1125    /// materialized-view refresh, or an inline graph TVF is one statement
1126    /// and must observe one snapshot; re-minting under autocommit / Read
1127    /// Committed takes a new high-water mark, so the nodes and edges of a
1128    /// single graph TVF could otherwise be materialized under two
1129    /// different snapshots.
1130    ///
1131    /// A nested `Text` statement is a different thing entirely: a driver
1132    /// loop issuing statement after statement through `execute_query`.
1133    /// Those are sequential autocommit statements and each must see its
1134    /// predecessors' commits. Inheriting there froze the loop's view —
1135    /// `apply_batched` (`impl_migrations.rs`) drives `APPLY MIGRATION …
1136    /// BATCH N ROWS` by re-running the body with `LIMIT N` until fewer
1137    /// than `N` rows are affected, so a frozen snapshot re-selected the
1138    /// same rows forever and the migration never converged. Twenty-five
1139    /// rows at `BATCH 7` should finish in four iterations; it hung
1140    /// unbounded instead.
1141    ///
1142    /// `AS OF` still wins over both — it names its own snapshot explicitly.
1143    fn statement_snapshot(
1144        &self,
1145        query: &str,
1146        identity: StatementIdentity<'_>,
1147    ) -> RedDBResult<(Snapshot, Option<Xid>, SnapshotRetentionGuard)> {
1148        match peek_top_level_as_of_with_table(query) {
1149            Some((spec, Some(table))) => {
1150                if !table.starts_with("red_")
1151                    && !table.starts_with("red.")
1152                    && !self.vcs_is_versioned(&table)?
1153                {
1154                    return Err(RedDBError::InvalidConfig(format!(
1155                        "AS OF requires a versioned collection — \
1156                         `{table}` has not opted in. \
1157                         Call vcs.set_versioned(\"{table}\", true) first."
1158                    )));
1159                }
1160                let xid = self.vcs_resolve_as_of(spec)?;
1161                let (snapshot, retention) = self.snapshot_manager().retain_snapshot(Snapshot {
1162                    xid,
1163                    in_progress: HashSet::new(),
1164                });
1165                Ok((snapshot, Some(xid), retention))
1166            }
1167            Some((spec, None)) => {
1168                let xid = self.vcs_resolve_as_of(spec)?;
1169                let (snapshot, retention) = self.snapshot_manager().retain_snapshot(Snapshot {
1170                    xid,
1171                    in_progress: HashSet::new(),
1172                });
1173                Ok((snapshot, Some(xid), retention))
1174            }
1175            None => match (identity, capture_current_snapshot()) {
1176                (StatementIdentity::Expr(_), Some(outer)) => {
1177                    let (snapshot, retention) =
1178                        self.snapshot_manager().retain_snapshot(outer.snapshot);
1179                    Ok((snapshot, None, retention))
1180                }
1181                _ => {
1182                    let (snapshot, retention) = self
1183                        .inner
1184                        .transaction_state
1185                        .retained_current_snapshot(current_connection_id());
1186                    Ok((snapshot, None, retention))
1187                }
1188            },
1189        }
1190    }
1191
1192    fn result_cache_safe(&self, conn_id: u64) -> bool {
1193        let has_active_xids = self
1194            .inner
1195            .transaction_state
1196            .snapshot_manager()
1197            .oldest_active_xid()
1198            .is_some();
1199        let in_own_tx = self.inner.transaction_state.in_transaction(conn_id);
1200        !has_active_xids && !in_own_tx
1201    }
1202}
1203
1204/// Whether a result's `engine` tag is one of the graph-analytics TVF
1205/// executors (issue #802). Graph-collection (`louvain(g)`) and inline
1206/// (`louvain(nodes => …, edges => …)`) forms both produce deterministic
1207/// algorithm output that is cached regardless of row count.
1208fn is_graph_tvf_engine(engine: &str) -> bool {
1209    matches!(engine, "runtime-graph-tvf" | "runtime-graph-tvf-inline")
1210}
1211
1212fn result_cache_key(query: &str) -> String {
1213    let tenant = current_tenant().unwrap_or_default();
1214    let auth = current_auth_identity()
1215        .map(|(user, role)| format!("{}|{:?}", user, role))
1216        .unwrap_or_default();
1217    if tenant.is_empty() && auth.is_empty() {
1218        query.to_string()
1219    } else {
1220        format!("{query}\u{001e}{tenant}\u{001e}{auth}")
1221    }
1222}
1223
1224#[cfg(test)]
1225mod tests {
1226    use super::*;
1227    use crate::api::RedDBOptions;
1228    use crate::runtime::impl_core::{
1229        clear_current_auth_identity, clear_current_tenant, set_current_auth_identity,
1230        set_current_tenant,
1231    };
1232    use crate::runtime::RedDBRuntime;
1233
1234    fn fresh_runtime() -> RedDBRuntime {
1235        RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("in-memory runtime")
1236    }
1237
1238    enum HeldFrame {
1239        Ordinary,
1240        Nested,
1241        Historical,
1242    }
1243
1244    fn verify_frame_survives_vacuum(delete: bool, kind: HeldFrame) {
1245        use crate::runtime::mvcc::{clear_current_connection_id, set_current_connection_id};
1246
1247        reset_thread_locals();
1248        clear_current_connection_id();
1249        let runtime = fresh_runtime();
1250        let execute = |connection, sql: &str| {
1251            set_current_connection_id(connection);
1252            let result = runtime.execute_query(sql);
1253            clear_current_connection_id();
1254            result.expect("valid frame retention fixture statement")
1255        };
1256        execute(1, "CREATE TABLE frame_rows (id TEXT, n INTEGER)");
1257        execute(1, "INSERT INTO frame_rows (id, n) VALUES ('row', 1)");
1258        let historical_xid = runtime.current_snapshot().xid;
1259        if matches!(kind, HeldFrame::Historical) {
1260            runtime
1261                .vcs_set_versioned("frame_rows", true)
1262                .expect("enable historical reads");
1263        }
1264        execute(2, "BEGIN");
1265        let query = if matches!(kind, HeldFrame::Historical) {
1266            format!("SELECT id, n FROM frame_rows AS OF SNAPSHOT {historical_xid}")
1267        } else {
1268            "SELECT id, n FROM frame_rows".to_string()
1269        };
1270        let frame = StatementExecutionFrame::build(&runtime, StatementIdentity::Text(&query))
1271            .expect("frame captures its snapshot");
1272        let frame = if matches!(kind, HeldFrame::Nested) {
1273            let guards = frame.install(&runtime);
1274            let expr = QueryExpr::Table(reddb_rql::ast::TableQuery::new("frame_rows"));
1275            let nested = StatementExecutionFrame::build(&runtime, StatementIdentity::Expr(&expr))
1276                .expect("nested frame inherits the protected snapshot");
1277            drop(guards);
1278            drop(frame);
1279            nested
1280        } else {
1281            frame
1282        };
1283        // Pause after capture and before install/scan: GC must also protect
1284        // this gap, rather than starting retention only at TLS installation.
1285        execute(
1286            2,
1287            if delete {
1288                "DELETE FROM frame_rows WHERE id = 'row'"
1289            } else {
1290                "UPDATE frame_rows SET n = 2 WHERE id = 'row'"
1291            },
1292        );
1293        execute(2, "COMMIT");
1294        execute(1, "VACUUM frame_rows");
1295        {
1296            let _guards = frame.install(&runtime);
1297            let records = super::super::record_search::scan_runtime_table_source_records_limited(
1298                &runtime.db(),
1299                "frame_rows",
1300                None,
1301            )
1302            .expect("captured frame scan succeeds after vacuum");
1303            assert_eq!(
1304                records.len(),
1305                1,
1306                "vacuum reclaimed an active frame's visible row"
1307            );
1308            assert_eq!(
1309                records[0]
1310                    .get("n")
1311                    .expect("selected value exists")
1312                    .to_string(),
1313                "1"
1314            );
1315        }
1316        drop(frame);
1317        execute(1, "VACUUM frame_rows");
1318        let physical = runtime
1319            .db()
1320            .store()
1321            .get_collection("frame_rows")
1322            .expect("fixture collection exists")
1323            .query_all(|_| true)
1324            .len();
1325        assert_eq!(
1326            physical,
1327            usize::from(!delete),
1328            "completed frame leaked its retention pin"
1329        );
1330        clear_current_connection_id();
1331    }
1332
1333    #[test]
1334    fn autocommit_frame_retains_update_until_scan_completes() {
1335        verify_frame_survives_vacuum(false, HeldFrame::Ordinary);
1336    }
1337
1338    #[test]
1339    fn autocommit_frame_retains_delete_until_scan_completes() {
1340        verify_frame_survives_vacuum(true, HeldFrame::Ordinary);
1341    }
1342
1343    #[test]
1344    fn nested_frame_retains_history_after_parent_frame_drops() {
1345        verify_frame_survives_vacuum(false, HeldFrame::Nested);
1346    }
1347
1348    #[test]
1349    fn historical_frame_retains_history_until_scan_completes() {
1350        verify_frame_survives_vacuum(true, HeldFrame::Historical);
1351    }
1352
1353    /// Ensure thread-local state from a prior test can't leak into
1354    /// the next one — tests in the same binary share the thread.
1355    fn reset_thread_locals() {
1356        clear_current_tenant();
1357        clear_current_auth_identity();
1358    }
1359
1360    #[test]
1361    fn autocommit_select_takes_live_snapshot() {
1362        reset_thread_locals();
1363        let rt = fresh_runtime();
1364        let frame = StatementExecutionFrame::build(&rt, StatementIdentity::Text("SELECT 1"))
1365            .expect("frame builds for SELECT 1");
1366
1367        // The inclusive bound excludes the next unallocated writer xid.
1368        // A pristine manager therefore has a valid empty snapshot at zero.
1369        let f: &dyn ReadFrame = &frame;
1370        assert!(f.as_of_floor().is_none(), "live read has no AS OF floor");
1371        assert_eq!(f.snapshot().xid, rt.snapshot_manager().peek_next_xid() - 1);
1372        assert!(!f.snapshot().sees(rt.snapshot_manager().peek_next_xid(), 0));
1373    }
1374
1375    #[test]
1376    fn autocommit_snapshot_does_not_lose_rows_after_index_publication() {
1377        reset_thread_locals();
1378        let rt = fresh_runtime();
1379        rt.execute_query("CREATE TABLE frame_index_race (id INT PRIMARY KEY, status TEXT)")
1380            .expect("create fixture");
1381        rt.execute_query("INSERT INTO frame_index_race (id, status) VALUES (1, 'old'), (2, 'old')")
1382            .expect("insert fixture");
1383        rt.execute_query("CREATE INDEX frame_status_hash ON frame_index_race (status) USING HASH")
1384            .expect("create index");
1385        let sql = "SELECT id FROM frame_index_race WHERE status = 'old'";
1386        let frame = StatementExecutionFrame::build(&rt, StatementIdentity::Text(sql))
1387            .expect("capture autocommit snapshot");
1388        rt.execute_query("UPDATE frame_index_race SET status = 'new' WHERE id = 1")
1389            .expect("publish changed index entry");
1390        let reddb_rql::ast::QueryExpr::Table(query) =
1391            reddb_rql::modes::parse_multi(sql).expect("parse")
1392        else {
1393            panic!("expected table query");
1394        };
1395        let _guards = frame.install(&rt);
1396        let records =
1397            super::super::query_exec::table::execute_runtime_canonical_table_query_indexed(
1398                &rt.db(),
1399                &query,
1400                Some(rt.index_store_ref()),
1401            )
1402            .expect("read captured snapshot");
1403        let mut ids = records
1404            .iter()
1405            .map(|record| record.get("id").expect("id").to_string())
1406            .collect::<Vec<_>>();
1407        ids.sort();
1408        assert_eq!(
1409            ids,
1410            ["1", "2"],
1411            "current index omitted a visible historical row"
1412        );
1413    }
1414
1415    #[test]
1416    fn captured_dml_snapshot_finds_rows_after_index_publication() {
1417        reset_thread_locals();
1418        let rt = fresh_runtime();
1419        rt.execute_query("CREATE TABLE frame_dml_race (id INT PRIMARY KEY, status TEXT)")
1420            .expect("create fixture");
1421        rt.execute_query("INSERT INTO frame_dml_race (id, status) VALUES (1, 'old'), (2, 'old')")
1422            .expect("insert fixture");
1423        rt.execute_query("CREATE INDEX frame_dml_status ON frame_dml_race (status) USING HASH")
1424            .expect("create index");
1425        let sql = "DELETE FROM frame_dml_race WHERE status = 'old'";
1426        let frame = StatementExecutionFrame::build(&rt, StatementIdentity::Text(sql))
1427            .expect("capture DML snapshot");
1428        rt.execute_query("UPDATE frame_dml_race SET status = 'new' WHERE id = 1")
1429            .expect("publish new indexed value");
1430        let reddb_rql::ast::QueryExpr::Table(query) =
1431            reddb_rql::modes::parse_multi("SELECT id FROM frame_dml_race WHERE status = 'old'")
1432                .expect("parse filter")
1433        else {
1434            panic!("expected table query")
1435        };
1436        let filter = reddb_rql::sql_lowering::effective_table_filter(&query).expect("filter");
1437        let _guards = frame.install(&rt);
1438        let ids = super::super::dml_target_scan::DmlTargetScan::new(
1439            &rt,
1440            "frame_dml_race",
1441            Some(&filter),
1442            None,
1443        )
1444        .find_target_ids()
1445        .expect("find DML targets");
1446        assert_eq!(
1447            ids.len(),
1448            2,
1449            "DML target scan must discover both snapshot-visible rows"
1450        );
1451    }
1452
1453    #[test]
1454    fn captured_snapshot_survives_indexed_update_and_delete_for_range_queries() {
1455        reset_thread_locals();
1456        let rt = fresh_runtime();
1457        rt.execute_query("CREATE TABLE frame_range_race (id INT PRIMARY KEY, score INT)")
1458            .expect("create fixture");
1459        rt.execute_query("INSERT INTO frame_range_race (id, score) VALUES (1, 10), (2, 20)")
1460            .expect("insert fixture");
1461        rt.execute_query("CREATE INDEX frame_score_range ON frame_range_race (score)")
1462            .expect("create index");
1463        let sql = "SELECT id FROM frame_range_race WHERE score >= 10 AND score <= 20 ORDER BY id";
1464        let frame = StatementExecutionFrame::build(&rt, StatementIdentity::Text(sql))
1465            .expect("capture read snapshot");
1466        rt.execute_query("UPDATE frame_range_race SET score = 99 WHERE id = 1")
1467            .expect("update row");
1468        rt.execute_query("DELETE FROM frame_range_race WHERE id = 2")
1469            .expect("delete row");
1470        let reddb_rql::ast::QueryExpr::Table(query) =
1471            reddb_rql::modes::parse_multi(sql).expect("parse")
1472        else {
1473            panic!("expected table query");
1474        };
1475        let _guards = frame.install(&rt);
1476        let records =
1477            super::super::query_exec::table::execute_runtime_canonical_table_query_indexed(
1478                &rt.db(),
1479                &query,
1480                Some(rt.index_store_ref()),
1481            )
1482            .expect("read captured snapshot");
1483        let ids = records
1484            .iter()
1485            .map(|record| record.get("id").expect("id").to_string())
1486            .collect::<Vec<_>>();
1487        assert_eq!(ids, ["1", "2"]);
1488    }
1489
1490    #[test]
1491    fn dml_target_scan_does_not_retry_inside_stored_function_budget() {
1492        use std::sync::atomic::{AtomicUsize, Ordering};
1493        use std::sync::Arc;
1494        reset_thread_locals();
1495        let rt = fresh_runtime();
1496        rt.execute_query("CREATE TABLE dml_budget_guard (id INT, status TEXT)")
1497            .expect("create fixture");
1498        rt.execute_query("INSERT INTO dml_budget_guard (id, status) VALUES (1, 'old')")
1499            .expect("insert fixture");
1500        rt.execute_query("CREATE INDEX dml_budget_status ON dml_budget_guard (status) USING HASH")
1501            .expect("create index");
1502        let frame = StatementExecutionFrame::build(
1503            &rt,
1504            StatementIdentity::Text("DELETE FROM dml_budget_guard WHERE status = 'old'"),
1505        )
1506        .expect("capture snapshot");
1507        let reddb_rql::ast::QueryExpr::Table(query) =
1508            reddb_rql::modes::parse_multi("SELECT id FROM dml_budget_guard WHERE status = 'old'")
1509                .expect("parse filter")
1510        else {
1511            panic!("expected table query")
1512        };
1513        let filter = reddb_rql::sql_lowering::effective_table_filter(&query).expect("filter");
1514        let calls = Arc::new(AtomicUsize::new(0));
1515        let observed = Arc::clone(&calls);
1516        *rt.index_store_ref().mutation_hook.lock() = Some(Arc::new(move |collection, phase| {
1517            if collection == "dml_budget_guard"
1518                && phase == super::super::index_store::MutationTestPhase::DmlIndexLookupStarted
1519            {
1520                observed.fetch_add(1, Ordering::SeqCst);
1521            }
1522        }));
1523        let _budget = super::super::function_budget::Scope::enter(1_000, 10_000)
1524            .expect("stored function budget");
1525        let _guards = frame.install(&rt);
1526        let ids = super::super::dml_target_scan::DmlTargetScan::new(
1527            &rt,
1528            "dml_budget_guard",
1529            Some(&filter),
1530            None,
1531        )
1532        .find_target_ids()
1533        .expect("find DML targets");
1534        assert_eq!(ids.len(), 1);
1535        assert_eq!(
1536            calls.load(Ordering::SeqCst),
1537            0,
1538            "bounded stored functions must not retry indexed discovery"
1539        );
1540        *rt.index_store_ref().mutation_hook.lock() = None;
1541    }
1542
1543    #[test]
1544    fn dml_index_lookup_retries_when_publication_races_target_selection() {
1545        use std::sync::{mpsc, Arc, Mutex};
1546        use std::time::Duration;
1547        reset_thread_locals();
1548        let rt = fresh_runtime();
1549        rt.execute_query("CREATE TABLE dml_lookup_race (id INT PRIMARY KEY, status TEXT)")
1550            .expect("create fixture");
1551        rt.execute_query("INSERT INTO dml_lookup_race (id, status) VALUES (1, 'old'), (2, 'old')")
1552            .expect("insert fixture");
1553        rt.execute_query("CREATE INDEX dml_lookup_status ON dml_lookup_race (status) USING HASH")
1554            .expect("create index");
1555        let frame = StatementExecutionFrame::build(
1556            &rt,
1557            StatementIdentity::Text("DELETE FROM dml_lookup_race WHERE status = 'old'"),
1558        )
1559        .expect("capture snapshot");
1560        let reddb_rql::ast::QueryExpr::Table(query) =
1561            reddb_rql::modes::parse_multi("SELECT id FROM dml_lookup_race WHERE status = 'old'")
1562                .expect("parse filter")
1563        else {
1564            panic!("expected table query")
1565        };
1566        let filter = reddb_rql::sql_lowering::effective_table_filter(&query).expect("filter");
1567        let (started_tx, started_rx) = mpsc::channel();
1568        let (published_tx, published_rx) = mpsc::channel();
1569        let published_rx = Mutex::new(published_rx);
1570        let first = std::sync::atomic::AtomicBool::new(true);
1571        *rt.index_store_ref().mutation_hook.lock() = Some(Arc::new(move |collection, phase| {
1572            if collection == "dml_lookup_race"
1573                && phase == super::super::index_store::MutationTestPhase::DmlIndexLookupStarted
1574                && first.swap(false, std::sync::atomic::Ordering::SeqCst)
1575            {
1576                started_tx.send(()).expect("notify writer");
1577                published_rx
1578                    .lock()
1579                    .unwrap()
1580                    .recv_timeout(Duration::from_secs(10))
1581                    .expect("writer published");
1582            }
1583        }));
1584        std::thread::scope(|scope| {
1585            let writer_rt = &rt;
1586            let writer = scope.spawn(move || {
1587                started_rx
1588                    .recv_timeout(Duration::from_secs(10))
1589                    .expect("lookup started");
1590                writer_rt
1591                    .execute_query("UPDATE dml_lookup_race SET status = 'new' WHERE id = 1")
1592                    .expect("publish update");
1593                published_tx.send(()).expect("release lookup");
1594            });
1595            let limits = super::super::resource_limits::ResourceLimits {
1596                max_query_duration: Some(Duration::from_secs(30)),
1597                ..Default::default()
1598            };
1599            let slots = std::sync::atomic::AtomicU64::new(0);
1600            let _budget = super::super::query_budget::Scope::enter(&limits, &slots)
1601                .expect("query deadline scope");
1602            let _guards = frame.install(&rt);
1603            let ids = super::super::dml_target_scan::DmlTargetScan::new(
1604                &rt,
1605                "dml_lookup_race",
1606                Some(&filter),
1607                None,
1608            )
1609            .find_target_ids()
1610            .expect("find DML targets");
1611            writer.join().expect("writer thread");
1612            assert_eq!(
1613                ids.len(),
1614                2,
1615                "racing publication must not omit a snapshot-visible row"
1616            );
1617        });
1618        *rt.index_store_ref().mutation_hook.lock() = None;
1619    }
1620
1621    #[test]
1622    fn replica_replay_preserves_snapshots_across_insert_update_and_delete() {
1623        use crate::replication::cdc::{change_record_from_entity, ChangeOperation};
1624        use crate::replication::logical::{ApplyMode, LogicalChangeApplier};
1625        reset_thread_locals();
1626        let source = fresh_runtime();
1627        let replica = fresh_runtime();
1628        for rt in [&source, &replica] {
1629            rt.execute_query("CREATE TABLE replica_snapshot (id INT, status TEXT)")
1630                .expect("schema");
1631        }
1632        replica
1633            .execute_query(
1634                "CREATE INDEX replica_snapshot_status ON replica_snapshot (status) USING HASH",
1635            )
1636            .expect("index");
1637        let sql = "SELECT id FROM replica_snapshot WHERE status = 'old'";
1638        let capture = || {
1639            StatementExecutionFrame::build(&replica, StatementIdentity::Text(sql)).expect("capture")
1640        };
1641        let read = |frame: &StatementExecutionFrame| {
1642            let reddb_rql::ast::QueryExpr::Table(query) =
1643                reddb_rql::modes::parse_multi(sql).expect("parse")
1644            else {
1645                panic!("table")
1646            };
1647            let _guards = frame.install(&replica);
1648            super::super::query_exec::table::execute_runtime_canonical_table_query_indexed(
1649                &replica.db(),
1650                &query,
1651                Some(replica.index_store_ref()),
1652            )
1653            .expect("snapshot read")
1654            .len()
1655        };
1656        let empty = capture();
1657        source
1658            .execute_query("INSERT INTO replica_snapshot (id, status) VALUES (1, 'old')")
1659            .expect("insert");
1660        let applier = LogicalChangeApplier::new(0);
1661        let replay = |lsn, op| {
1662            let entity = source
1663                .db()
1664                .store()
1665                .get_collection("replica_snapshot")
1666                .unwrap()
1667                .query_all(|entity| entity.xmax == 0)
1668                .pop()
1669                .unwrap();
1670            applier
1671                .apply(
1672                    &replica.db(),
1673                    &change_record_from_entity(
1674                        lsn,
1675                        1,
1676                        op,
1677                        "replica_snapshot",
1678                        "table",
1679                        &entity,
1680                        12,
1681                        None,
1682                    ),
1683                    ApplyMode::Replica,
1684                )
1685                .expect("replay");
1686        };
1687        replay(1, ChangeOperation::Insert);
1688        assert_eq!(
1689            read(&empty),
1690            0,
1691            "replay must not backdate an insert into an earlier snapshot"
1692        );
1693        let inserted = capture();
1694        source
1695            .execute_query("UPDATE replica_snapshot SET status = 'new' WHERE id = 1")
1696            .expect("update");
1697        replay(2, ChangeOperation::Update);
1698        assert_eq!(read(&inserted), 1, "old version remains visible");
1699        assert_eq!(read(&capture()), 0, "fresh snapshot uses the updated index");
1700        // A snapshot of all rows must retain the deleted version as well.
1701        let all_sql = "SELECT id FROM replica_snapshot";
1702        let before_delete =
1703            StatementExecutionFrame::build(&replica, StatementIdentity::Text(all_sql)).unwrap();
1704        replay(3, ChangeOperation::Delete);
1705        let reddb_rql::ast::QueryExpr::Table(query) =
1706            reddb_rql::modes::parse_multi(all_sql).unwrap()
1707        else {
1708            panic!("table")
1709        };
1710        {
1711            let _guards = before_delete.install(&replica);
1712            assert_eq!(
1713                super::super::query_exec::table::execute_runtime_canonical_table_query_indexed(
1714                    &replica.db(),
1715                    &query,
1716                    Some(replica.index_store_ref())
1717                )
1718                .unwrap()
1719                .len(),
1720                1
1721            );
1722        }
1723        assert_eq!(
1724            replica.execute_query(all_sql).unwrap().result.records.len(),
1725            0
1726        );
1727    }
1728
1729    #[test]
1730    fn autocommit_index_reads_keep_old_rows_while_another_transaction_is_open() {
1731        use crate::runtime::mvcc::{clear_current_connection_id, set_current_connection_id};
1732        reset_thread_locals();
1733        let rt = fresh_runtime();
1734        let execute = |connection, sql: &str| {
1735            set_current_connection_id(connection);
1736            let result = rt.execute_query(sql);
1737            clear_current_connection_id();
1738            result.expect("statement")
1739        };
1740        execute(1, "CREATE TABLE active_writer_rows (id INT, status TEXT)");
1741        execute(
1742            1,
1743            "INSERT INTO active_writer_rows (id, status) VALUES (1, 'old')",
1744        );
1745        execute(
1746            1,
1747            "CREATE INDEX active_writer_status ON active_writer_rows (status) USING HASH",
1748        );
1749        execute(2, "BEGIN");
1750        execute(
1751            2,
1752            "UPDATE active_writer_rows SET status = 'new' WHERE id = 1",
1753        );
1754        assert_eq!(
1755            execute(1, "SELECT id FROM active_writer_rows WHERE status = 'old'")
1756                .result
1757                .records
1758                .len(),
1759            1
1760        );
1761        assert_eq!(
1762            execute(1, "SELECT id FROM active_writer_rows WHERE status = 'new'")
1763                .result
1764                .records
1765                .len(),
1766            0
1767        );
1768        execute(2, "ROLLBACK");
1769        assert_eq!(
1770            execute(1, "SELECT id FROM active_writer_rows WHERE status = 'old'")
1771                .result
1772                .records
1773                .len(),
1774            1
1775        );
1776    }
1777
1778    #[test]
1779    fn frame_captures_identity_and_scope() {
1780        reset_thread_locals();
1781        set_current_tenant("acme".to_string());
1782        set_current_auth_identity("alice".to_string(), Role::Write);
1783
1784        let rt = fresh_runtime();
1785        let frame = StatementExecutionFrame::build(&rt, StatementIdentity::Text("SELECT 1"))
1786            .expect("frame builds");
1787        let f: &dyn ReadFrame = &frame;
1788
1789        assert_eq!(f.effective_scope(), Some("acme"));
1790        let id = f.identity().expect("identity captured");
1791        assert_eq!(id.0, "alice");
1792        assert!(matches!(id.1, Role::Write));
1793
1794        // Cache key mixes scope + identity so two callers under
1795        // different tenants never share a cache slot.
1796        assert!(
1797            f.cache_key().contains("acme") && f.cache_key().contains("alice"),
1798            "cache key folds in scope + identity, got {:?}",
1799            f.cache_key()
1800        );
1801
1802        reset_thread_locals();
1803    }
1804
1805    #[test]
1806    fn as_of_rejects_non_versioned_user_collection() {
1807        reset_thread_locals();
1808        let rt = fresh_runtime();
1809
1810        // `not_versioned` is a plain user collection — the frame
1811        // builder must reject AS OF until the caller opts in via
1812        // `vcs.set_versioned`.
1813        let err = match StatementExecutionFrame::build(
1814            &rt,
1815            StatementIdentity::Text("SELECT * FROM not_versioned AS OF COMMIT 'deadbeef'"),
1816        ) {
1817            Err(e) => e,
1818            Ok(_) => panic!("AS OF on non-versioned user collection rejected"),
1819        };
1820
1821        let msg = format!("{err}");
1822        assert!(
1823            msg.contains("AS OF requires a versioned collection"),
1824            "expected AS OF rejection, got: {msg}"
1825        );
1826    }
1827
1828    /// End-to-end proof that the SELECT path consumes a `ReadFrame`.
1829    ///
1830    /// Sets a tenant + identity via the public thread-local API the
1831    /// runtime uses for ambient scope, drives a real `SELECT` through
1832    /// `execute_query`, then inspects the result cache that the SELECT
1833    /// path populates via `frame.cache_key()`. The key only carries
1834    /// the tenant + identity *because* it was built through the frame —
1835    /// reverting the wiring to inline `current_tenant()` /
1836    /// `current_auth_identity()` reads would still pass this test, but
1837    /// dropping the frame entirely (so the SELECT path stopped touching
1838    /// `cache_key`) would break it.
1839    #[test]
1840    fn select_path_routes_through_frame_cache_key() {
1841        reset_thread_locals();
1842        set_current_tenant("acme".to_string());
1843        set_current_auth_identity("alice".to_string(), Role::Read);
1844
1845        let rt = fresh_runtime();
1846        let result = rt
1847            .execute_query("SELECT 1")
1848            .expect("SELECT 1 executes under tenant=acme/identity=alice");
1849        assert_eq!(result.statement_type, "select");
1850
1851        // The textual SELECT path builds a frame and
1852        // writes its result through `frame.cache_key()`. That key folds
1853        // tenant + identity in via `result_cache_key`, so finding "acme"
1854        // and "alice" inside any cached key proves the frame was the
1855        // seam used.
1856        let cache = rt.inner.result_cache.read();
1857        let any_keyed_with_scope = cache
1858            .0
1859            .keys()
1860            .any(|k| k.contains("acme") && k.contains("alice"));
1861        assert!(
1862            any_keyed_with_scope,
1863            "expected at least one result-cache key carrying tenant+identity, \
1864             got keys: {:?}",
1865            cache.0.keys().collect::<Vec<_>>()
1866        );
1867
1868        reset_thread_locals();
1869    }
1870
1871    /// A SELECT that calls a volatile builtin (here:
1872    /// `pg_advisory_unlock`, the volatile token the runtime currently
1873    /// recognises in `query_has_volatile_builtin`) must NOT populate
1874    /// the result cache. Any caller hitting the cache after this would
1875    /// see a stale answer for an inherently-volatile query, so the
1876    /// SELECT path gates writes through `frame.should_cache_result()`.
1877    ///
1878    /// Deletion test: removing `ReadFrame::should_cache_result`, or
1879    /// reverting the SELECT path to skip its safety gate, would let
1880    /// the result cache silently absorb this statement and break the
1881    /// assertion below.
1882    #[test]
1883    fn volatile_select_does_not_populate_result_cache() {
1884        reset_thread_locals();
1885        let rt = fresh_runtime();
1886
1887        // Frame-level invariant: the volatile-builtin signal collapses
1888        // `should_cache_result` to false even for an autocommit /
1889        // out-of-tx connection.
1890        let frame = StatementExecutionFrame::build(
1891            &rt,
1892            StatementIdentity::Text("SELECT pg_advisory_unlock(1)"),
1893        )
1894        .expect("frame");
1895        let f: &dyn ReadFrame = &frame;
1896        assert!(
1897            !f.should_cache_result(),
1898            "volatile builtin must disable result-cache safety"
1899        );
1900
1901        // End-to-end: drive the volatile SELECT through `execute_query`
1902        // and confirm no entry was stamped under its cache key. Other
1903        // entries from prior tests sharing the binary may exist, so we
1904        // assert specifically on this query's key.
1905        let _ = rt
1906            .execute_query("SELECT pg_advisory_unlock(1)")
1907            .expect("volatile SELECT executes");
1908        let cache = rt.inner.result_cache.read();
1909        let key = result_cache_key("SELECT pg_advisory_unlock(1)");
1910        assert!(
1911            !cache.0.contains_key(&key),
1912            "volatile SELECT must not populate result cache, found key {key:?} in {:?}",
1913            cache.0.keys().collect::<Vec<_>>()
1914        );
1915
1916        reset_thread_locals();
1917    }
1918
1919    #[test]
1920    fn blob_cache_backend_populates_blob_path_without_legacy_write() {
1921        reset_thread_locals();
1922        let rt = fresh_runtime();
1923        rt.inner
1924            .db
1925            .store()
1926            .set_config_tree("runtime.result_cache.backend", &crate::json!("blob_cache"));
1927
1928        let result = rt.execute_query("SELECT 1").expect("SELECT 1 executes");
1929        assert_eq!(result.statement_type, "select");
1930
1931        let key = result_cache_key("SELECT 1");
1932        assert!(
1933            rt.inner
1934                .result_blob_cache
1935                .get("runtime.result_cache", &key)
1936                .is_some(),
1937            "blob backend should stamp the Blob Cache path"
1938        );
1939        assert!(rt.inner.result_blob_entries.read().0.contains_key(&key));
1940        assert!(
1941            !rt.inner.result_cache.read().0.contains_key(&key),
1942            "blob backend should not write the legacy map"
1943        );
1944    }
1945
1946    #[test]
1947    fn blob_cache_backend_keeps_volatile_select_out_of_blob_path() {
1948        reset_thread_locals();
1949        let rt = fresh_runtime();
1950        rt.inner
1951            .db
1952            .store()
1953            .set_config_tree("runtime.result_cache.backend", &crate::json!("blob_cache"));
1954
1955        let _ = rt
1956            .execute_query("SELECT pg_advisory_unlock(1)")
1957            .expect("volatile SELECT executes");
1958        let key = result_cache_key("SELECT pg_advisory_unlock(1)");
1959        assert!(
1960            rt.inner
1961                .result_blob_cache
1962                .get("runtime.result_cache", &key)
1963                .is_none(),
1964            "volatile SELECT must not populate blob result cache"
1965        );
1966        assert!(!rt.inner.result_blob_entries.read().0.contains_key(&key));
1967    }
1968
1969    #[test]
1970    fn shadow_backend_dual_writes_and_reports_no_divergence_on_equal_results() {
1971        reset_thread_locals();
1972        let rt = fresh_runtime();
1973        rt.inner
1974            .db
1975            .store()
1976            .set_config_tree("runtime.result_cache.backend", &crate::json!("shadow"));
1977
1978        let first = rt.execute_query("SELECT 1").expect("first SELECT");
1979        let second = rt.execute_query("SELECT 1").expect("cached SELECT");
1980        assert_eq!(first.result.len(), second.result.len());
1981
1982        let key = result_cache_key("SELECT 1");
1983        assert!(rt.inner.result_cache.read().0.contains_key(&key));
1984        assert!(rt.inner.result_blob_entries.read().0.contains_key(&key));
1985        assert_eq!(rt.result_cache_shadow_divergences(), 0);
1986        assert_eq!(
1987            crate::runtime::METRIC_CACHE_SHADOW_DIVERGENCE_TOTAL,
1988            "cache_shadow_divergence_total"
1989        );
1990    }
1991
1992    #[test]
1993    fn as_of_on_red_collection_records_floor() {
1994        reset_thread_locals();
1995        let rt = fresh_runtime();
1996
1997        // `red_*` collections always allow AS OF. The frame should
1998        // resolve to a concrete xid and surface it via the Interface.
1999        let frame = StatementExecutionFrame::build(
2000            &rt,
2001            StatementIdentity::Text("SELECT * FROM red_commits AS OF SNAPSHOT 1"),
2002        )
2003        .expect("AS OF SNAPSHOT 1 on red_commits resolves");
2004
2005        let f: &dyn ReadFrame = &frame;
2006        assert_eq!(
2007            f.as_of_floor(),
2008            Some(1),
2009            "AS OF SNAPSHOT 1 records xid=1 as the floor"
2010        );
2011        assert_eq!(f.snapshot().xid, 1);
2012        assert!(
2013            f.snapshot().in_progress.is_empty(),
2014            "historical reads have no in-progress set"
2015        );
2016    }
2017
2018    /// The frame classifies common SQL prefixes into the coarse
2019    /// `Privilege` / `LockIntent` buckets at build time. This test
2020    /// pins the mapping so a regression that silently re-routes
2021    /// (e.g. INSERT classified as Read) surfaces here, not at a
2022    /// downstream privilege gate.
2023    #[test]
2024    fn frame_classifies_privilege_and_lock_intent_from_prefix() {
2025        reset_thread_locals();
2026        let rt = fresh_runtime();
2027
2028        let cases = [
2029            ("SELECT 1", Privilege::Read, LockIntent::Shared),
2030            ("LIST KV settings", Privilege::Read, LockIntent::Shared),
2031            (
2032                "KV GET settings.feature",
2033                Privilege::Read,
2034                LockIntent::Shared,
2035            ),
2036            ("VAULT LIST secrets", Privilege::Read, LockIntent::Shared),
2037            (
2038                "INSERT INTO t (id) VALUES (1)",
2039                Privilege::Write,
2040                LockIntent::Exclusive,
2041            ),
2042            (
2043                "KV PUT settings.feature = 'on'",
2044                Privilege::Write,
2045                LockIntent::Exclusive,
2046            ),
2047            (
2048                "VAULT PUT secrets.api = 'x'",
2049                Privilege::Write,
2050                LockIntent::Exclusive,
2051            ),
2052            (
2053                "UPDATE t SET x = 1 WHERE id = 1",
2054                Privilege::Write,
2055                LockIntent::Exclusive,
2056            ),
2057            (
2058                "DELETE FROM t WHERE id = 1",
2059                Privilege::Write,
2060                LockIntent::Exclusive,
2061            ),
2062            (
2063                "CREATE TABLE foo (id INT)",
2064                Privilege::Write,
2065                LockIntent::Exclusive,
2066            ),
2067            ("BEGIN", Privilege::None, LockIntent::None),
2068            ("COMMIT", Privilege::None, LockIntent::None),
2069            ("SET timezone = 'UTC'", Privilege::None, LockIntent::None),
2070        ];
2071
2072        for (q, want_priv, want_lock) in cases {
2073            let frame = StatementExecutionFrame::build(&rt, StatementIdentity::Text(q))
2074                .unwrap_or_else(|e| panic!("frame builds for {q:?}: {e}"));
2075            let f: &dyn ReadFrame = &frame;
2076            assert_eq!(f.required_privilege(), want_priv, "privilege for {q:?}");
2077            assert_eq!(f.lock_intent(), want_lock, "lock intent for {q:?}");
2078        }
2079    }
2080
2081    /// Deletion-test for `ReadFrame::required_privilege`: a SELECT
2082    /// driven through `execute_query` under an identity whose role
2083    /// doesn't satisfy the frame's coarse `Read` privilege gets
2084    /// denied with the frame's signal.
2085    ///
2086    /// We test the gate by classifying an INSERT (which the frame
2087    /// reports as `Privilege::Write`) under `Role::Read` — the only
2088    /// pair the legacy fallback would also reject, but here the
2089    /// rejection comes through `frame.check_query_privilege` BEFORE
2090    /// the parsed-expression walker runs. Removing
2091    /// `required_privilege` (or the `is_satisfied_by` consult inside
2092    /// `check_query_privilege`) would force the deny path back to the
2093    /// inline `RedDBRuntime::check_query_privilege` walker — but the
2094    /// auth_store gate up there is bypassed when no auth_store is
2095    /// wired (embedded test mode), so this test would FLIP from
2096    /// denied to permitted and break the assertion below.
2097    #[test]
2098    fn insert_under_read_role_denied_via_frame_privilege() {
2099        reset_thread_locals();
2100        set_current_auth_identity("alice".to_string(), Role::Read);
2101
2102        let rt = fresh_runtime();
2103        // Bypass parser by reaching into the frame directly: the
2104        // frame derives privilege from the SQL prefix without
2105        // needing an auth_store wired up. Driving end-to-end via
2106        // `execute_query` would also reject (no table `t`), but for
2107        // a different reason — we want to pin the privilege seam.
2108        let frame = StatementExecutionFrame::build(
2109            &rt,
2110            StatementIdentity::Text("INSERT INTO t (id) VALUES (1)"),
2111        )
2112        .expect("frame builds for INSERT");
2113        let f: &dyn ReadFrame = &frame;
2114        assert_eq!(
2115            f.required_privilege(),
2116            Privilege::Write,
2117            "INSERT classified as Write"
2118        );
2119        let id = f.identity().expect("identity captured");
2120        assert!(
2121            !f.required_privilege().is_satisfied_by(id.1),
2122            "Role::Read does not satisfy Privilege::Write — frame must deny"
2123        );
2124
2125        // End-to-end: the frame's `check_query_privilege` sees the
2126        // (Read role, Write privilege) mismatch and denies before
2127        // dispatch. We drive a synthetic `QueryExpr::Table` because
2128        // the SELECT/INSERT parser would happen to also fail, and we
2129        // want the failure to come from the privilege seam.
2130        use reddb_rql::ast::{QueryExpr, TableQuery};
2131        let expr = QueryExpr::Table(TableQuery::new("t"));
2132        let err = frame
2133            .check_query_privilege(&rt, &expr)
2134            .expect_err("denied via frame's coarse privilege gate");
2135        let msg = format!("{err}");
2136        assert!(
2137            msg.contains("permission denied") && msg.contains("Write"),
2138            "expected frame-level Write deny, got: {msg}"
2139        );
2140
2141        reset_thread_locals();
2142    }
2143
2144    /// End-to-end proof that the frame-owned row-buffer arena (#885) is
2145    /// wired into the SELECT path and produces observable results
2146    /// byte-identical to the per-request-allocation baseline.
2147    ///
2148    /// A table with more rows than the streaming high-water mark
2149    /// (`DEFAULT_HIGH_WATER_MARK`) forces the `execute_runtime_table_query_in`
2150    /// path to assemble many chunks, each leasing/recycling the frame
2151    /// arena's single chunk buffer. Driving it through `execute_query`
2152    /// (which builds a `StatementExecutionFrame` and lends its arena)
2153    /// must return every inserted row, in order — exactly what the
2154    /// allocate-per-chunk path returned. A bug in the arena wiring
2155    /// (dropped rows, bled rows, mis-ordering) would surface here.
2156    #[test]
2157    fn large_select_through_frame_arena_returns_all_rows_in_order() {
2158        reset_thread_locals();
2159        let rt = fresh_runtime();
2160        rt.execute_query("CREATE TABLE big (id INT)")
2161            .expect("create table");
2162
2163        // > DEFAULT_HIGH_WATER_MARK (1024) rows so the streaming channel
2164        // spans multiple chunks and the arena buffer is reused.
2165        const N: usize = 2_500;
2166        for start in (0..N).step_by(250) {
2167            let end = (start + 250).min(N);
2168            let values = (start..end)
2169                .map(|i| format!("({i})"))
2170                .collect::<Vec<_>>()
2171                .join(", ");
2172            rt.execute_query(&format!("INSERT INTO big (id) VALUES {values}"))
2173                .unwrap_or_else(|err| panic!("insert rows {start}..{end}: {err:?}"));
2174        }
2175
2176        let result = rt
2177            .execute_query("SELECT id FROM big ORDER BY id")
2178            .expect("large SELECT executes through the frame arena path");
2179        assert_eq!(result.statement_type, "select");
2180        assert_eq!(
2181            result.result.records.len(),
2182            N,
2183            "every inserted row streams back through the arena-backed channel"
2184        );
2185        for (i, record) in result.result.records.iter().enumerate() {
2186            assert_eq!(
2187                record.get("id"),
2188                Some(&reddb_types::Value::Integer(i as i64)),
2189                "row {i} is byte-identical to the per-request-allocation baseline"
2190            );
2191        }
2192
2193        reset_thread_locals();
2194    }
2195
2196    /// Transport adapters may decode their wire-specific parameter value
2197    /// shapes, but SQL parsing/binding must stay behind the runtime's
2198    /// statement entrypoint. This pins the deeper seam introduced for
2199    /// parameterized query execution. HTTP, JSON-RPC, RedWire, and gRPC hand
2200    /// a `QueryRequest` to the Request module, as does PG wire through the
2201    /// shared prepared registry. All paths install a real
2202    /// `StatementExecutionFrame` before dispatch.
2203    ///
2204    /// The Request transports reach the runtime entrypoint one layer deeper:
2205    /// `QueryRequestExecutor` calls `execute_query_with_params` on their
2206    /// behalf. Their delegation target is the Request seam, so that is what
2207    /// is pinned here — the "no binding in the adapter" half is unchanged
2208    /// for all.
2209    #[test]
2210    fn parameterized_transport_adapters_delegate_binding_to_runtime() {
2211        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
2212        let adapters = [
2213            ("src/server/handlers_query.rs", "QueryRequestExecutor"),
2214            ("src/rpc_stdio.rs", "QueryRequestExecutor"),
2215            ("src/wire/redwire/session.rs", "QueryRequestExecutor"),
2216            ("src/wire/postgres/server.rs", "QueryRequestExecutor"),
2217            ("src/grpc.rs", "QueryRequestExecutor"),
2218        ];
2219
2220        for (relative, delegation) in adapters {
2221            let path = manifest_dir.join(relative);
2222            let text = std::fs::read_to_string(&path)
2223                .unwrap_or_else(|err| panic!("read {}: {err}", path.display()));
2224            assert!(
2225                text.contains(delegation),
2226                "{relative} should delegate parameterized query execution through {delegation}"
2227            );
2228            assert!(
2229                !text.contains("user_params::bind"),
2230                "{relative} must not bind SQL params in the transport adapter"
2231            );
2232        }
2233
2234        // The Request module is the only place RedWire's delegation may
2235        // bottom out: it must still reach the runtime entrypoint itself.
2236        let seam = std::fs::read_to_string(manifest_dir.join("src/runtime/query_request.rs"))
2237            .expect("read src/runtime/query_request.rs");
2238        assert!(
2239            seam.contains("execute_query_with_params"),
2240            "the Request module must execute text SQL through the runtime entrypoint"
2241        );
2242    }
2243
2244    /// Deletion-test for `ReadFrame::lock_intent`: a transaction
2245    /// control statement carries `LockIntent::None` and the
2246    /// `acquire_intent_locks` path returns `None` without consulting
2247    /// `intent_lock_modes_for`. Removing the method (or its consult
2248    /// site in `acquire_intent_locks`) would force the lock-mode
2249    /// helper to walk a fabricated parsed expression to reach the
2250    /// same conclusion — but the assertion that no guard is allocated
2251    /// for a `BEGIN` frame would still hold, so we additionally pin
2252    /// the classifier mapping above to make the deletion observable.
2253    #[test]
2254    fn control_statement_skips_intent_locks_via_frame() {
2255        reset_thread_locals();
2256        let rt = fresh_runtime();
2257
2258        let frame = StatementExecutionFrame::build(&rt, StatementIdentity::Text("BEGIN"))
2259            .expect("frame builds for BEGIN");
2260        let f: &dyn ReadFrame = &frame;
2261        assert_eq!(f.lock_intent(), LockIntent::None);
2262
2263        // Drive `acquire_intent_locks` against a fabricated SELECT
2264        // expression that WOULD normally yield `(IS, IS)`; the frame's
2265        // `lock_intent() == None` short-circuit must still suppress
2266        // the guard.
2267        use reddb_rql::ast::{QueryExpr, TableQuery};
2268        let expr = QueryExpr::Table(TableQuery::new("t"));
2269        let guard = frame
2270            .acquire_intent_locks(&rt, &expr)
2271            .expect("no lock is attempted");
2272        assert!(
2273            guard.is_none(),
2274            "BEGIN frame's lock_intent=None must short-circuit lock acquisition"
2275        );
2276    }
2277
2278    /// Nested sub-execution inside one statement (CTE prelude,
2279    /// materialized-view refresh, inline graph TVF) must read the
2280    /// enclosing statement's snapshot. Autocommit is the case that used
2281    /// to break: `current_snapshot()` mints a fresh high-water mark per
2282    /// call, so an inline graph TVF could materialize its nodes and its
2283    /// edges under two different snapshots within one statement.
2284    #[test]
2285    fn nested_frame_inherits_outer_statement_snapshot() {
2286        reset_thread_locals();
2287        let rt = fresh_runtime();
2288        rt.execute_query("CREATE TABLE nested_snap (id INT)")
2289            .expect("create table");
2290
2291        let outer = StatementExecutionFrame::build(
2292            &rt,
2293            StatementIdentity::Text("SELECT * FROM nested_snap"),
2294        )
2295        .expect("outer frame builds");
2296        let _outer_guards = outer.install(&rt);
2297
2298        // A write between the two builds moves the high-water mark, so a
2299        // re-minting nested frame would land on a different xid.
2300        rt.execute_query("INSERT INTO nested_snap (id) VALUES (1)")
2301            .expect("concurrent insert");
2302
2303        let expr = QueryExpr::Table(reddb_rql::ast::TableQuery::new("nested_snap"));
2304        let nested = StatementExecutionFrame::build(&rt, StatementIdentity::Expr(&expr))
2305            .expect("nested frame builds");
2306
2307        assert_eq!(
2308            ReadFrame::snapshot(&nested).xid,
2309            ReadFrame::snapshot(&outer).xid,
2310            "nested execution must inherit the outer statement's snapshot"
2311        );
2312    }
2313
2314    /// The other side of the same rule, and the one that matters more:
2315    /// a nested statement built from *text* is a statement in its own
2316    /// right, not part of the enclosing one, so it must mint a fresh
2317    /// snapshot and observe everything committed before it.
2318    ///
2319    /// `apply_batched` (`impl_migrations.rs`) is the load-bearing caller:
2320    /// it drives `APPLY MIGRATION … BATCH N ROWS` by re-running the body
2321    /// with `LIMIT N` through `execute_query` until fewer than `N` rows
2322    /// are affected. Inheriting the outer `APPLY MIGRATION` statement's
2323    /// snapshot froze that loop's view, so every iteration re-selected
2324    /// the same rows and the migration never converged — 25 rows at
2325    /// `BATCH 7` hung instead of finishing in four iterations.
2326    #[test]
2327    fn nested_text_statement_sees_commits_made_since_the_outer_frame() {
2328        reset_thread_locals();
2329        let rt = fresh_runtime();
2330        rt.execute_query("CREATE TABLE nested_text_snap (id INT)")
2331            .expect("create table");
2332
2333        let outer = StatementExecutionFrame::build(
2334            &rt,
2335            StatementIdentity::Text("SELECT * FROM nested_text_snap"),
2336        )
2337        .expect("outer frame builds");
2338        let _outer_guards = outer.install(&rt);
2339
2340        rt.execute_query("INSERT INTO nested_text_snap (id) VALUES (1)")
2341            .expect("concurrent insert");
2342
2343        let nested = StatementExecutionFrame::build(
2344            &rt,
2345            StatementIdentity::Text("SELECT * FROM nested_text_snap"),
2346        )
2347        .expect("nested frame builds");
2348
2349        assert_ne!(
2350            ReadFrame::snapshot(&nested).xid,
2351            ReadFrame::snapshot(&outer).xid,
2352            "a nested text statement must mint a fresh snapshot, not inherit \
2353             the enclosing statement's frozen view"
2354        );
2355    }
2356
2357    /// A frame with no statement text must not silently answer an
2358    /// `AS OF` read with live data. `TableQuery::as_of` is consumed
2359    /// nowhere in the runtime or scan path, so the only correct
2360    /// behaviours are "resolve it" (text path) or "refuse".
2361    #[test]
2362    fn expr_frame_rejects_as_of_instead_of_reading_live() {
2363        reset_thread_locals();
2364        let rt = fresh_runtime();
2365
2366        let mut table = reddb_rql::ast::TableQuery::new("red_commits");
2367        table.as_of = Some(reddb_rql::ast::AsOfClause::Snapshot(1));
2368        let expr = QueryExpr::Table(table);
2369
2370        let err = match StatementExecutionFrame::build(&rt, StatementIdentity::Expr(&expr)) {
2371            Err(err) => err,
2372            Ok(_) => panic!("AS OF without statement text must be refused, not read live"),
2373        };
2374        let msg = format!("{err}");
2375        assert!(
2376            msg.contains("AS OF cannot be resolved from a pre-parsed expression"),
2377            "expected a loud AS OF refusal, got: {msg}"
2378        );
2379    }
2380
2381    /// The expression path has no stable text key, so it must opt out of
2382    /// the result cache entirely. A kind label (`"table"`, `"insert"`)
2383    /// would key every statement of the same kind to one cache slot.
2384    #[test]
2385    fn expr_frame_opts_out_of_the_result_cache() {
2386        reset_thread_locals();
2387        let rt = fresh_runtime();
2388
2389        let expr = QueryExpr::Table(reddb_rql::ast::TableQuery::new("t"));
2390        let frame = StatementExecutionFrame::build(&rt, StatementIdentity::Expr(&expr))
2391            .expect("expr frame builds");
2392
2393        assert!(frame.cache_key().is_empty(), "expr frame has no cache key");
2394        assert!(
2395            !frame.can_read_result_cache(),
2396            "expr frame must never serve from the result cache"
2397        );
2398    }
2399}