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