Skip to main content

reddb_server/runtime/
statement_frame.rs

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