Skip to main content

powdb_query/executor/
mod.rs

1//! PowDB query executor.
2
3// Submodules that don't use macros defined in this file.
4mod compiled;
5mod eval;
6pub mod mem_budget;
7
8use crate::ast::*;
9use crate::canonicalize::canonicalize;
10use crate::plan::*;
11use crate::plan_cache::PlanCache;
12use crate::planner;
13use crate::result::{QueryError, QueryResult};
14use powdb_storage::catalog::Catalog;
15use powdb_storage::row::{decode_row, RowLayout, ROW_MAGIC, ROW_PREFIX_SIZE};
16use powdb_storage::types::*;
17use powdb_storage::view::ViewRegistry;
18pub use powdb_storage::wal::{WalDurabilityTicket, WalSyncMode};
19
20use std::io;
21use std::path::Path;
22use std::sync::{Arc, Mutex};
23use std::time::Instant;
24use tracing::{error, info, warn, Level};
25
26use self::compiled::*;
27use self::eval::*;
28
29/// Legacy sentinel string constant — kept for backward compatibility with
30/// any external code matching on the string representation. New code should
31/// match on `QueryError::ReadonlyNeedsWrite` directly.
32pub const READONLY_NEEDS_WRITE: &str = "__POWDB_READONLY_NEEDS_WRITE__";
33
34/// Return the byte offset where the row body starts.
35///
36/// v0.5 rows begin with the `PROW` magic/version prefix. Legacy rows start
37/// directly with the row body. Raw executor fast paths must add this base
38/// before reading body-relative bitmap/data offsets.
39#[inline]
40pub(crate) fn row_body_base(row: &[u8]) -> usize {
41    if row.len() >= ROW_PREFIX_SIZE && &row[0..4] == ROW_MAGIC {
42        ROW_PREFIX_SIZE
43    } else {
44        0
45    }
46}
47
48/// Query frontend dialect. PowQL remains the default/native dialect; SQL is
49/// an explicit frontend that lowers to the same AST before planning.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum QueryDialect {
52    PowQL,
53    Sql,
54}
55
56/// Plan cache capacity. Bench workloads fill ~15 slots; real apps will sit
57/// comfortably in 256. Lookup is O(1), collisions clear the cache (see
58/// `plan_cache::PlanCache::insert`).
59const PLAN_CACHE_CAPACITY: usize = 256;
60const SQL_RAW_CACHE_SALT: u64 = 0x7261_772d_7371_6c01;
61
62#[inline]
63fn sql_raw_cache_hash(hash: u64) -> u64 {
64    hash ^ SQL_RAW_CACHE_SALT
65}
66type WalArchiveHook =
67    Arc<dyn Fn(&Path, &[powdb_storage::wal::WalRecord]) -> io::Result<()> + Send + Sync>;
68
69/// Maximum number of rows a join may produce before the executor aborts.
70/// Prevents Cartesian-product blowups (e.g. `T cross join T` on 10K rows
71/// would produce 100M rows in memory without this cap).
72pub(super) const MAX_JOIN_ROWS: usize = 1_000_000;
73
74/// Maximum candidate pairs allowed for a fallback nested-loop join. This is
75/// grounded in the release benchmark's conservative 250 ms evaluation budget.
76pub(super) const MAX_NESTED_LOOP_PAIRS: usize = 6_400_000;
77
78/// Maximum number of rows that may be materialized for sorting.
79/// Queries that exceed this should add a LIMIT clause to narrow the input
80/// before sorting.
81pub(super) const MAX_SORT_ROWS: usize = 10_000_000;
82
83#[inline]
84pub(super) fn check_join_limit(row_count: usize) -> Result<(), QueryError> {
85    if row_count > MAX_JOIN_ROWS {
86        return Err(QueryError::JoinLimitExceeded);
87    }
88    Ok(())
89}
90
91// ─── Mission D11 Phase 1: scalar hot-loop helpers ─────────────────────────
92//
93// These macros expand into the scan body of `agg_single_col_fast` and sit
94// inside the `for_each_row_raw` closure. They exist to:
95//
96//   1. Split the loop on presence of a predicate *outside* the hot body,
97//      so the no-predicate path (agg_sum/agg_min/agg_max bench workloads)
98//      never pays the `Option<CompiledPredicate>` branch per row.
99//   2. Drop two bounds checks per row by reading the null bitmap byte
100//      and the 8-byte value via raw pointer casts.
101//
102// SAFETY (shared across every call site below):
103//
104//   - `$bmp_byte` is `col_idx / 8` where `col_idx < n_cols`, and the row body
105//     encoding stores `bitmap_size = n_cols.div_ceil(8)` bytes of bitmap
106//     starting at body offset 2. So `bmp_off = row_body_base(row) + 2 +
107//     $bmp_byte < row_len`, and `get_unchecked(bmp_off)` is inside the
108//     row slice.
109//   - `$off = 2 + bitmap_size + fixed_offsets[col_idx]` is body-relative for a fixed-size
110//     column. Every fixed-size column contributes `fixed_size(type_id)`
111//     bytes to the fixed region, so the row always has
112//     `[data_off .. data_off + 8]` available for any i64/f64 column, where
113//     `data_off = row_body_base(row) + $off` — enforced by the row encoder
114//     (`storage/src/row.rs`) and the schema invariant that a row with a
115//     given schema has enough body bytes for `2 + bitmap_size + fixed_region_size`.
116//   - Both macros are only invoked from `agg_single_col_fast`, which
117//     early-returns if the column isn't Int/Float (8-byte fixed) and
118//     early-returns if `fast.fixed_offsets[col_idx]` is `None`.
119macro_rules! agg_int_loop {
120    (
121        $self:expr, $table:expr, $pred:expr,
122        $bmp_byte:expr, $bmp_bit:expr, $off:expr,
123        |$v:ident : i64| $body:block
124    ) => {{
125        let bmp_byte = $bmp_byte;
126        let bmp_bit = $bmp_bit;
127        let off = $off;
128        if let Some(pred) = &$pred {
129            for_each_row_raw_cancellable(&$self.catalog, $table, |_rid, data| {
130                if !pred(data) {
131                    return;
132                }
133                let base = row_body_base(data);
134                let bmp_off = base + 2 + bmp_byte;
135                let data_off = base + off;
136                // Bounds guard: skip corrupt/truncated rows that are too
137                // short to contain the bitmap byte or the 8-byte value.
138                if bmp_off >= data.len() || data_off + 8 > data.len() {
139                    return;
140                }
141                // SAFETY: `bmp_off < data.len()` is checked above.
142                // The bitmap byte lives at body offset 2..2+bitmap_size in
143                // the row encoding, and bmp_byte = col_idx / 8 < bitmap_size.
144                // Corrupt rows are rejected by the bounds guard.
145                let bmp = unsafe { *data.get_unchecked(bmp_off) };
146                if (bmp >> bmp_bit) & 1 == 1 {
147                    return;
148                }
149                // SAFETY: `data_off + 8 <= data.len()` is checked above.
150                // `data_off = base + 2 + bitmap_size + fixed_offsets[col_idx]`
151                // points to an 8-byte i64 in the fixed-size region of the row.
152                // The pointer cast is valid because we read exactly 8
153                // bytes via from_le_bytes. Corrupt rows are rejected by
154                // the bounds guard.
155                let $v: i64 =
156                    unsafe { i64::from_le_bytes(*(data.as_ptr().add(data_off) as *const [u8; 8])) };
157                $body
158            })?;
159        } else {
160            for_each_row_raw_cancellable(&$self.catalog, $table, |_rid, data| {
161                let base = row_body_base(data);
162                let bmp_off = base + 2 + bmp_byte;
163                let data_off = base + off;
164                // Bounds guard: skip corrupt/truncated rows.
165                if bmp_off >= data.len() || data_off + 8 > data.len() {
166                    return;
167                }
168                // SAFETY: `bmp_off < data.len()` is checked above.
169                // See the predicate branch for the full invariant.
170                let bmp = unsafe { *data.get_unchecked(bmp_off) };
171                if (bmp >> bmp_bit) & 1 == 1 {
172                    return;
173                }
174                // SAFETY: `data_off + 8 <= data.len()` is checked above.
175                // See the predicate branch for the full invariant.
176                let $v: i64 =
177                    unsafe { i64::from_le_bytes(*(data.as_ptr().add(data_off) as *const [u8; 8])) };
178                $body
179            })?;
180        }
181    }};
182}
183
184macro_rules! agg_float_loop {
185    (
186        $self:expr, $table:expr, $pred:expr,
187        $bmp_byte:expr, $bmp_bit:expr, $off:expr,
188        |$v:ident : f64| $body:block
189    ) => {{
190        let bmp_byte = $bmp_byte;
191        let bmp_bit = $bmp_bit;
192        let off = $off;
193        if let Some(pred) = &$pred {
194            for_each_row_raw_cancellable(&$self.catalog, $table, |_rid, data| {
195                if !pred(data) {
196                    return;
197                }
198                let base = row_body_base(data);
199                let bmp_off = base + 2 + bmp_byte;
200                let data_off = base + off;
201                // Bounds guard: skip corrupt/truncated rows that are too
202                // short to contain the bitmap byte or the 8-byte value.
203                if bmp_off >= data.len() || data_off + 8 > data.len() {
204                    return;
205                }
206                // SAFETY: `bmp_off < data.len()` is checked above.
207                // The bitmap byte lives at body offset 2..2+bitmap_size in
208                // the row encoding, and bmp_byte = col_idx / 8 < bitmap_size.
209                // Corrupt rows are rejected by the bounds guard.
210                let bmp = unsafe { *data.get_unchecked(bmp_off) };
211                if (bmp >> bmp_bit) & 1 == 1 {
212                    return;
213                }
214                // SAFETY: `data_off + 8 <= data.len()` is checked above.
215                // `data_off = base + 2 + bitmap_size + fixed_offsets[col_idx]`
216                // points to an 8-byte f64 in the fixed-size region of the row.
217                // The pointer cast is valid because we read exactly 8
218                // bytes via from_le_bytes. Corrupt rows are rejected by
219                // the bounds guard.
220                let $v: f64 =
221                    unsafe { f64::from_le_bytes(*(data.as_ptr().add(data_off) as *const [u8; 8])) };
222                $body
223            })?;
224        } else {
225            for_each_row_raw_cancellable(&$self.catalog, $table, |_rid, data| {
226                let base = row_body_base(data);
227                let bmp_off = base + 2 + bmp_byte;
228                let data_off = base + off;
229                // Bounds guard: skip corrupt/truncated rows.
230                if bmp_off >= data.len() || data_off + 8 > data.len() {
231                    return;
232                }
233                // SAFETY: `bmp_off < data.len()` is checked above.
234                // See the predicate branch for the full invariant.
235                let bmp = unsafe { *data.get_unchecked(bmp_off) };
236                if (bmp >> bmp_bit) & 1 == 1 {
237                    return;
238                }
239                // SAFETY: `data_off + 8 <= data.len()` is checked above.
240                // See the predicate branch for the full invariant.
241                let $v: f64 =
242                    unsafe { f64::from_le_bytes(*(data.as_ptr().add(data_off) as *const [u8; 8])) };
243                $body
244            })?;
245        }
246    }};
247}
248
249// Submodules that use the macros above — must be declared after macro_rules!.
250mod plan_exec;
251mod prepared;
252
253#[cfg(test)]
254mod tests;
255
256// Re-exports for the public API
257pub use self::prepared::PreparedQuery;
258
259use self::plan_exec::{
260    aggregate_rows, aggregate_rows_with_provenance, compare_order_values,
261    cooperative_stable_sort_by, counts_every_row, exec_group_by, exec_group_by_with_provenance,
262    execute_materialized_join, execute_window, for_each_row_raw_cancellable, format_plan_tree,
263    literal_limit, predicate_column_indices_json, range_matches, synthesize_range_predicate,
264    validate_column_references, validate_json_path_types, validate_no_stray_aggregates,
265    validate_slice_counts, LoweredPlan,
266};
267
268/// Mission infra-1: classify a parsed statement as read-only vs. mutating.
269/// Used by [`Engine::execute_powql_readonly`] and by the server handler
270/// to decide between the RwLock reader and writer sides. `Union` recurses
271/// because each side can independently be read/write (though in practice
272/// both sides are reads — the parser only builds Union from query shapes).
273pub fn is_read_only_statement(stmt: &Statement) -> bool {
274    match stmt {
275        Statement::Query(_) => true,
276        Statement::ListTypes | Statement::Describe(_) | Statement::ListLinks => true,
277        Statement::Union(u) => is_read_only_statement(&u.left) && is_read_only_statement(&u.right),
278        Statement::Insert(_)
279        | Statement::Upsert(_)
280        | Statement::UpdateQuery(_)
281        | Statement::DeleteQuery(_)
282        | Statement::CreateType(_)
283        | Statement::CreateLink(_)
284        | Statement::AlterTable(_)
285        | Statement::DropTable(_)
286        | Statement::CreateView(_)
287        | Statement::RefreshView(_)
288        | Statement::DropView(_) => false,
289        Statement::Begin | Statement::Commit | Statement::Rollback => false,
290        Statement::Explain(inner) => is_read_only_statement(inner),
291    }
292}
293
294/// Map a read-only executor result into the read-only-engine surface: the
295/// internal "this statement writes" sentinel ([`QueryError::ReadonlyNeedsWrite`])
296/// becomes the terminal, operator-facing [`QueryError::ReadonlyMode`]. There is
297/// no writer to escalate to in read-only mode, so the sentinel never leaves the
298/// engine.
299fn to_readonly_terminal(
300    result: Result<QueryResult, QueryError>,
301) -> Result<QueryResult, QueryError> {
302    match result {
303        Err(QueryError::ReadonlyNeedsWrite) => Err(QueryError::ReadonlyMode),
304        other => other,
305    }
306}
307
308/// Return whether executing this read plan would have to refresh a dirty
309/// materialized view. This is intentionally a whole-plan preflight: the server
310/// may retry only this typed condition under exclusive admission, so it must be
311/// raised before any input branch performs row work.
312fn plan_reads_dirty_view(plan: &PlanNode, views: &ViewRegistry) -> bool {
313    match plan {
314        PlanNode::SeqScan { table }
315        | PlanNode::AliasScan { table, .. }
316        | PlanNode::IndexScan { table, .. }
317        | PlanNode::RangeScan { table, .. }
318        | PlanNode::ExprIndexScan { table, .. }
319        | PlanNode::ExprRangeScan { table, .. }
320        | PlanNode::OrderedExprIndexScan { table, .. } => views.is_dirty(table),
321
322        PlanNode::Filter { input, .. }
323        | PlanNode::Project { input, .. }
324        | PlanNode::Sort { input, .. }
325        | PlanNode::Limit { input, .. }
326        | PlanNode::Offset { input, .. }
327        | PlanNode::Aggregate { input, .. }
328        | PlanNode::Distinct { input }
329        | PlanNode::GroupBy { input, .. }
330        | PlanNode::Window { input, .. } => plan_reads_dirty_view(input, views),
331
332        PlanNode::NestedLoopJoin { left, right, .. } | PlanNode::Union { left, right, .. } => {
333            plan_reads_dirty_view(left, views) || plan_reads_dirty_view(right, views)
334        }
335
336        // Nested sub-query fields scan their child tables directly, so a
337        // dirty child view needs the same escalation as the parent input.
338        PlanNode::NestedProject { input, fields } => {
339            plan_reads_dirty_view(input, views)
340                || fields.iter().any(|field| match field {
341                    crate::plan::NestedProjectField::Nested(nested) => {
342                        let mut dirty = false;
343                        nested.visit_tables(&mut |table| dirty |= views.is_dirty(table));
344                        // A block link traversal's child table is a placeholder
345                        // until execution-time catalog resolution, so
346                        // visit_tables cannot see it; escalate conservatively
347                        // whenever any view is dirty.
348                        dirty
349                            || (plan_exec::nested_fields_have_via_link(std::slice::from_ref(field))
350                                && any_view_dirty(views))
351                    }
352                    crate::plan::NestedProjectField::Plain(_) => false,
353                    // Scalar link hop tables are likewise unknown here.
354                    crate::plan::NestedProjectField::Link(link) => {
355                        link.resolved.is_none() && any_view_dirty(views)
356                    }
357                })
358        }
359
360        // EXPLAIN formats its input without executing it, so inspecting a plan
361        // that names a dirty view never requires a refresh.
362        PlanNode::Explain { .. }
363        | PlanNode::AlterTable { .. }
364        | PlanNode::DropTable { .. }
365        | PlanNode::Insert { .. }
366        | PlanNode::Upsert { .. }
367        | PlanNode::Update { .. }
368        | PlanNode::Delete { .. }
369        | PlanNode::CreateTable { .. }
370        | PlanNode::CreateLink { .. }
371        | PlanNode::ListTypes
372        | PlanNode::Describe { .. }
373        | PlanNode::ListLinks
374        | PlanNode::CreateView { .. }
375        | PlanNode::RefreshView { .. }
376        | PlanNode::DropView { .. }
377        | PlanNode::Begin
378        | PlanNode::Commit
379        | PlanNode::Rollback => false,
380    }
381}
382
383/// Open the materialized-view registry over `data_dir`, marking every view
384/// whose stored source no longer parses as dirty.
385///
386/// Dirty is how a read is made to go through `Engine::refresh_view`, which is
387/// where an unreadable source is reported (see
388/// `plan_exec::dispatch::parse_stored_view_source`). Without this, such a view
389/// is CLEAN forever: its dependency list was empty for the same reason its
390/// source will not parse, so no mutation ever dirties it, no read ever
391/// refreshes it, and every read serves stale rows with no error at all. Marking
392/// it dirty converts that into the typed error, and touches only memory, so a
393/// database that is merely being inspected is not modified.
394/// Whether `data_dir` already holds a catalog, i.e. whether reopening it is
395/// meant to find an existing database.
396///
397/// The file name is the on-disk identity of a PowDB directory, shared by the
398/// backup, sync and server crates; it is a format constant, not a storage
399/// implementation detail, and changing it would be a format break carrying its
400/// own migration.
401fn catalog_file_present(data_dir: &Path) -> bool {
402    data_dir.join("catalog.bin").exists()
403}
404
405fn open_view_registry(data_dir: &Path) -> ViewRegistry {
406    let mut registry = ViewRegistry::open(data_dir).unwrap_or_else(|_| ViewRegistry::new(data_dir));
407    let unreadable: Vec<String> = registry
408        .list_views()
409        .iter()
410        .filter(|name| {
411            registry
412                .get(name)
413                .is_some_and(|def| crate::parser::parse(&def.query).is_err())
414        })
415        .map(|name| (*name).to_string())
416        .collect();
417    for name in unreadable {
418        warn!(
419            view = %name,
420            "materialized view has an unparseable stored source; reads will report an error \
421             rather than serve rows that cannot be recomputed"
422        );
423        registry.mark_dirty(&name);
424    }
425    registry
426}
427
428/// Names of the dirty materialized views this plan scans, taken from table
429/// names the plan itself carries.
430///
431/// Deliberately narrower than [`plan_reads_dirty_view`]: that one escalates
432/// conservatively for link traversals whose child table is only knowable after
433/// execution-time catalog resolution, which is the right answer for a preflight
434/// that can only say yes or no, but it cannot name a table to refresh. The
435/// write path refreshes those where it resolves them.
436fn collect_dirty_scanned_views(plan: &PlanNode, views: &ViewRegistry, out: &mut Vec<String>) {
437    match plan {
438        PlanNode::SeqScan { table }
439        | PlanNode::AliasScan { table, .. }
440        | PlanNode::IndexScan { table, .. }
441        | PlanNode::RangeScan { table, .. }
442        | PlanNode::ExprIndexScan { table, .. }
443        | PlanNode::ExprRangeScan { table, .. }
444        | PlanNode::OrderedExprIndexScan { table, .. } => {
445            if views.is_dirty(table) && !out.iter().any(|name| name == table) {
446                out.push(table.clone());
447            }
448        }
449
450        PlanNode::Filter { input, .. }
451        | PlanNode::Project { input, .. }
452        | PlanNode::Sort { input, .. }
453        | PlanNode::Limit { input, .. }
454        | PlanNode::Offset { input, .. }
455        | PlanNode::Aggregate { input, .. }
456        | PlanNode::Distinct { input }
457        | PlanNode::GroupBy { input, .. }
458        | PlanNode::Window { input, .. }
459        | PlanNode::NestedProject { input, .. } => collect_dirty_scanned_views(input, views, out),
460
461        PlanNode::NestedLoopJoin { left, right, .. } | PlanNode::Union { left, right, .. } => {
462            collect_dirty_scanned_views(left, views, out);
463            collect_dirty_scanned_views(right, views, out);
464        }
465
466        // EXPLAIN formats its input without executing it, and the write
467        // statements own their own view bookkeeping.
468        _ => {}
469    }
470}
471
472/// True when any registered materialized view is currently dirty. Conservative
473/// escalation test for plans whose scanned tables are not knowable before
474/// execution-time catalog resolution (link traversals resolve their child
475/// tables from the persistent catalog at query time).
476fn any_view_dirty(views: &ViewRegistry) -> bool {
477    views.list_views().iter().any(|v| views.is_dirty(v))
478}
479
480pub struct Engine {
481    catalog: Catalog,
482    /// Exclusive PID-based lock on the data directory, held for the engine's
483    /// lifetime so two separate processes can't open the same dir and corrupt
484    /// the heap/WAL. Released on clean drop; a `mem::forget` crash leaves a
485    /// stale lock the next open takes over. Leading `_`: it does its work
486    /// through `Drop`, never read directly.
487    _dir_lock: powdb_storage::dir_lock::DirLock,
488    /// Mission D9 — cached parsed+planned query trees keyed by canonical
489    /// hash. Saves the ~3μs parse+plan cost on repeat queries that differ
490    /// only in literal values.
491    ///
492    /// Mission infra-1: wrapped in `Mutex` so the read path can be driven
493    /// by `&self`. The critical section is extremely short — a single
494    /// hashmap lookup + plan clone on a hit, or a single insert on a miss.
495    /// A full `RwLock` would be over-engineered here; the contention window
496    /// is smaller than the read-path scan work it gates.
497    plan_cache: Mutex<PlanCache>,
498    /// Mission C Phase 13: reusable `Vec<Value>` scratch buffer for the
499    /// prepared-insert fast path. `execute_prepared` used to allocate a
500    /// fresh `vec![Value::Empty; n_cols]` on every insert; recycling this
501    /// buffer shaves one heap alloc per row on `insert_batch_1k`.
502    insert_values_scratch: Vec<Value>,
503    /// Materialized view registry: tracks view definitions, dependencies,
504    /// and dirty state. Views are backed by regular catalog tables; this
505    /// registry adds the lifecycle metadata.
506    view_registry: ViewRegistry,
507    in_transaction: bool,
508    /// WS2 — per-query memory budget ceiling (bytes). The running total lives
509    /// in a thread-local (see [`mem_budget`]) and is reset at every top-level
510    /// query entry, so sort/join/GROUP BY/IN-list materialization can be capped
511    /// without OOM-killing the process. This field holds only the *limit* (a
512    /// plain `usize`, so `Engine` stays `Sync` for the concurrent read path).
513    /// Default [`mem_budget::DEFAULT_QUERY_MEMORY_LIMIT`] (256 MB); overridable
514    /// via `Engine::with_memory_limit` (server reads `POWDB_QUERY_MEMORY_LIMIT`).
515    query_memory_limit: usize,
516    /// Maximum candidate pairs a fallback nested-loop join may evaluate before
517    /// it is rejected. Default [`MAX_NESTED_LOOP_PAIRS`], overridable via
518    /// [`Engine::set_nested_loop_pair_limit`] (server reads
519    /// `POWDB_MAX_NESTED_LOOP_PAIRS`). A plain `usize` so `Engine` stays `Sync`.
520    nested_loop_pair_limit: usize,
521    wal_archive_hook: Option<WalArchiveHook>,
522    /// True when opened via [`Engine::open_read_only`] for snapshot serving. In
523    /// this mode the catalog and its files are read-only, the `DirLock` is a
524    /// shared reader lock, and every mutating execute path returns the terminal
525    /// [`QueryError::ReadonlyMode`] instead of ever touching disk.
526    read_only: bool,
527    /// Test-only: when true, every executor fast path and the compiled
528    /// predicate entry decline to fire, so the query runs through the generic
529    /// evaluator. See [`Engine::set_force_generic_path`]. The field only
530    /// exists under the `testing` feature, and [`Engine::generic_path_forced`]
531    /// is a compile-time `false` without it, so no shipped build pays a branch.
532    #[cfg(feature = "testing")]
533    force_generic_path: bool,
534    /// Test-only: the name of every fast-path check site that has declined
535    /// because `force_generic_path` was set. A bare count would only tell a
536    /// test that *something* declined; a query usually passes several check
537    /// sites, so a count stays non-zero even when the one site under test lost
538    /// its guard. Recording names is what makes "this shape really was
539    /// diverted" provable, and a missed site is a hole in the whole runner.
540    /// Behind a `Mutex` because the read path drives the engine by `&self` and
541    /// `Engine` must stay `Sync`; it is only ever locked while the switch is on.
542    #[cfg(feature = "testing")]
543    forced_generic_sites: std::sync::Mutex<Vec<&'static str>>,
544}
545
546impl Engine {
547    /// Open or create a PowDB engine rooted at `data_dir`.
548    ///
549    /// If the directory already contains a catalog, it is reopened.
550    /// Otherwise a fresh empty database is created.
551    ///
552    /// # Examples
553    ///
554    /// ```
555    /// use powdb_query::executor::Engine;
556    ///
557    /// let dir = tempfile::tempdir().unwrap();
558    /// let engine = Engine::new(dir.path()).unwrap();
559    /// // Engine is ready — the directory now contains a catalog.
560    /// ```
561    pub fn new(data_dir: &Path) -> io::Result<Self> {
562        Self::new_inner(data_dir, None)
563    }
564
565    /// Open or create an engine that archives WAL records before any recovery,
566    /// rollback, or drop checkpoint truncates them. This keeps the query crate
567    /// independent of replication metadata while giving sync-aware callers one
568    /// lifecycle boundary for retained-history preservation.
569    pub fn new_with_wal_archive<F>(data_dir: &Path, archive: F) -> io::Result<Self>
570    where
571        F: Fn(&Path, &[powdb_storage::wal::WalRecord]) -> io::Result<()> + Send + Sync + 'static,
572    {
573        Self::new_inner(data_dir, Some(Arc::new(archive)))
574    }
575
576    fn new_inner(data_dir: &Path, wal_archive_hook: Option<WalArchiveHook>) -> io::Result<Self> {
577        powdb_storage::create_data_dir_secure(data_dir)?;
578        // Refuse to open a directory another live process already holds, before
579        // touching any on-disk state (concurrent writers corrupt the heap/WAL).
580        let dir_lock = powdb_storage::dir_lock::DirLock::acquire(data_dir)?;
581        // Try to reopen an existing database first; only create a fresh
582        // catalog when there isn't one already on disk.
583        let catalog_result = match &wal_archive_hook {
584            Some(hook) => {
585                let hook = Arc::clone(hook);
586                Catalog::open_with_wal_archive(data_dir, move |dir, records| hook(dir, records))
587            }
588            None => Catalog::open(data_dir),
589        };
590        let catalog = match catalog_result {
591            Ok(c) => {
592                info!(data_dir = %data_dir.display(), "engine reopened existing database");
593                c
594            }
595            // Exactly one NotFound means "there is no database here": the one
596            // `Catalog::open` raises because the catalog file itself is absent.
597            // Every other file the open path touches raises the same kind, a
598            // table's `.heap` most obviously, and `Catalog::create` renames a
599            // fresh empty catalog over the existing one and truncates the WAL.
600            // Treating any NotFound as a fresh directory therefore turned a
601            // single missing heap into silent, total loss of every table,
602            // including the ones still intact on disk. Damage must stay loud so
603            // the missing file can be restored.
604            Err(e) if e.kind() == io::ErrorKind::NotFound && !catalog_file_present(data_dir) => {
605                info!(data_dir = %data_dir.display(), "engine initialized fresh database");
606                Catalog::create(data_dir)?
607            }
608            Err(e) => return Err(e),
609        };
610        let view_registry = open_view_registry(data_dir);
611        Ok(Engine {
612            catalog,
613            _dir_lock: dir_lock,
614            plan_cache: Mutex::new(PlanCache::new(PLAN_CACHE_CAPACITY)),
615            insert_values_scratch: Vec::new(),
616            view_registry,
617            in_transaction: false,
618            query_memory_limit: mem_budget::DEFAULT_QUERY_MEMORY_LIMIT,
619            nested_loop_pair_limit: MAX_NESTED_LOOP_PAIRS,
620            wal_archive_hook,
621            read_only: false,
622            #[cfg(feature = "testing")]
623            force_generic_path: false,
624            #[cfg(feature = "testing")]
625            forced_generic_sites: std::sync::Mutex::new(Vec::new()),
626        })
627    }
628
629    /// Open an engine **read-only** over a quiescent data directory for snapshot
630    /// serving (tier 1 of the replica story). This is the supported way to serve
631    /// a restored backup or a checkpointed replica with no write gate at all:
632    ///
633    /// - the catalog and every heap/index/WAL file are opened read-only
634    ///   ([`Catalog::open_read_only`]), so nothing on disk is ever mutated;
635    /// - a **shared reader** [`DirLock`] is taken, so N read-only processes may
636    ///   serve the same directory concurrently, while a read-write open refuses
637    ///   to start against live readers (and readers refuse a live writer);
638    /// - a non-empty WAL is refused with an actionable error rather than replayed
639    ///   (the directory must be recovered by a read-write engine first);
640    /// - every mutating statement returns the terminal [`QueryError::ReadonlyMode`].
641    ///
642    /// Materialized-view refresh must happen before snapshotting: a query over a
643    /// stale (dirty) view is refused in this mode rather than silently escalating.
644    pub fn open_read_only(data_dir: &Path) -> io::Result<Self> {
645        // Validate readability without ever chmod-ing the directory (a read-only
646        // open must leave it byte-identical).
647        powdb_storage::validate_data_dir_read_only(data_dir)?;
648        // A shared reader lock: coexists with other readers, refuses a live writer.
649        let dir_lock = powdb_storage::dir_lock::DirLock::acquire_reader(data_dir)?;
650        let catalog = Catalog::open_read_only(data_dir)?;
651        info!(data_dir = %data_dir.display(), "engine opened read-only for snapshot serving");
652        let view_registry = open_view_registry(data_dir);
653        Ok(Engine {
654            catalog,
655            _dir_lock: dir_lock,
656            plan_cache: Mutex::new(PlanCache::new(PLAN_CACHE_CAPACITY)),
657            insert_values_scratch: Vec::new(),
658            view_registry,
659            in_transaction: false,
660            query_memory_limit: mem_budget::DEFAULT_QUERY_MEMORY_LIMIT,
661            nested_loop_pair_limit: MAX_NESTED_LOOP_PAIRS,
662            // No WAL-archive hook: a read-only engine never writes, so its Drop
663            // must never checkpoint (the hook is what would drive that).
664            wal_archive_hook: None,
665            read_only: true,
666            #[cfg(feature = "testing")]
667            force_generic_path: false,
668            #[cfg(feature = "testing")]
669            forced_generic_sites: std::sync::Mutex::new(Vec::new()),
670        })
671    }
672
673    /// Read-only open with an explicit per-query memory budget (bytes).
674    pub fn open_read_only_with_memory_limit(
675        data_dir: &Path,
676        limit_bytes: usize,
677    ) -> io::Result<Self> {
678        let mut engine = Engine::open_read_only(data_dir)?;
679        engine.set_query_memory_limit(limit_bytes);
680        Ok(engine)
681    }
682
683    /// Whether this engine was opened read-only for snapshot serving.
684    pub fn is_read_only(&self) -> bool {
685        self.read_only
686    }
687
688    /// Plan `stmt` and lower it. **The only place in the executor that calls
689    /// the planner.**
690    ///
691    /// Planner output is not executable as it stands: the planner is pure, so
692    /// it emits `IndexScan` / `RangeScan` probes speculatively and leaves every
693    /// literal exactly as written, and lowering is what decides whether those
694    /// probes exist and what key bytes they address. Running raw planner output
695    /// is therefore not a missed optimization, it is a different answer.
696    ///
697    /// Eight subquery materialization sites used to plan a statement and hand
698    /// the result straight to `execute_plan` / `execute_plan_readonly`. The
699    /// consequence was that a predicate answered correctly at the top level and
700    /// incorrectly one level of nesting down:
701    /// `count(H filter .price < 3)` gave 2 while
702    /// `count(H filter .n in (H filter .price < 3 { .n }))` gave 0 over the
703    /// same rows and the same index.
704    ///
705    /// Funnelling every plan through here is what makes that unrepeatable: a
706    /// ninth site has to call this to get a plan at all, and what it gets back
707    /// is a [`LoweredPlan`], which is the only thing the execution entry points
708    /// accept. `no_execution_entry_point_can_receive_an_unlowered_plan` in
709    /// `tests/cross_type_index_parity.rs` fails the build if a second call to
710    /// the planner appears anywhere under `src/executor/`.
711    fn plan_and_lower(&self, stmt: Statement) -> Result<LoweredPlan, QueryError> {
712        Ok(self.plan_and_lower_cacheable(stmt)?.1)
713    }
714
715    /// [`Engine::plan_and_lower`] for the callers that also need the raw plan,
716    /// which is only ever the plan cache: the cache stores the pre-lowering
717    /// tree, because lowering is a function of catalog state and the cache
718    /// outlives DDL. Lowering therefore runs on every cache hit as well.
719    fn plan_and_lower_cacheable(
720        &self,
721        stmt: Statement,
722    ) -> Result<(PlanNode, LoweredPlan), QueryError> {
723        let plan =
724            crate::planner::plan_statement(stmt).map_err(|e| QueryError::Parse(e.to_string()))?;
725        let lowered = self.lower(&plan);
726        Ok((plan, lowered))
727    }
728
729    /// [`Engine::plan_and_lower_cacheable`] from PowQL text. The only call to
730    /// `planner::plan` under `src/executor/`, for the same reason.
731    fn plan_text_and_lower(&self, input: &str) -> Result<(PlanNode, LoweredPlan), QueryError> {
732        let plan = planner::plan(input).map_err(|e| QueryError::Parse(e.to_string()))?;
733        let lowered = self.lower(&plan);
734        Ok((plan, lowered))
735    }
736
737    /// Lower a plan that came from somewhere other than the planner: the plan
738    /// cache, or a fallback the executor built from an already-lowered tree.
739    /// Lowering is idempotent, so calling it on a plan that has been through it
740    /// already is a no-op.
741    fn lower(&self, plan: &PlanNode) -> LoweredPlan {
742        LoweredPlan::of(&self.catalog, plan)
743    }
744
745    /// Test-only: the EXPLAIN text of `query`'s plan after `passes` rounds of
746    /// lowering.
747    ///
748    /// Routing every plan through [`Engine::plan_and_lower`] is only sound if
749    /// lowering is idempotent: a plan that reaches an entry point already
750    /// lowered (a re-lowered cache hit, a prepared template, a fallback the
751    /// executor rebuilt from a lowered tree) must come out unchanged rather
752    /// than rewritten a second time. This exposes the pass so a test can hold
753    /// that directly instead of inferring it from answers.
754    ///
755    /// Only available with the `testing` feature.
756    #[cfg(feature = "testing")]
757    pub fn lowered_plan_text(&self, query: &str, passes: usize) -> Result<String, QueryError> {
758        let (_, mut plan) = self.plan_text_and_lower(query)?;
759        for _ in 1..passes.max(1) {
760            plan = self.lower(plan.node());
761        }
762        Ok(format_plan_tree(&self.catalog, plan.node(), 0))
763    }
764
765    /// Run a lowered plan on the mutable path. `Engine::execute_plan` stays
766    /// public and takes a bare `&PlanNode` for embedders that build plans
767    /// themselves, and lowers it before calling this; every path inside the
768    /// executor goes through here so that what it runs is a plan the type
769    /// system says was lowered.
770    fn execute_lowered(&mut self, plan: &LoweredPlan) -> Result<QueryResult, QueryError> {
771        self.refresh_dirty_views_read_by(plan.node())?;
772        self.dispatch_mut(plan.node())
773    }
774
775    /// Refresh every stale materialized view this plan is about to read, before
776    /// any of it runs.
777    ///
778    /// The dispatch arms each carry their own dirty check, and the fast paths
779    /// that short-circuit them do not: `V filter .id > 0 { .id }` is served by
780    /// `project_filter_limit_fast`, which takes the table name and scans the
781    /// backing heap directly, so a stale view answered with its pre-mutation
782    /// rows while the bare `V` next to it answered correctly. Checking at every
783    /// fast path is how that happened; checking once, here, at the boundary
784    /// every statement and subquery crosses, is what makes it not recur.
785    ///
786    /// The walk only runs when a view is dirty at all, and only refreshes views
787    /// the plan actually names, so refreshing one cannot re-enter itself
788    /// through its own source query.
789    fn refresh_dirty_views_read_by(&mut self, plan: &PlanNode) -> Result<(), QueryError> {
790        if !any_view_dirty(&self.view_registry) {
791            return Ok(());
792        }
793        let mut stale: Vec<String> = Vec::new();
794        collect_dirty_scanned_views(plan, &self.view_registry, &mut stale);
795        for name in stale {
796            self.refresh_view(&name)?;
797        }
798        Ok(())
799    }
800
801    /// Test-only: force every query onto the generic evaluator.
802    ///
803    /// The planner is pure, so one query text runs through different physical
804    /// code depending on catalog state and plan shape: a compiled byte-level
805    /// predicate, a fused scan, a bounded top-N heap, an index probe, or the
806    /// generic decode-and-evaluate loop. Those paths are supposed to be
807    /// indistinguishable from outside; twice now they were not, and the
808    /// disagreement shipped because no test ran the same query both ways.
809    ///
810    /// With this set, predicate compilation declines and every fast-path match
811    /// site falls through, so a test can execute a query optimized and
812    /// unoptimized and diff the two results.
813    /// It changes which code runs, never what the answer should be: any
814    /// difference it exposes is a bug in one of the two paths.
815    ///
816    /// Each decline records the name of the site that declined; read them back
817    /// with [`Engine::forced_generic_sites`]. A comparison whose shape never
818    /// declined anywhere is comparing one code path with itself, so the names
819    /// are what keep the comparison honest.
820    ///
821    /// Only available with the `testing` feature; there is no way to reach it
822    /// from a shipped build.
823    #[cfg(feature = "testing")]
824    pub fn set_force_generic_path(&mut self, force: bool) {
825        self.force_generic_path = force;
826    }
827
828    /// Whether fast paths are currently suppressed, recording `site` when they
829    /// are. `site` names the specific fast path being declined, so a test can
830    /// assert that the shape it ran was diverted *there* rather than merely
831    /// somewhere. Compiles to a constant `false` without the `testing` feature,
832    /// so every guarded branch folds away in a shipped build.
833    #[cfg(feature = "testing")]
834    #[inline]
835    pub(in crate::executor) fn generic_path_forced(&self, site: &'static str) -> bool {
836        if self.force_generic_path {
837            if let Ok(mut sites) = self.forced_generic_sites.lock() {
838                sites.push(site);
839            }
840            return true;
841        }
842        false
843    }
844
845    /// Test-only: the fast-path check sites that have declined so far because
846    /// [`Engine::set_force_generic_path`] is on, in the order they declined. A
847    /// shape that is supposed to reach a named fast path but never appears here
848    /// has a missing check site, not a passing test.
849    #[cfg(feature = "testing")]
850    pub fn forced_generic_sites(&self) -> Vec<&'static str> {
851        match self.forced_generic_sites.lock() {
852            Ok(sites) => sites.clone(),
853            Err(poisoned) => poisoned.into_inner().clone(),
854        }
855    }
856
857    /// Test-only: forget the recorded declines so one query's declines can be
858    /// observed in isolation.
859    #[cfg(feature = "testing")]
860    pub fn reset_forced_generic_sites(&self) {
861        match self.forced_generic_sites.lock() {
862            Ok(mut sites) => sites.clear(),
863            Err(poisoned) => poisoned.into_inner().clear(),
864        }
865    }
866
867    #[cfg(not(feature = "testing"))]
868    #[inline]
869    pub(in crate::executor) fn generic_path_forced(&self, _site: &'static str) -> bool {
870        false
871    }
872
873    /// Compile `predicate` into a byte-level closure, unless fast paths are
874    /// suppressed. This is the single entry point every executor site uses, so
875    /// [`Engine::set_force_generic_path`] cannot be bypassed by a caller that
876    /// forgets the check.
877    #[inline]
878    pub(in crate::executor) fn compile_predicate_unless_forced(
879        &self,
880        site: &'static str,
881        predicate: &Expr,
882        columns: &[String],
883        layout: &FastLayout,
884        schema: &Schema,
885    ) -> Option<CompiledPredicate> {
886        if self.generic_path_forced(site) {
887            return None;
888        }
889        compile_predicate(predicate, columns, layout, schema)
890    }
891
892    /// Open or create an engine with an explicit per-query memory limit
893    /// (bytes). Used by the server to apply `POWDB_QUERY_MEMORY_LIMIT`, and by
894    /// tests that need a tiny limit to exercise the budget guard.
895    pub fn with_memory_limit(data_dir: &Path, limit_bytes: usize) -> io::Result<Self> {
896        let mut engine = Engine::new(data_dir)?;
897        engine.set_query_memory_limit(limit_bytes);
898        Ok(engine)
899    }
900
901    /// Open or create an archive-aware engine with an explicit per-query memory
902    /// limit.
903    pub fn with_memory_limit_and_wal_archive<F>(
904        data_dir: &Path,
905        limit_bytes: usize,
906        archive: F,
907    ) -> io::Result<Self>
908    where
909        F: Fn(&Path, &[powdb_storage::wal::WalRecord]) -> io::Result<()> + Send + Sync + 'static,
910    {
911        let mut engine = Engine::new_with_wal_archive(data_dir, archive)?;
912        engine.set_query_memory_limit(limit_bytes);
913        Ok(engine)
914    }
915
916    /// Current per-query memory limit in bytes.
917    pub fn query_memory_limit(&self) -> usize {
918        self.query_memory_limit
919    }
920
921    /// Override the per-query memory limit in bytes (builder-style).
922    pub fn set_query_memory_limit(&mut self, limit_bytes: usize) {
923        self.query_memory_limit = limit_bytes;
924    }
925
926    /// Current fallback nested-loop join candidate-pair cap.
927    pub fn nested_loop_pair_limit(&self) -> usize {
928        self.nested_loop_pair_limit
929    }
930
931    /// Override the fallback nested-loop join candidate-pair cap. Used by the
932    /// server to apply `POWDB_MAX_NESTED_LOOP_PAIRS`, and by tests that need a
933    /// tiny cap to exercise the guard on a small join. A zero limit is clamped
934    /// to 1 so a valid single-pair join is never rejected outright.
935    pub fn set_nested_loop_pair_limit(&mut self, limit: usize) {
936        self.nested_loop_pair_limit = limit.max(1);
937    }
938
939    /// Set the WAL durability mode (see [`WalSyncMode`]). `Full` (the default)
940    /// fsyncs every commit; `Normal` moves the fsync to a background flusher
941    /// with a bounded crash-loss window; `Off` is bench-only (no durability).
942    /// Wired from the server's `POWDB_SYNC_MODE` / `--sync-mode` config.
943    pub fn set_wal_sync_mode(&mut self, mode: WalSyncMode) {
944        self.catalog.set_wal_sync_mode(mode);
945    }
946
947    /// Run `f` with commit durability deferred — the WAL group-commit entry
948    /// point for callers that serialize writers behind an exclusive lock.
949    ///
950    /// Inside `f`, Full-mode commit points register the WAL generation they
951    /// need durable instead of fsyncing inline. The returned ticket (if any)
952    /// must be waited on before the statement's result is acknowledged; the
953    /// caller should release its exclusive engine lock first, so other
954    /// committers can append while the fsync runs. That overlap is what lets
955    /// one fsync cover many commits. A lone committer's wait performs the
956    /// fsync immediately — group commit never introduces a delay.
957    ///
958    /// `Normal`/`Off` sync modes return no ticket; their durability
959    /// contracts are unchanged. If `f` panics the engine must not be reused
960    /// (the deferral flag may still be set); lock poisoning enforces this
961    /// for callers that share the engine behind a lock.
962    pub fn run_with_deferred_durability<T>(
963        &mut self,
964        f: impl FnOnce(&mut Engine) -> T,
965    ) -> (T, Option<WalDurabilityTicket>) {
966        self.catalog.set_wal_sync_deferred(true);
967        let out = f(self);
968        self.catalog.set_wal_sync_deferred(false);
969        let ticket = self.catalog.take_wal_durability_ticket();
970        (out, ticket)
971    }
972
973    /// Number of fsyncs issued against the WAL (test/metrics hook).
974    pub fn wal_fsync_count(&self) -> u64 {
975        self.catalog.wal_fsync_count()
976    }
977
978    /// Roll back the active explicit transaction while archiving any committed
979    /// pre-transaction WAL records that recovery must replay and truncate.
980    /// This is the sync-aware counterpart to the ordinary `rollback` statement;
981    /// callers provide the archive hook so the query crate stays independent of
982    /// replication metadata.
983    pub fn rollback_transaction_with_wal_archive<F>(
984        &mut self,
985        archive: F,
986    ) -> Result<QueryResult, QueryError>
987    where
988        F: FnMut(&Path, &[powdb_storage::wal::WalRecord]) -> io::Result<()>,
989    {
990        if !self.in_transaction {
991            return Err(QueryError::Execution(
992                "no active transaction to roll back".into(),
993            ));
994        }
995        self.catalog
996            .rollback_to_last_sync_with_wal_archive(archive)
997            .map_err(|e| QueryError::StorageError(e.to_string()))?;
998        self.finish_rollback_after_catalog_restore()
999    }
1000
1001    pub fn rollback_transaction_preserving_wal_archive(
1002        &mut self,
1003    ) -> Result<QueryResult, QueryError> {
1004        let Some(hook) = self.wal_archive_hook.clone() else {
1005            if !self.in_transaction {
1006                return Err(QueryError::Execution(
1007                    "no active transaction to roll back".into(),
1008                ));
1009            }
1010            self.catalog
1011                .rollback_to_last_sync()
1012                .map_err(|e| QueryError::StorageError(e.to_string()))?;
1013            return self.finish_rollback_after_catalog_restore();
1014        };
1015        self.rollback_transaction_with_wal_archive(move |dir, records| hook(dir, records))
1016    }
1017
1018    fn finish_rollback_after_catalog_restore(&mut self) -> Result<QueryResult, QueryError> {
1019        self.in_transaction = false;
1020        if let Ok(mut cache) = self.plan_cache.lock() {
1021            cache.clear();
1022        }
1023        self.view_registry = open_view_registry(self.catalog.data_dir());
1024        Ok(QueryResult::Executed {
1025            message: "transaction rolled back".to_string(),
1026        })
1027    }
1028
1029    /// Enter a budgeted-statement frame for the current query. The returned
1030    /// guard must be held for the duration of the statement; on its drop the
1031    /// reentrancy depth is decremented. Only the *outermost* statement entry
1032    /// zeroes this thread's running total, so a nested `execute_powql` (the
1033    /// source query of a `create_view`/`refresh_view`) does NOT discard the
1034    /// outer frame's accounting. The accumulator is thread-local, so this never
1035    /// touches another concurrent query's total.
1036    #[must_use = "the budget guard must outlive the statement body"]
1037    pub(super) fn enter_memory_budget(&self) -> mem_budget::EnterGuard {
1038        mem_budget::enter()
1039    }
1040
1041    /// Charge the estimated footprint of a freshly materialized batch of rows
1042    /// against the current per-query budget. Returns
1043    /// [`QueryError::MemoryLimitExceeded`] cleanly if the batch would push the
1044    /// query over its limit. Used at every full-materialization point (sort
1045    /// buffer, join build side, GROUP BY hash table, IN-list).
1046    pub(super) fn charge_rows(&self, rows: &[Vec<Value>]) -> Result<(), QueryError> {
1047        let mut total = 0usize;
1048        let mut cancel = crate::cancel::CancelCheck::new();
1049        for row in rows {
1050            cancel.tick()?;
1051            total = total.saturating_add(mem_budget::estimate_row_size(row));
1052        }
1053        mem_budget::charge(total, self.query_memory_limit)
1054    }
1055
1056    /// Charge a materialized IN-list (the literal expressions pulled out of an
1057    /// uncorrelated `IN (subquery)`) against the current per-query budget.
1058    /// Each item is conservatively sized at the `Expr` slot plus, for string
1059    /// literals, the owned heap bytes.
1060    pub(super) fn charge_in_list(&self, list: &[crate::ast::Expr]) -> Result<(), QueryError> {
1061        let base = std::mem::size_of::<crate::ast::Expr>();
1062        let mut total = std::mem::size_of::<Vec<crate::ast::Expr>>();
1063        let mut cancel = crate::cancel::CancelCheck::new();
1064        for item in list {
1065            cancel.tick()?;
1066            total = total.saturating_add(base);
1067            if let crate::ast::Expr::Literal(crate::ast::Literal::String(s)) = item {
1068                total = total.saturating_add(s.capacity());
1069            }
1070        }
1071        mem_budget::charge(total, self.query_memory_limit)
1072    }
1073
1074    /// Dispatch to the requested query frontend.
1075    pub fn execute_with_dialect(
1076        &mut self,
1077        dialect: QueryDialect,
1078        input: &str,
1079    ) -> Result<QueryResult, QueryError> {
1080        match dialect {
1081            QueryDialect::PowQL => self.execute_powql(input),
1082            QueryDialect::Sql => self.execute_sql(input),
1083        }
1084    }
1085
1086    /// Read-only variant of [`Engine::execute_with_dialect`].
1087    pub fn execute_readonly_with_dialect(
1088        &self,
1089        dialect: QueryDialect,
1090        input: &str,
1091    ) -> Result<QueryResult, QueryError> {
1092        match dialect {
1093            QueryDialect::PowQL => self.execute_powql_readonly(input),
1094            QueryDialect::Sql => self.execute_sql_readonly(input),
1095        }
1096    }
1097
1098    /// Parse + plan + execute a PowQL query.
1099    ///
1100    /// # Examples
1101    ///
1102    /// ```
1103    /// use powdb_query::executor::Engine;
1104    /// use powdb_query::result::QueryResult;
1105    ///
1106    /// let dir = tempfile::tempdir().unwrap();
1107    /// let mut engine = Engine::new(dir.path()).unwrap();
1108    ///
1109    /// // Create a table and insert a row.
1110    /// engine.execute_powql("type User { required name: str, age: int }").unwrap();
1111    /// engine.execute_powql(r#"insert User { name := "Alice", age := 30 }"#).unwrap();
1112    ///
1113    /// // Query rows back.
1114    /// let result = engine.execute_powql("User").unwrap();
1115    /// assert_eq!(result.row_count(), 1);
1116    /// ```
1117    ///
1118    /// Mission D6 — tracing collapse: the previous implementation ran 4
1119    /// `Instant::now()` + 3 `elapsed().as_micros()` calls + formatted an
1120    /// `info!` span on every query, even when tracing was disabled. On a
1121    /// sub-microsecond `point_lookup_indexed` call that overhead was
1122    /// 100-200ns — 20%+ of the whole query. We now measure time only when
1123    /// INFO is actually enabled via `tracing::enabled!`, and we moved the
1124    /// noisy `debug!(?plan)` line behind the same gate so the Debug
1125    /// formatter can't run unconditionally either.
1126    ///
1127    /// Mission D9 — plan cache: on the hot path we canonicalise the query
1128    /// text (lex + FNV-1a hash with literal values stripped), check the
1129    /// cache, and on a hit substitute the new literals into a clone of the
1130    /// cached plan. This skips re-lexing, re-parsing, and re-planning —
1131    /// around 3μs per call on bench workloads. On a miss we plan as before
1132    /// and insert the plan under its canonical hash.
1133    pub fn execute_powql(&mut self, input: &str) -> Result<QueryResult, QueryError> {
1134        if self.read_only {
1135            // Snapshot-serving mode: run reads through the read-only executor and
1136            // turn the "this statement writes" sentinel into the terminal
1137            // ReadonlyMode error. No mutation ever reaches disk.
1138            return to_readonly_terminal(self.execute_powql_readonly(input));
1139        }
1140        // WS2: each *outermost* statement starts with the full memory
1141        // allowance. The guard holds the reentrancy depth so a nested
1142        // `execute_powql` (e.g. a view's source query) does not reset the
1143        // outer frame's accounting mid-statement.
1144        let _budget = self.enter_memory_budget();
1145        // A token may be cancelled before execution starts (for example, EOF
1146        // detected while this job was waiting for the engine lock). Check once
1147        // at the statement boundary so even point operations with no long loop
1148        // honor cancellation before they can mutate state.
1149        crate::cancel::check()?;
1150        // Hot path: tracing disabled. Zero syscalls, zero formatting.
1151        if !tracing::enabled!(Level::INFO) {
1152            // D9: try the plan cache first. Canonicalisation lexes the
1153            // query once; on a hit we skip the parser and planner entirely.
1154            if let Ok((hash, literals)) = canonicalize(input) {
1155                let cached = self
1156                    .plan_cache
1157                    .lock()
1158                    .map_err(|e| QueryError::Execution(format!("plan cache lock poisoned: {e}")))?
1159                    .get_with_substitution(hash, &literals);
1160                if let Some(plan) = cached {
1161                    let plan = self.lower(&plan);
1162                    let result = self.execute_lowered(&plan);
1163                    // Mission B (post-review): statement-boundary WAL
1164                    // group commit. Catalog::wal_log now only appends;
1165                    // the fsync happens here exactly once per statement.
1166                    // `sync_wal` is a no-op when nothing was buffered
1167                    // (pure reads pay zero fsync).
1168                    if !self.in_transaction {
1169                        self.catalog
1170                            .commit_autocommit()
1171                            .map_err(|e| QueryError::StorageError(e.to_string()))?;
1172                    }
1173                    return result;
1174                }
1175                // Miss — plan, insert, execute.
1176                let (raw, plan) = self.plan_text_and_lower(input)?;
1177                self.plan_cache
1178                    .lock()
1179                    .map_err(|e| QueryError::Execution(format!("plan cache lock poisoned: {e}")))?
1180                    .insert(hash, raw, literals.len());
1181                let result = self.execute_lowered(&plan);
1182                if !self.in_transaction {
1183                    self.catalog
1184                        .commit_autocommit()
1185                        .map_err(|e| QueryError::StorageError(e.to_string()))?;
1186                }
1187                return result;
1188            }
1189            // Lex error — fall through to the planner so the caller gets a
1190            // consistent error shape.
1191            let (_, plan) = self.plan_text_and_lower(input)?;
1192            let result = self.execute_lowered(&plan);
1193            if !self.in_transaction {
1194                self.catalog
1195                    .commit_autocommit()
1196                    .map_err(|e| QueryError::StorageError(e.to_string()))?;
1197            }
1198            return result;
1199        }
1200
1201        // Instrumented path — only taken under explicit tracing subscribers.
1202        let total_start = Instant::now();
1203        let plan_start = Instant::now();
1204        // `plan_us` now covers planning AND lowering. They are one step from
1205        // the caller's point of view (lowering is not optional, an unlowered
1206        // plan answers differently), and keeping them one call is what keeps
1207        // the planner reachable from a single place.
1208        let (_, plan) = self.plan_text_and_lower(input).inspect_err(|err| {
1209            error!(query = %input, error = %err, "query plan failed");
1210        })?;
1211        let plan_us = plan_start.elapsed().as_micros();
1212
1213        let exec_start = Instant::now();
1214        let result = self.execute_lowered(&plan);
1215        if !self.in_transaction {
1216            self.catalog
1217                .commit_autocommit()
1218                .map_err(|e| QueryError::StorageError(e.to_string()))?;
1219        }
1220        let exec_us = exec_start.elapsed().as_micros();
1221
1222        let total_us = total_start.elapsed().as_micros();
1223        match &result {
1224            Ok(r) => {
1225                info!(
1226                    query = %input,
1227                    plan_us = plan_us,
1228                    exec_us = exec_us,
1229                    total_us = total_us,
1230                    rows = r.row_count(),
1231                    "query ok"
1232                );
1233            }
1234            Err(e) => {
1235                error!(
1236                    query = %input,
1237                    plan_us = plan_us,
1238                    exec_us = exec_us,
1239                    error = %e,
1240                    "query failed"
1241                );
1242            }
1243        }
1244        result
1245    }
1246
1247    /// Parse + plan + execute a SQL query through the SQL frontend.
1248    ///
1249    /// SQL is lowered to the existing PowDB AST and to canonical PowQL text.
1250    /// The canonical PowQL text is used as the plan-cache key, so equivalent
1251    /// SQL and PowQL spellings share cached plans.
1252    pub fn execute_sql(&mut self, input: &str) -> Result<QueryResult, QueryError> {
1253        if self.read_only {
1254            return to_readonly_terminal(self.execute_sql_readonly(input));
1255        }
1256        let _budget = self.enter_memory_budget();
1257        crate::cancel::check()?;
1258        let parsed = crate::sql::parse_sql_with_canonical(input)
1259            .map_err(|e| QueryError::Parse(e.to_string()))?;
1260
1261        if !tracing::enabled!(Level::INFO) {
1262            if let Ok((hash, literals)) = canonicalize(&parsed.canonical_powql) {
1263                let hash = if crate::sql::statement_has_aggregate(&parsed.statement) {
1264                    sql_raw_cache_hash(hash)
1265                } else {
1266                    hash
1267                };
1268                let cached = self
1269                    .plan_cache
1270                    .lock()
1271                    .map_err(|e| QueryError::Execution(format!("plan cache lock poisoned: {e}")))?
1272                    .get_with_substitution(hash, &literals);
1273                if let Some(plan) = cached {
1274                    let plan = self.lower(&plan);
1275                    let result = self.execute_lowered(&plan);
1276                    if !self.in_transaction {
1277                        self.catalog
1278                            .commit_autocommit()
1279                            .map_err(|e| QueryError::StorageError(e.to_string()))?;
1280                    }
1281                    return result;
1282                }
1283
1284                let (raw, plan) = self.plan_and_lower_cacheable(parsed.statement)?;
1285                self.plan_cache
1286                    .lock()
1287                    .map_err(|e| QueryError::Execution(format!("plan cache lock poisoned: {e}")))?
1288                    .insert(hash, raw, literals.len());
1289                let result = self.execute_lowered(&plan);
1290                if !self.in_transaction {
1291                    self.catalog
1292                        .commit_autocommit()
1293                        .map_err(|e| QueryError::StorageError(e.to_string()))?;
1294                }
1295                return result;
1296            }
1297        }
1298
1299        let plan = self.plan_and_lower(parsed.statement)?;
1300        let result = self.execute_lowered(&plan);
1301        if !self.in_transaction {
1302            self.catalog
1303                .commit_autocommit()
1304                .map_err(|e| QueryError::StorageError(e.to_string()))?;
1305        }
1306        result
1307    }
1308
1309    /// Read-only variant of [`Engine::execute_sql`].
1310    pub fn execute_sql_readonly(&self, input: &str) -> Result<QueryResult, QueryError> {
1311        let _budget = self.enter_memory_budget();
1312        crate::cancel::check()?;
1313        let parsed = crate::sql::parse_sql_with_canonical(input)
1314            .map_err(|e| QueryError::Parse(e.to_string()))?;
1315        if !is_read_only_statement(&parsed.statement) {
1316            return Err(QueryError::ReadonlyNeedsWrite);
1317        }
1318
1319        if let Ok((hash, literals)) = canonicalize(&parsed.canonical_powql) {
1320            let hash = if crate::sql::statement_has_aggregate(&parsed.statement) {
1321                sql_raw_cache_hash(hash)
1322            } else {
1323                hash
1324            };
1325            let cached = self
1326                .plan_cache
1327                .lock()
1328                .map_err(|e| QueryError::Execution(format!("plan cache lock poisoned: {e}")))?
1329                .get_with_substitution(hash, &literals);
1330            if let Some(plan) = cached {
1331                let plan = self.lower(&plan);
1332                return self.execute_plan_readonly(&plan);
1333            }
1334            let (raw, plan) = self.plan_and_lower_cacheable(parsed.statement)?;
1335            self.plan_cache
1336                .lock()
1337                .map_err(|e| QueryError::Execution(format!("plan cache lock poisoned: {e}")))?
1338                .insert(hash, raw, literals.len());
1339            return self.execute_plan_readonly(&plan);
1340        }
1341
1342        let plan = self.plan_and_lower(parsed.statement)?;
1343        self.execute_plan_readonly(&plan)
1344    }
1345
1346    /// Execute PowQL with `$N` placeholders bound to positional `params`.
1347    ///
1348    /// Task 4: parameters are substituted as literal *tokens* before
1349    /// parsing (see [`crate::parser::parse_with_params`]), so untrusted
1350    /// input can never change the query's shape. This path deliberately
1351    /// **bypasses the plan cache** — template caching is a follow-up — and
1352    /// otherwise mirrors the non-cached tail of [`Engine::execute_powql`].
1353    pub fn execute_powql_with_params(
1354        &mut self,
1355        input: &str,
1356        params: &[crate::ast::ParamValue],
1357    ) -> Result<QueryResult, QueryError> {
1358        if self.read_only {
1359            return to_readonly_terminal(self.execute_powql_readonly_with_params(input, params));
1360        }
1361        let _budget = self.enter_memory_budget();
1362        crate::cancel::check()?;
1363        let stmt = crate::parser::parse_with_params(input, params)
1364            .map_err(|e| QueryError::Parse(e.to_string()))?;
1365        let plan = self.plan_and_lower(stmt)?;
1366        let result = self.execute_lowered(&plan);
1367        if !self.in_transaction {
1368            self.catalog
1369                .commit_autocommit()
1370                .map_err(|e| QueryError::StorageError(e.to_string()))?;
1371        }
1372        result
1373    }
1374
1375    /// Read-only variant of [`Engine::execute_powql_with_params`].
1376    ///
1377    /// Mirrors [`Engine::execute_powql_readonly`]: parses with bound
1378    /// params, rejects any write statement with
1379    /// [`QueryError::ReadonlyNeedsWrite`] so the caller can escalate to the
1380    /// write lock, then executes under a shared borrow. No plan-cache
1381    /// interaction.
1382    pub fn execute_powql_readonly_with_params(
1383        &self,
1384        input: &str,
1385        params: &[crate::ast::ParamValue],
1386    ) -> Result<QueryResult, QueryError> {
1387        let _budget = self.enter_memory_budget();
1388        crate::cancel::check()?;
1389        let stmt = crate::parser::parse_with_params(input, params)
1390            .map_err(|e| QueryError::Parse(e.to_string()))?;
1391        if !is_read_only_statement(&stmt) {
1392            return Err(QueryError::ReadonlyNeedsWrite);
1393        }
1394        let plan = self.plan_and_lower(stmt)?;
1395        self.execute_plan_readonly(&plan)
1396    }
1397
1398    /// Cancellation-aware variant of [`Engine::execute_powql`]. Installs
1399    /// `cancel` as the current thread's cancellation token for the duration of
1400    /// the statement, so cancellable read and mutation-target discovery loops
1401    /// poll it. Mutation application checks once before its first write, then
1402    /// finishes without polling because the engine has no statement savepoint
1403    /// with which to undo a written prefix. The base methods also honor an
1404    /// already installed token; a caller with no token (embedded/direct use)
1405    /// never cancels.
1406    pub fn execute_powql_with_cancel(
1407        &mut self,
1408        input: &str,
1409        cancel: Arc<crate::cancel::ExecCancel>,
1410    ) -> Result<QueryResult, QueryError> {
1411        let _cancel_guard = crate::cancel::install(cancel);
1412        self.execute_powql(input)
1413    }
1414
1415    /// Cancellation-aware variant of [`Engine::execute_sql`].
1416    pub fn execute_sql_with_cancel(
1417        &mut self,
1418        input: &str,
1419        cancel: Arc<crate::cancel::ExecCancel>,
1420    ) -> Result<QueryResult, QueryError> {
1421        let _cancel_guard = crate::cancel::install(cancel);
1422        self.execute_sql(input)
1423    }
1424
1425    /// Cancellation-aware variant of [`Engine::execute_powql_readonly`].
1426    pub fn execute_powql_readonly_with_cancel(
1427        &self,
1428        input: &str,
1429        cancel: Arc<crate::cancel::ExecCancel>,
1430    ) -> Result<QueryResult, QueryError> {
1431        let _cancel_guard = crate::cancel::install(cancel);
1432        self.execute_powql_readonly(input)
1433    }
1434
1435    /// Cancellation-aware variant of [`Engine::execute_sql_readonly`].
1436    pub fn execute_sql_readonly_with_cancel(
1437        &self,
1438        input: &str,
1439        cancel: Arc<crate::cancel::ExecCancel>,
1440    ) -> Result<QueryResult, QueryError> {
1441        let _cancel_guard = crate::cancel::install(cancel);
1442        self.execute_sql_readonly(input)
1443    }
1444
1445    /// Cancellation-aware variant of [`Engine::execute_powql_with_params`].
1446    pub fn execute_powql_with_params_and_cancel(
1447        &mut self,
1448        input: &str,
1449        params: &[crate::ast::ParamValue],
1450        cancel: Arc<crate::cancel::ExecCancel>,
1451    ) -> Result<QueryResult, QueryError> {
1452        let _cancel_guard = crate::cancel::install(cancel);
1453        self.execute_powql_with_params(input, params)
1454    }
1455
1456    /// Cancellation-aware variant of [`Engine::execute_powql_readonly_with_params`].
1457    pub fn execute_powql_readonly_with_params_and_cancel(
1458        &self,
1459        input: &str,
1460        params: &[crate::ast::ParamValue],
1461        cancel: Arc<crate::cancel::ExecCancel>,
1462    ) -> Result<QueryResult, QueryError> {
1463        let _cancel_guard = crate::cancel::install(cancel);
1464        self.execute_powql_readonly_with_params(input, params)
1465    }
1466
1467    /// Plan cache stats — useful for benches and debugging.
1468    pub fn plan_cache_stats(&self) -> (u64, u64, usize) {
1469        let cache = self.plan_cache.lock().unwrap_or_else(|e| e.into_inner());
1470        (cache.hits, cache.misses, cache.len())
1471    }
1472
1473    /// Mission infra-1: read-only entry point.
1474    ///
1475    /// Parses + plans + executes a PowQL query using only a shared borrow
1476    /// on the engine. Rejects any statement that would mutate state
1477    /// (Insert/Update/Delete/CreateTable/AlterTable/DropTable/CreateView/
1478    /// RefreshView/DropView) by returning [`READONLY_NEEDS_WRITE`] so the
1479    /// caller can escalate to the write lock.
1480    ///
1481    /// Also returns [`READONLY_NEEDS_WRITE`] if a materialized view in the
1482    /// query is dirty — refreshing one requires `&mut self`, so the caller
1483    /// must retake the write lock for the first refresh.
1484    ///
1485    /// This method is the concurrent-read fast path behind
1486    /// `Arc<RwLock<Engine>>`: multiple threads can call it simultaneously
1487    /// under a shared `.read()` lock and each will scan independently.
1488    pub fn execute_powql_readonly(&self, input: &str) -> Result<QueryResult, QueryError> {
1489        // WS2: each *outermost* statement starts with the full memory
1490        // allowance. The guard holds the reentrancy depth so a nested
1491        // `execute_powql*` does not reset the outer frame's accounting.
1492        let _budget = self.enter_memory_budget();
1493        crate::cancel::check()?;
1494        // Parse the statement first so we can classify read vs. write
1495        // without touching the catalog. This is the same lex+parse cost
1496        // the hot path would pay anyway.
1497        let stmt = crate::parser::parse(input).map_err(|e| QueryError::Parse(e.to_string()))?;
1498        if !is_read_only_statement(&stmt) {
1499            return Err(QueryError::ReadonlyNeedsWrite);
1500        }
1501
1502        // Try the plan cache first — identical hash scheme to
1503        // `execute_powql` so both paths share cache state. The mutex
1504        // section is just a hashmap lookup + plan clone.
1505        if let Ok((hash, literals)) = canonicalize(input) {
1506            let cached = self
1507                .plan_cache
1508                .lock()
1509                .map_err(|e| QueryError::Execution(format!("plan cache lock poisoned: {e}")))?
1510                .get_with_substitution(hash, &literals);
1511            if let Some(plan) = cached {
1512                let plan = self.lower(&plan);
1513                return self.execute_plan_readonly(&plan);
1514            }
1515            // Miss: plan + insert + execute. The planner is pure, so this
1516            // is safe from `&self`.
1517            let (raw, plan) = self.plan_and_lower_cacheable(stmt)?;
1518            self.plan_cache
1519                .lock()
1520                .map_err(|e| QueryError::Execution(format!("plan cache lock poisoned: {e}")))?
1521                .insert(hash, raw, literals.len());
1522            return self.execute_plan_readonly(&plan);
1523        }
1524        // Lex error — fall through to the planner for a consistent error
1525        // shape (though `parse` above would usually have caught it).
1526        let plan = self.plan_and_lower(stmt)?;
1527        self.execute_plan_readonly(&plan)
1528    }
1529
1530    /// Read-only version of [`Engine::execute_plan`]. Dispatches the
1531    /// read-path plan variants by calling `&self` helpers and errors with
1532    /// [`READONLY_NEEDS_WRITE`] on any write variant. This is the
1533    /// recursion target for composite read plans under the RwLock reader.
1534    ///
1535    /// The dispatch mirrors `execute_plan` for the read branches but does
1536    /// not carry any of the fast-paths that need `&mut self` (e.g. plan-
1537    /// cache mutation on inner subqueries is handled via the shared mutex
1538    /// in [`Engine::execute_powql_readonly`]; in-flight subquery
1539    /// materialisation uses [`Engine::materialize_subqueries_readonly`]).
1540    fn execute_plan_readonly(&self, plan: &LoweredPlan) -> Result<QueryResult, QueryError> {
1541        self.dispatch_readonly(plan.node())
1542    }
1543
1544    /// The read-path dispatch itself. Takes a bare `&PlanNode` because it is
1545    /// the recursion target: every child of a lowered plan is lowered, so a
1546    /// subtree needs no second wrapper. Reaching it from outside an already
1547    /// lowered tree is what [`Engine::execute_plan_readonly`] exists to
1548    /// prevent, which is why this one is private and unlowered plans cannot
1549    /// name it.
1550    fn dispatch_readonly(&self, plan: &PlanNode) -> Result<QueryResult, QueryError> {
1551        // Detect every dirty materialized-view source before executing any
1552        // branch of the plan. Without this preflight, a join could fully scan
1553        // its clean left input before discovering a dirty right input, then
1554        // repeat that work after the server upgrades to writer admission.
1555        // Alias scans also need this centralized check: they do not pass
1556        // through the SeqScan arm below.
1557        if plan_reads_dirty_view(plan, &self.view_registry) {
1558            return Err(QueryError::ReadonlyNeedsWrite);
1559        }
1560        // Mirror the mutable path: reject a stray aggregate FunctionCall before
1561        // evaluating any row (see execute_plan for the rationale).
1562        validate_no_stray_aggregates(plan)?;
1563        validate_json_path_types(&self.catalog, plan)?;
1564        validate_column_references(&self.catalog, plan)?;
1565        validate_slice_counts(plan)?;
1566        match plan {
1567            PlanNode::ExprIndexScan { .. }
1568            | PlanNode::ExprRangeScan { .. }
1569            | PlanNode::OrderedExprIndexScan { .. } => {
1570                if let Some(result) = self.execute_expression_index_plan(plan, None)? {
1571                    return Ok(result);
1572                }
1573                let fallback = self.lower(plan);
1574                self.execute_plan_readonly(&fallback)
1575            }
1576            PlanNode::SeqScan { table } => {
1577                // Dirty view means we'd need to refresh it — can't do that
1578                // under `&self`. Escalate to the write path.
1579                if self.view_registry.is_dirty(table) {
1580                    return Err(QueryError::ReadonlyNeedsWrite);
1581                }
1582                let schema = self
1583                    .catalog
1584                    .schema(table)
1585                    .ok_or_else(|| QueryError::TableNotFound(table.clone()))?
1586                    .clone();
1587                let columns: Vec<String> = schema.columns.iter().map(|c| c.name.clone()).collect();
1588                // Cooperative cancellation: a full-table scan of a huge table
1589                // must stay stoppable.
1590                let mut cancel = crate::cancel::CancelCheck::new();
1591                let mut rows: Vec<Vec<Value>> = Vec::new();
1592                for (_, row) in self.catalog.scan(table).map_err(|e| e.to_string())? {
1593                    cancel.tick()?;
1594                    rows.push(row);
1595                }
1596                Ok(QueryResult::Rows { columns, rows })
1597            }
1598
1599            PlanNode::AliasScan { table, alias } => {
1600                let schema = self
1601                    .catalog
1602                    .schema(table)
1603                    .ok_or_else(|| QueryError::TableNotFound(table.clone()))?
1604                    .clone();
1605                let columns: Vec<String> = schema
1606                    .columns
1607                    .iter()
1608                    .map(|c| format!("{alias}.{}", c.name))
1609                    .collect();
1610                let mut cancel = crate::cancel::CancelCheck::new();
1611                let mut rows: Vec<Vec<Value>> = Vec::new();
1612                for (_, row) in self.catalog.scan(table).map_err(|e| e.to_string())? {
1613                    cancel.tick()?;
1614                    rows.push(row);
1615                }
1616                Ok(QueryResult::Rows { columns, rows })
1617            }
1618
1619            PlanNode::NestedProject { input, fields } => {
1620                // Dirty child views were escalated by the preflight above;
1621                // the assembly itself only reads.
1622                // Resolve link traversals against the persistent catalog before
1623                // assembly (like the mutable dispatch), so child tables and
1624                // scalar hop chains are concrete.
1625                let resolved;
1626                let fields: &[crate::plan::NestedProjectField] =
1627                    if plan_exec::nested_fields_have_via_link(fields) {
1628                        let outer = plan_exec::scan_source_table(input).ok_or_else(|| {
1629                            QueryError::Execution(
1630                                "link traversal requires a plain aliased table scan as its parent"
1631                                    .into(),
1632                            )
1633                        })?;
1634                        resolved = self.resolve_nested_via_links(fields, outer)?;
1635                        &resolved
1636                    } else {
1637                        fields
1638                    };
1639                let parent = self.dispatch_readonly(input)?;
1640                self.execute_nested_project(parent, fields)
1641            }
1642
1643            PlanNode::IndexScan { table, column, key } => {
1644                let schema = self
1645                    .catalog
1646                    .schema(table)
1647                    .ok_or_else(|| QueryError::TableNotFound(table.clone()))?
1648                    .clone();
1649                let columns: Vec<String> = schema.columns.iter().map(|c| c.name.clone()).collect();
1650                let key_value = literal_to_value(key)?;
1651                let tbl = self
1652                    .catalog
1653                    .get_table(table)
1654                    .ok_or_else(|| QueryError::TableNotFound(table.clone()))?;
1655
1656                if tbl.has_index(column) {
1657                    // Use index_lookup_all to handle both unique and
1658                    // non-unique indexes — returns all matching RowIds.
1659                    let rids = tbl.index_lookup_all(column, &key_value);
1660                    let mut rows: Vec<Vec<Value>> = Vec::with_capacity(rids.len());
1661                    let mut cancel = crate::cancel::CancelCheck::new();
1662                    for rid in rids {
1663                        cancel.tick()?;
1664                        // Overflow safety (P0-3/P0-4): `tbl.get` reassembles
1665                        // spilled columns (the old `heap.get` + `decode_row`
1666                        // returned Empty / wrapped a >= 64KB value).
1667                        if let Some(row) = tbl.get(rid) {
1668                            rows.push(row);
1669                        }
1670                    }
1671                    return Ok(QueryResult::Rows { columns, rows });
1672                }
1673
1674                // No index: synthetic eq predicate + compiled scan.
1675                // Overflow safety (P0-4/P1): v2-capable tables use the decoded
1676                // last-resort scan below (raw scan drops/mis-reads spilled cols).
1677                let fast = FastLayout::new(&schema);
1678                let synth_pred = Expr::BinaryOp(
1679                    Box::new(Expr::Field(column.clone())),
1680                    BinOp::Eq,
1681                    Box::new(key.clone()),
1682                );
1683                if !tbl.has_overflow_rows() {
1684                    if let Some(compiled) = self.compile_predicate_unless_forced(
1685                        "readonly:index-scan-scan-fallback:predicate",
1686                        &synth_pred,
1687                        &columns,
1688                        &fast,
1689                        &schema,
1690                    ) {
1691                        let mut rows: Vec<Vec<Value>> = Vec::with_capacity(64);
1692                        for_each_row_raw_cancellable(&self.catalog, table, |_rid, data| {
1693                            if compiled(data) {
1694                                rows.push(decode_row(&schema, data));
1695                            }
1696                        })?;
1697                        return Ok(QueryResult::Rows { columns, rows });
1698                    }
1699                }
1700
1701                // Last resort: slow eq-check.
1702                let col_idx =
1703                    schema
1704                        .column_index(column)
1705                        .ok_or_else(|| QueryError::ColumnNotFound {
1706                            table: String::new(),
1707                            column: column.clone(),
1708                        })?;
1709                let mut cancel = crate::cancel::CancelCheck::new();
1710                let mut rows: Vec<Vec<Value>> = Vec::new();
1711                for (_, row) in tbl.scan() {
1712                    cancel.tick()?;
1713                    if row[col_idx] == key_value {
1714                        rows.push(row);
1715                    }
1716                }
1717                Ok(QueryResult::Rows { columns, rows })
1718            }
1719
1720            PlanNode::RangeScan {
1721                table,
1722                column,
1723                start,
1724                end,
1725            } => {
1726                let tbl = self
1727                    .catalog
1728                    .get_table(table)
1729                    .ok_or_else(|| QueryError::TableNotFound(table.clone()))?;
1730                let columns: Vec<String> = tbl
1731                    .schema()
1732                    .columns
1733                    .iter()
1734                    .map(|c| c.name.clone())
1735                    .collect();
1736                let schema = tbl.schema().clone();
1737
1738                let start_val = match start {
1739                    Some((expr, _)) => Some(literal_to_value(expr)?),
1740                    None => None,
1741                };
1742                let end_val = match end {
1743                    Some((expr, _)) => Some(literal_to_value(expr)?),
1744                    None => None,
1745                };
1746                let start_inclusive = start.as_ref().map(|(_, inc)| *inc).unwrap_or(true);
1747                let end_inclusive = end.as_ref().map(|(_, inc)| *inc).unwrap_or(true);
1748
1749                // Range scans only use the btree fast path for unique indexes.
1750                // Non-unique indexes store composite keys that don't compare
1751                // directly against raw column values.
1752                if tbl.is_index_unique(column) == Some(true) {
1753                    if let Some(btree) = tbl.index(column) {
1754                        let hits: Vec<(Value, RowId)> = match (&start_val, &end_val) {
1755                            (Some(s), Some(e)) => btree.range(s, e).collect(),
1756                            (Some(s), None) => btree.range_from(s),
1757                            (None, Some(e)) => btree.range_to(e),
1758                            (None, None) => {
1759                                // Unbounded both sides — equivalent to seq scan.
1760                                let mut cancel = crate::cancel::CancelCheck::new();
1761                                let mut rows: Vec<Vec<Value>> = Vec::new();
1762                                for (_, row) in tbl.scan() {
1763                                    cancel.tick()?;
1764                                    rows.push(row);
1765                                }
1766                                return Ok(QueryResult::Rows { columns, rows });
1767                            }
1768                        };
1769                        let mut rows: Vec<Vec<Value>> = Vec::with_capacity(hits.len());
1770                        let mut cancel = crate::cancel::CancelCheck::new();
1771                        for (key, rid) in hits {
1772                            cancel.tick()?;
1773                            // Filter for exclusive bounds.
1774                            if !start_inclusive {
1775                                if let Some(ref s) = start_val {
1776                                    if &key == s {
1777                                        continue;
1778                                    }
1779                                }
1780                            }
1781                            if !end_inclusive {
1782                                if let Some(ref e) = end_val {
1783                                    if &key == e {
1784                                        continue;
1785                                    }
1786                                }
1787                            }
1788                            // Overflow safety (P0-3): reassemble spilled cols.
1789                            if let Some(row) = tbl.get(rid) {
1790                                rows.push(row);
1791                            }
1792                        }
1793                        return Ok(QueryResult::Rows { columns, rows });
1794                    }
1795                }
1796
1797                // Fallback: no index — synthesize the range predicate and scan.
1798                // Overflow safety (P0-4): v2-capable tables use the decoded
1799                // last-resort scan below.
1800                let fast = FastLayout::new(&schema);
1801                let synth = synthesize_range_predicate(column, start, end);
1802                if !tbl.has_overflow_rows() {
1803                    if let Some(compiled) = self.compile_predicate_unless_forced(
1804                        "readonly:range-scan-scan-fallback:predicate",
1805                        &synth,
1806                        &columns,
1807                        &fast,
1808                        &schema,
1809                    ) {
1810                        let mut rows: Vec<Vec<Value>> = Vec::with_capacity(64);
1811                        for_each_row_raw_cancellable(&self.catalog, table, |_rid, data| {
1812                            if compiled(data) {
1813                                rows.push(decode_row(&schema, data));
1814                            }
1815                        })?;
1816                        return Ok(QueryResult::Rows { columns, rows });
1817                    }
1818                }
1819
1820                // Last resort: decoded row eval.
1821                let col_idx =
1822                    schema
1823                        .column_index(column)
1824                        .ok_or_else(|| QueryError::ColumnNotFound {
1825                            table: String::new(),
1826                            column: column.clone(),
1827                        })?;
1828                let mut cancel = crate::cancel::CancelCheck::new();
1829                let mut rows: Vec<Vec<Value>> = Vec::new();
1830                for (_, row) in tbl.scan() {
1831                    cancel.tick()?;
1832                    if range_matches(
1833                        &row[col_idx],
1834                        &start_val,
1835                        start_inclusive,
1836                        &end_val,
1837                        end_inclusive,
1838                    ) {
1839                        rows.push(row);
1840                    }
1841                }
1842                Ok(QueryResult::Rows { columns, rows })
1843            }
1844
1845            PlanNode::Filter { input, predicate } => {
1846                // Materialise subqueries using the `&self` variant.
1847                // Uncorrelated subqueries are replaced with InList/Bool;
1848                // correlated ones are left as InSubquery/ExistsSubquery
1849                // for per-row materialisation below.
1850                let materialized;
1851                let predicate = if contains_subquery(predicate) {
1852                    materialized = self.materialize_subqueries_readonly(predicate)?;
1853                    &materialized
1854                } else {
1855                    predicate
1856                };
1857
1858                // Correlated subquery path: per-row materialisation.
1859                if contains_subquery(predicate) {
1860                    let result = self.dispatch_readonly(input)?;
1861                    return match result {
1862                        QueryResult::Rows { columns, rows } => {
1863                            let mut filtered = Vec::new();
1864                            // Cooperative cancellation: this runs a subquery per
1865                            // outer row, so a large outer scan must stay stoppable.
1866                            let mut cancel = crate::cancel::CancelCheck::new();
1867                            for row in rows {
1868                                cancel.tick()?;
1869                                let row_pred = self.materialize_correlated_for_row_readonly(
1870                                    predicate, &row, &columns,
1871                                )?;
1872                                if eval_predicate(&row_pred, &row, &columns) {
1873                                    filtered.push(row);
1874                                }
1875                            }
1876                            Ok(QueryResult::Rows {
1877                                columns,
1878                                rows: filtered,
1879                            })
1880                        }
1881                        _ => Err("filter requires row input".into()),
1882                    };
1883                }
1884
1885                // Lane A fast path: Filter over an equality-driven index scan
1886                // (mirrors the mutable path). Pure `&self`, so it is shared.
1887                if matches!(
1888                    input.as_ref(),
1889                    PlanNode::IndexScan { .. } | PlanNode::ExprIndexScan { .. }
1890                ) {
1891                    if let Some(result) = self.try_filter_index_residual_fast(input, predicate)? {
1892                        return Ok(result);
1893                    }
1894                }
1895
1896                // Fused Filter+SeqScan fast path.
1897                // Overflow safety (P0-4/P1): v2-capable tables fall through to
1898                // the decoded general path below.
1899                if let PlanNode::SeqScan { table } = input.as_ref() {
1900                    if !self.catalog.table_has_overflow(table)
1901                        && !self.generic_path_forced("readonly:filter-seqscan-raw")
1902                    {
1903                        if self.view_registry.is_dirty(table) {
1904                            return Err(QueryError::ReadonlyNeedsWrite);
1905                        }
1906                        let schema = self
1907                            .catalog
1908                            .schema(table)
1909                            .ok_or_else(|| QueryError::TableNotFound(table.clone()))?
1910                            .clone();
1911                        let columns: Vec<String> =
1912                            schema.columns.iter().map(|c| c.name.clone()).collect();
1913                        let fast = FastLayout::new(&schema);
1914                        let row_layout = RowLayout::new(&schema);
1915                        let mut rows: Vec<Vec<Value>> = Vec::with_capacity(64);
1916
1917                        // Cooperative cancellation: full-table compiled/selective
1918                        // predicate scan must stay stoppable (see the write-path
1919                        // Filter fast path for the same pattern).
1920                        let mut cancel = crate::cancel::CancelCheck::new();
1921                        let mut cancel_err: Option<QueryError> = None;
1922                        if let Some(compiled) = self.compile_predicate_unless_forced(
1923                            "readonly:filter-seqscan:predicate",
1924                            predicate,
1925                            &columns,
1926                            &fast,
1927                            &schema,
1928                        ) {
1929                            self.catalog
1930                                .try_for_each_row_raw(table, |_rid, data| {
1931                                    if let Err(e) = cancel.tick() {
1932                                        cancel_err = Some(e);
1933                                        return std::ops::ControlFlow::Break(());
1934                                    }
1935                                    if compiled(data) {
1936                                        rows.push(decode_row(&schema, data));
1937                                    }
1938                                    std::ops::ControlFlow::Continue(())
1939                                })
1940                                .map_err(|e| QueryError::StorageError(e.to_string()))?;
1941                        } else {
1942                            let pred_cols = predicate_column_indices_json(predicate, &columns);
1943                            self.catalog
1944                                .try_for_each_row_raw(table, |_rid, data| {
1945                                    if let Err(e) = cancel.tick() {
1946                                        cancel_err = Some(e);
1947                                        return std::ops::ControlFlow::Break(());
1948                                    }
1949                                    let pred_row =
1950                                        decode_selective(&schema, &row_layout, data, &pred_cols);
1951                                    if eval_predicate(predicate, &pred_row, &columns) {
1952                                        rows.push(decode_row(&schema, data));
1953                                    }
1954                                    std::ops::ControlFlow::Continue(())
1955                                })
1956                                .map_err(|e| QueryError::StorageError(e.to_string()))?;
1957                        }
1958                        if let Some(e) = cancel_err {
1959                            return Err(e);
1960                        }
1961
1962                        return Ok(QueryResult::Rows { columns, rows });
1963                    }
1964                }
1965
1966                // General path.
1967                let result = self.dispatch_readonly(input)?;
1968                match result {
1969                    QueryResult::Rows { columns, rows } => {
1970                        let mut cancel = crate::cancel::CancelCheck::new();
1971                        let mut filtered: Vec<Vec<Value>> = Vec::new();
1972                        for row in rows {
1973                            cancel.tick()?;
1974                            if eval_predicate(predicate, &row, &columns) {
1975                                filtered.push(row);
1976                            }
1977                        }
1978                        Ok(QueryResult::Rows {
1979                            columns,
1980                            rows: filtered,
1981                        })
1982                    }
1983                    _ => Err("filter requires row input".into()),
1984                }
1985            }
1986
1987            PlanNode::Project { input, fields } => {
1988                if matches!(
1989                    input.as_ref(),
1990                    PlanNode::ExprIndexScan { .. }
1991                        | PlanNode::ExprRangeScan { .. }
1992                        | PlanNode::OrderedExprIndexScan { .. }
1993                ) {
1994                    if let Some(result) = self.execute_expression_index_plan(input, Some(fields))? {
1995                        return Ok(result);
1996                    }
1997                }
1998                // Fast path: Project over IndexScan. Avoids full-row decode
1999                // by calling decode_column only for projected fields.
2000                if let PlanNode::IndexScan { table, column, key } = input.as_ref() {
2001                    let key_value = literal_to_value(key)?;
2002                    let tbl = self
2003                        .catalog
2004                        .get_table(table)
2005                        .ok_or_else(|| QueryError::TableNotFound(table.clone()))?;
2006                    let schema = tbl.schema();
2007
2008                    let proj_columns: Vec<String> = fields
2009                        .iter()
2010                        .map(|f| {
2011                            f.alias.clone().unwrap_or_else(|| match &f.expr {
2012                                Expr::Field(name) => name.clone(),
2013                                _ => "?".into(),
2014                            })
2015                        })
2016                        .collect();
2017
2018                    let proj_indices: Vec<usize> = fields
2019                        .iter()
2020                        .filter_map(|f| {
2021                            if let Expr::Field(name) = &f.expr {
2022                                schema.column_index(name)
2023                            } else {
2024                                None
2025                            }
2026                        })
2027                        .collect();
2028
2029                    // Plain-field projections only; a computed projection
2030                    // (e.g. `length(.v)`) falls through to the generic
2031                    // expression-evaluating path (its column is otherwise
2032                    // dropped — proj_indices only collects Fields).
2033                    let all_plain_fields = fields.iter().all(|f| matches!(f.expr, Expr::Field(_)));
2034                    if tbl.has_index(column)
2035                        && all_plain_fields
2036                        && !self.generic_path_forced("readonly:project-over-index-scan")
2037                    {
2038                        let rids = tbl.index_lookup_all(column, &key_value);
2039                        let mut rows: Vec<Vec<Value>> = Vec::with_capacity(rids.len());
2040                        let mut cancel = crate::cancel::CancelCheck::new();
2041                        for rid in rids {
2042                            cancel.tick()?;
2043                            // Overflow safety (P0-3/P0-4): reassemble via
2044                            // `tbl.get` so spilled projected columns return
2045                            // their value, not Empty / a wrapped >= 64KB blob.
2046                            if let Some(full) = tbl.get(rid) {
2047                                let row: Vec<Value> =
2048                                    proj_indices.iter().map(|&ci| full[ci].clone()).collect();
2049                                rows.push(row);
2050                            }
2051                        }
2052                        return Ok(QueryResult::Rows {
2053                            columns: proj_columns,
2054                            rows,
2055                        });
2056                    }
2057                }
2058
2059                // Fast paths over Limit(Sort(...)) / Limit(Filter(...)) / Limit(SeqScan).
2060                if let PlanNode::Limit {
2061                    input: inner,
2062                    count: limit_expr,
2063                } = input.as_ref()
2064                {
2065                    if let PlanNode::Sort {
2066                        input: sort_input,
2067                        keys,
2068                    } = inner.as_ref()
2069                    {
2070                        if keys.len() == 1 {
2071                            if let (Expr::Field(sort_field), Some(limit)) =
2072                                (&keys[0].expr, literal_limit(limit_expr))
2073                            {
2074                                let descending = keys[0].descending;
2075                                let (table_opt, pred_opt): (Option<&str>, Option<&Expr>) =
2076                                    match sort_input.as_ref() {
2077                                        PlanNode::SeqScan { table } => (Some(table.as_str()), None),
2078                                        PlanNode::Filter {
2079                                            input: fi,
2080                                            predicate,
2081                                        } => {
2082                                            if let PlanNode::SeqScan { table } = fi.as_ref() {
2083                                                (Some(table.as_str()), Some(predicate))
2084                                            } else {
2085                                                (None, None)
2086                                            }
2087                                        }
2088                                        _ => (None, None),
2089                                    };
2090                                if let Some(table) = table_opt {
2091                                    if let Some(result) = self.project_filter_sort_limit_fast(
2092                                        table, fields, sort_field, descending, limit, pred_opt,
2093                                    )? {
2094                                        return Ok(result);
2095                                    }
2096                                }
2097                            }
2098                        }
2099                    }
2100                    if let PlanNode::Filter {
2101                        input: fi,
2102                        predicate,
2103                    } = inner.as_ref()
2104                    {
2105                        if let (PlanNode::SeqScan { table }, Some(limit)) =
2106                            (fi.as_ref(), literal_limit(limit_expr))
2107                        {
2108                            if let Some(result) = self.project_filter_limit_fast(
2109                                table,
2110                                fields,
2111                                limit,
2112                                Some(predicate),
2113                            )? {
2114                                return Ok(result);
2115                            }
2116                        }
2117                    }
2118                    if let (PlanNode::SeqScan { table }, Some(limit)) =
2119                        (inner.as_ref(), literal_limit(limit_expr))
2120                    {
2121                        if let Some(result) =
2122                            self.project_filter_limit_fast(table, fields, limit, None)?
2123                        {
2124                            return Ok(result);
2125                        }
2126                    }
2127                }
2128
2129                // Project(Filter(SeqScan)) without Limit.
2130                if let PlanNode::Filter {
2131                    input: fi,
2132                    predicate,
2133                } = input.as_ref()
2134                {
2135                    if let PlanNode::SeqScan { table } = fi.as_ref() {
2136                        if let Some(result) = self.project_filter_limit_fast(
2137                            table,
2138                            fields,
2139                            usize::MAX,
2140                            Some(predicate),
2141                        )? {
2142                            return Ok(result);
2143                        }
2144                    }
2145                }
2146
2147                // Project(SeqScan) without Filter or Limit.
2148                if let PlanNode::SeqScan { table } = input.as_ref() {
2149                    if let Some(result) =
2150                        self.project_filter_limit_fast(table, fields, usize::MAX, None)?
2151                    {
2152                        return Ok(result);
2153                    }
2154                }
2155
2156                // Generic path.
2157                let result = self.dispatch_readonly(input)?;
2158                match result {
2159                    QueryResult::Rows { columns, rows } => {
2160                        let proj_columns: Vec<String> = fields
2161                            .iter()
2162                            .map(|f| {
2163                                f.alias.clone().unwrap_or_else(|| match &f.expr {
2164                                    Expr::Field(name) => name.clone(),
2165                                    Expr::QualifiedField { qualifier, field } => {
2166                                        format!("{qualifier}.{field}")
2167                                    }
2168                                    _ => "?".into(),
2169                                })
2170                            })
2171                            .collect();
2172                        let mut cancel = crate::cancel::CancelCheck::new();
2173                        let mut proj_rows: Vec<Vec<Value>> = Vec::with_capacity(rows.len());
2174                        for row in &rows {
2175                            cancel.tick()?;
2176                            proj_rows.push(
2177                                fields
2178                                    .iter()
2179                                    .map(|f| eval_expr(&f.expr, row, &columns))
2180                                    .collect(),
2181                            );
2182                        }
2183                        Ok(QueryResult::Rows {
2184                            columns: proj_columns,
2185                            rows: proj_rows,
2186                        })
2187                    }
2188                    _ => Err("project requires row input".into()),
2189                }
2190            }
2191
2192            PlanNode::Sort { input, keys } => {
2193                let result = self.dispatch_readonly(input)?;
2194                match result {
2195                    QueryResult::Rows { columns, mut rows } => {
2196                        if rows.len() > MAX_SORT_ROWS {
2197                            return Err(QueryError::SortLimitExceeded);
2198                        }
2199                        // WS2: byte-budget guard on the sort buffer.
2200                        self.charge_rows(&rows)?;
2201                        let key_specs: Vec<(Option<usize>, &Expr, bool)> = keys
2202                            .iter()
2203                            .map(|k| {
2204                                let stored_name = match &k.expr {
2205                                    Expr::Field(name) => Some(name.clone()),
2206                                    Expr::QualifiedField { qualifier, field } => {
2207                                        Some(format!("{qualifier}.{field}"))
2208                                    }
2209                                    _ => None,
2210                                };
2211                                // Same resolver the read-write sort path and
2212                                // every other clause use, so the readonly path
2213                                // does not disagree with them about whether
2214                                // `order .amount` inside a join names a column.
2215                                let index = stored_name
2216                                    .as_ref()
2217                                    .and_then(|name| resolve_column_index(name, &columns));
2218                                if let Some(name) = stored_name {
2219                                    if index.is_none() {
2220                                        return Err(QueryError::ColumnNotFound {
2221                                            table: String::new(),
2222                                            column: name,
2223                                        });
2224                                    }
2225                                }
2226                                Ok((index, &k.expr, k.descending))
2227                            })
2228                            .collect::<Result<_, QueryError>>()?;
2229                        cooperative_stable_sort_by(&mut rows, self.query_memory_limit, |a, b| {
2230                            for &(col_idx, expr, descending) in &key_specs {
2231                                let (left_value, right_value) = match col_idx {
2232                                    Some(index) => (&a[index], &b[index]),
2233                                    None => {
2234                                        let left = eval_expr(expr, a, &columns);
2235                                        let right = eval_expr(expr, b, &columns);
2236                                        let cmp = compare_order_values(&left, &right, descending);
2237                                        if cmp != std::cmp::Ordering::Equal {
2238                                            return cmp;
2239                                        }
2240                                        continue;
2241                                    }
2242                                };
2243                                let cmp = compare_order_values(left_value, right_value, descending);
2244                                if cmp != std::cmp::Ordering::Equal {
2245                                    return cmp;
2246                                }
2247                            }
2248                            std::cmp::Ordering::Equal
2249                        })?;
2250                        Ok(QueryResult::Rows { columns, rows })
2251                    }
2252                    _ => Err("sort requires row input".into()),
2253                }
2254            }
2255
2256            PlanNode::Limit { input, count } => {
2257                let result = self.dispatch_readonly(input)?;
2258                let n = match count {
2259                    Expr::Literal(Literal::Int(v)) => *v as usize,
2260                    _ => return Err("limit must be integer literal".into()),
2261                };
2262                match result {
2263                    QueryResult::Rows { columns, rows } => {
2264                        let mut cancel = crate::cancel::CancelCheck::new();
2265                        let mut limited = Vec::with_capacity(n.min(rows.len()));
2266                        for row in rows.into_iter().take(n) {
2267                            cancel.tick()?;
2268                            limited.push(row);
2269                        }
2270                        Ok(QueryResult::Rows {
2271                            columns,
2272                            rows: limited,
2273                        })
2274                    }
2275                    _ => Err("limit requires row input".into()),
2276                }
2277            }
2278
2279            PlanNode::Offset { input, count } => {
2280                let result = self.dispatch_readonly(input)?;
2281                let n = match count {
2282                    Expr::Literal(Literal::Int(v)) => *v as usize,
2283                    _ => return Err("offset must be integer literal".into()),
2284                };
2285                match result {
2286                    QueryResult::Rows { columns, rows } => {
2287                        let mut cancel = crate::cancel::CancelCheck::new();
2288                        let mut offset = Vec::with_capacity(rows.len().saturating_sub(n));
2289                        for (index, row) in rows.into_iter().enumerate() {
2290                            cancel.tick()?;
2291                            if index >= n {
2292                                offset.push(row);
2293                            }
2294                        }
2295                        Ok(QueryResult::Rows {
2296                            columns,
2297                            rows: offset,
2298                        })
2299                    }
2300                    _ => Err("offset requires row input".into()),
2301                }
2302            }
2303
2304            PlanNode::Aggregate {
2305                input,
2306                function,
2307                argument,
2308                mode: _,
2309                provenance_alias,
2310            } => {
2311                if let Some(provenance_alias) = provenance_alias {
2312                    let input = self.materialize_rows_with_provenance(input)?;
2313                    self.charge_rows(&input.rows)?;
2314                    return aggregate_rows_with_provenance(
2315                        *function,
2316                        argument.as_ref(),
2317                        &input,
2318                        provenance_alias,
2319                        self.query_memory_limit,
2320                    );
2321                }
2322                // Fast path: count() over SeqScan.
2323                // Overflow safety (P0-4): v2-capable tables use the decoded
2324                // generic path (raw count drops >= 64KB rows). A count with a
2325                // target column (`count(T { .v })`) counts non-null values, so
2326                // it must not take this row-counting path.
2327                if *function == AggFunc::Count
2328                    && counts_every_row(argument.as_ref())
2329                    && !self.generic_path_forced("readonly:count-fast-block")
2330                {
2331                    if let PlanNode::SeqScan { table } = input.as_ref() {
2332                        if !self.catalog.table_has_overflow(table) {
2333                            // A dirty materialized view must be refreshed before
2334                            // it can be counted, which needs `&mut self`. Escalate
2335                            // to the write path (F3: count(View) returned stale).
2336                            if self.view_registry.is_dirty(table) {
2337                                return Err(QueryError::ReadonlyNeedsWrite);
2338                            }
2339                            let mut count: i64 = 0;
2340                            for_each_row_raw_cancellable(&self.catalog, table, |_rid, _data| {
2341                                count += 1;
2342                            })?;
2343                            return Ok(QueryResult::Scalar(Value::Int(count)));
2344                        }
2345                    }
2346                    if let PlanNode::Filter {
2347                        input: inner,
2348                        predicate,
2349                    } = input.as_ref()
2350                    {
2351                        // Only take the fast path for a plain Filter(SeqScan)
2352                        // with no subquery in the predicate. A subquery
2353                        // predicate (`count(T filter .x in (...))`) must be
2354                        // resolved first; the fast path evaluates the raw
2355                        // predicate with no subquery materialisation, which
2356                        // silently yields 0 (F1). Falling through routes it to
2357                        // the generic path that runs the subquery correctly.
2358                        if let PlanNode::SeqScan { table } = inner.as_ref() {
2359                            if self.view_registry.is_dirty(table) {
2360                                // F3: count(View filter ...) over a dirty view.
2361                                return Err(QueryError::ReadonlyNeedsWrite);
2362                            }
2363                        }
2364                        if let (PlanNode::SeqScan { table }, false) =
2365                            (inner.as_ref(), contains_subquery(predicate))
2366                        {
2367                            if !self.catalog.table_has_overflow(table) {
2368                                let schema = self
2369                                    .catalog
2370                                    .schema(table)
2371                                    .ok_or_else(|| QueryError::TableNotFound(table.clone()))?
2372                                    .clone();
2373                                let columns: Vec<String> =
2374                                    schema.columns.iter().map(|c| c.name.clone()).collect();
2375                                let fast = FastLayout::new(&schema);
2376                                let row_layout = RowLayout::new(&schema);
2377
2378                                if let Some(compiled) = self.compile_predicate_unless_forced(
2379                                    "readonly:count-filter:predicate",
2380                                    predicate,
2381                                    &columns,
2382                                    &fast,
2383                                    &schema,
2384                                ) {
2385                                    let mut count: i64 = 0;
2386                                    for_each_row_raw_cancellable(
2387                                        &self.catalog,
2388                                        table,
2389                                        |_rid, data| {
2390                                            if compiled(data) {
2391                                                count += 1;
2392                                            }
2393                                        },
2394                                    )?;
2395                                    return Ok(QueryResult::Scalar(Value::Int(count)));
2396                                }
2397
2398                                let pred_cols = predicate_column_indices_json(predicate, &columns);
2399                                let mut count: i64 = 0;
2400                                for_each_row_raw_cancellable(
2401                                    &self.catalog,
2402                                    table,
2403                                    |_rid, data| {
2404                                        let pred_row = decode_selective(
2405                                            &schema,
2406                                            &row_layout,
2407                                            data,
2408                                            &pred_cols,
2409                                        );
2410                                        if eval_predicate(predicate, &pred_row, &columns) {
2411                                            count += 1;
2412                                        }
2413                                    },
2414                                )?;
2415                                return Ok(QueryResult::Scalar(Value::Int(count)));
2416                            }
2417                        }
2418                    }
2419                }
2420
2421                // Fast path: sum/avg/min/max over single fixed-size numeric.
2422                if matches!(
2423                    function,
2424                    AggFunc::Sum
2425                        | AggFunc::Avg
2426                        | AggFunc::Min
2427                        | AggFunc::Max
2428                        | AggFunc::CountDistinct
2429                ) {
2430                    if let Some(Expr::Field(col)) = argument.as_ref() {
2431                        let (table_opt, pred_opt): (Option<&str>, Option<&Expr>) =
2432                            match input.as_ref() {
2433                                PlanNode::SeqScan { table } => (Some(table.as_str()), None),
2434                                PlanNode::Filter {
2435                                    input: inner,
2436                                    predicate,
2437                                } => {
2438                                    if let PlanNode::SeqScan { table } = inner.as_ref() {
2439                                        (Some(table.as_str()), Some(predicate))
2440                                    } else {
2441                                        (None, None)
2442                                    }
2443                                }
2444                                _ => (None, None),
2445                            };
2446                        if let Some(table) = table_opt {
2447                            if let Some(result) =
2448                                self.agg_single_col_fast(table, col, *function, pred_opt)?
2449                            {
2450                                return Ok(result);
2451                            }
2452                        }
2453                    }
2454                }
2455
2456                // Generic path.
2457                let result = self.dispatch_readonly(input)?;
2458                match result {
2459                    QueryResult::Rows { columns, rows } => {
2460                        aggregate_rows(*function, argument.as_ref(), &columns, &rows)
2461                    }
2462                    _ => Err("aggregate requires row input".into()),
2463                }
2464            }
2465
2466            PlanNode::Distinct { input } => {
2467                let result = self.dispatch_readonly(input)?;
2468                match result {
2469                    QueryResult::Rows { columns, rows } => {
2470                        let mut seen = std::collections::HashSet::new();
2471                        let mut unique_rows = Vec::new();
2472                        let mut cancel = crate::cancel::CancelCheck::new();
2473                        for row in rows {
2474                            cancel.tick()?;
2475                            if seen.insert(row.clone()) {
2476                                unique_rows.push(row);
2477                            }
2478                        }
2479                        Ok(QueryResult::Rows {
2480                            columns,
2481                            rows: unique_rows,
2482                        })
2483                    }
2484                    other => Ok(other),
2485                }
2486            }
2487
2488            PlanNode::GroupBy {
2489                input,
2490                keys,
2491                aggregates,
2492                having,
2493            } => {
2494                if aggregates
2495                    .iter()
2496                    .any(|aggregate| aggregate.provenance_alias.is_some())
2497                {
2498                    let input = self.materialize_rows_with_provenance(input)?;
2499                    self.charge_rows(&input.rows)?;
2500                    return exec_group_by_with_provenance(
2501                        input,
2502                        keys,
2503                        aggregates,
2504                        having,
2505                        self.query_memory_limit,
2506                    );
2507                }
2508                let result = self.dispatch_readonly(input)?;
2509                match result {
2510                    QueryResult::Rows { columns, rows } => {
2511                        // WS2: byte-budget guard on the GROUP BY input buffer
2512                        // (the hash table is bounded by the input it groups).
2513                        self.charge_rows(&rows)?;
2514                        exec_group_by(columns, rows, keys, aggregates, having)
2515                    }
2516                    _ => Err("group by requires row input".into()),
2517                }
2518            }
2519
2520            PlanNode::NestedLoopJoin {
2521                left,
2522                right,
2523                on,
2524                kind,
2525            } => {
2526                let left_result = self.dispatch_readonly(left)?;
2527                let right_result = self.dispatch_readonly(right)?;
2528                let (left_columns, left_rows) = match left_result {
2529                    QueryResult::Rows { columns, rows } => (columns, rows),
2530                    _ => return Err("join left side must produce rows".into()),
2531                };
2532                let (right_columns, right_rows) = match right_result {
2533                    QueryResult::Rows { columns, rows } => (columns, rows),
2534                    _ => return Err("join right side must produce rows".into()),
2535                };
2536
2537                // WS2: byte-budget guard on the join build side.
2538                self.charge_rows(&left_rows)?;
2539                self.charge_rows(&right_rows)?;
2540
2541                execute_materialized_join(
2542                    left_columns,
2543                    left_rows,
2544                    right_columns,
2545                    right_rows,
2546                    on.as_ref(),
2547                    *kind,
2548                    self.nested_loop_pair_limit,
2549                )
2550            }
2551
2552            PlanNode::Window { input, windows } => {
2553                let result = self.dispatch_readonly(input)?;
2554                execute_window(result, windows, self.query_memory_limit)
2555            }
2556
2557            PlanNode::Union { left, right, all } => {
2558                let left_result = self.dispatch_readonly(left)?;
2559                let right_result = self.dispatch_readonly(right)?;
2560                let (left_cols, left_rows) = match left_result {
2561                    QueryResult::Rows { columns, rows } => (columns, rows),
2562                    _ => return Err("UNION requires query results on left side".into()),
2563                };
2564                let (_, right_rows) = match right_result {
2565                    QueryResult::Rows { columns, rows } => (columns, rows),
2566                    _ => return Err("UNION requires query results on right side".into()),
2567                };
2568                let mut combined = left_rows;
2569                let mut cancel = crate::cancel::CancelCheck::new();
2570                if *all {
2571                    for row in right_rows {
2572                        cancel.tick()?;
2573                        combined.push(row);
2574                    }
2575                } else {
2576                    let mut seen = std::collections::HashSet::new();
2577                    for row in &combined {
2578                        cancel.tick()?;
2579                        seen.insert(row.clone());
2580                    }
2581                    for row in right_rows {
2582                        cancel.tick()?;
2583                        if seen.insert(row.clone()) {
2584                            combined.push(row);
2585                        }
2586                    }
2587                }
2588                Ok(QueryResult::Rows {
2589                    columns: left_cols,
2590                    rows: combined,
2591                })
2592            }
2593
2594            PlanNode::Explain { input } => {
2595                // Every execute entry point runs lower_unindexed_scans before
2596                // dispatch and lowering recurses into Explain, so `input` is
2597                // already the plan that will actually run.
2598                let text = format_plan_tree(&self.catalog, input, 0);
2599                Ok(QueryResult::Rows {
2600                    columns: vec!["plan".to_string()],
2601                    rows: text
2602                        .lines()
2603                        .map(|line| vec![Value::Str(line.to_string())])
2604                        .collect(),
2605                })
2606            }
2607
2608            PlanNode::ListTypes => self.introspect_list_types(),
2609
2610            PlanNode::Describe { table } => self.introspect_describe(table),
2611
2612            PlanNode::ListLinks => self.introspect_list_links(),
2613
2614            // All write variants — caller must escalate to the write lock.
2615            PlanNode::Insert { .. }
2616            | PlanNode::Update { .. }
2617            | PlanNode::Delete { .. }
2618            | PlanNode::Upsert { .. }
2619            | PlanNode::CreateTable { .. }
2620            | PlanNode::CreateLink { .. }
2621            | PlanNode::AlterTable { .. }
2622            | PlanNode::DropTable { .. }
2623            | PlanNode::CreateView { .. }
2624            | PlanNode::RefreshView { .. }
2625            | PlanNode::DropView { .. }
2626            | PlanNode::Begin
2627            | PlanNode::Commit
2628            | PlanNode::Rollback => Err(QueryError::ReadonlyNeedsWrite),
2629        }
2630    }
2631
2632    /// `&self` variant of [`Engine::materialize_subqueries`]. Used by the
2633    /// read path so `Filter` predicates with `InSubquery`/`ExistsSubquery`
2634    /// children can evaluate their inner queries without taking the write
2635    /// lock. Inner queries that would themselves need a write (e.g. dirty
2636    /// view) escalate via [`READONLY_NEEDS_WRITE`] just like the top-level
2637    /// read path does.
2638    fn materialize_subqueries_readonly(&self, expr: &Expr) -> Result<Expr, QueryError> {
2639        match expr {
2640            Expr::InSubquery {
2641                expr: inner,
2642                subquery,
2643                negated,
2644            } => {
2645                if is_correlated_subquery(subquery, &self.catalog) {
2646                    // Pass through — will be materialized per-row in the
2647                    // Filter handler's correlated subquery path.
2648                    let inner = self.materialize_subqueries_readonly(inner)?;
2649                    return Ok(Expr::InSubquery {
2650                        expr: Box::new(inner),
2651                        subquery: subquery.clone(),
2652                        negated: *negated,
2653                    });
2654                }
2655                let inner = self.materialize_subqueries_readonly(inner)?;
2656                let sub_plan = self.plan_and_lower(Statement::Query(*subquery.clone()))?;
2657                let result = self.execute_plan_readonly(&sub_plan)?;
2658                let values = match result {
2659                    QueryResult::Rows { rows, .. } => {
2660                        let mut values = Vec::with_capacity(rows.len());
2661                        let mut cancel = crate::cancel::CancelCheck::new();
2662                        for mut row in rows {
2663                            cancel.tick()?;
2664                            if !row.is_empty() {
2665                                values.push(value_to_expr(row.swap_remove(0)));
2666                            }
2667                        }
2668                        values
2669                    }
2670                    _ => Vec::new(),
2671                };
2672                // WS2: byte-budget guard on the materialized IN-list.
2673                self.charge_in_list(&values)?;
2674                Ok(Expr::InList {
2675                    expr: Box::new(inner),
2676                    list: values,
2677                    negated: *negated,
2678                })
2679            }
2680            Expr::ExistsSubquery { subquery, negated } => {
2681                if is_correlated_subquery(subquery, &self.catalog) {
2682                    return Ok(expr.clone());
2683                }
2684                let sub_plan = self.plan_and_lower(Statement::Query(*subquery.clone()))?;
2685                let result = self.execute_plan_readonly(&sub_plan)?;
2686                let has_rows = match result {
2687                    QueryResult::Rows { rows, .. } => !rows.is_empty(),
2688                    _ => false,
2689                };
2690                let truth = if *negated { !has_rows } else { has_rows };
2691                Ok(Expr::Literal(Literal::Bool(truth)))
2692            }
2693            Expr::BinaryOp(l, op, r) => {
2694                let l = self.materialize_subqueries_readonly(l)?;
2695                let r = self.materialize_subqueries_readonly(r)?;
2696                Ok(Expr::BinaryOp(Box::new(l), *op, Box::new(r)))
2697            }
2698            Expr::UnaryOp(op, inner) => {
2699                let inner = self.materialize_subqueries_readonly(inner)?;
2700                Ok(Expr::UnaryOp(*op, Box::new(inner)))
2701            }
2702            Expr::Case { whens, else_expr } => {
2703                let whens = whens
2704                    .iter()
2705                    .map(|(c, r)| {
2706                        let c = self.materialize_subqueries_readonly(c)?;
2707                        let r = self.materialize_subqueries_readonly(r)?;
2708                        Ok((Box::new(c), Box::new(r)))
2709                    })
2710                    .collect::<Result<Vec<_>, QueryError>>()?;
2711                let else_expr = match else_expr {
2712                    Some(e) => Some(Box::new(self.materialize_subqueries_readonly(e)?)),
2713                    None => None,
2714                };
2715                Ok(Expr::Case { whens, else_expr })
2716            }
2717            other => Ok(other.clone()),
2718        }
2719    }
2720
2721    /// Per-row materialisation of correlated subqueries. For each row in the
2722    /// outer query, substitute outer column references in the subquery's
2723    /// filter with the current row's literal values, execute the modified
2724    /// subquery, and return the result as an InList or Bool literal.
2725    fn materialize_correlated_for_row_readonly(
2726        &self,
2727        expr: &Expr,
2728        outer_row: &[Value],
2729        outer_columns: &[String],
2730    ) -> Result<Expr, QueryError> {
2731        match expr {
2732            Expr::InSubquery {
2733                expr: inner,
2734                subquery,
2735                negated,
2736            } => {
2737                let inner =
2738                    self.materialize_correlated_for_row_readonly(inner, outer_row, outer_columns)?;
2739                let mut sub = *subquery.clone();
2740                if let Some(ref filter) = sub.filter {
2741                    sub.filter = Some(substitute_outer_refs(
2742                        filter,
2743                        &sub.source,
2744                        &self.catalog,
2745                        outer_row,
2746                        outer_columns,
2747                    ));
2748                }
2749                let sub_plan = self.plan_and_lower(Statement::Query(sub))?;
2750                let result = self.execute_plan_readonly(&sub_plan)?;
2751                let values = match result {
2752                    QueryResult::Rows { rows, .. } => {
2753                        let mut values = Vec::with_capacity(rows.len());
2754                        let mut cancel = crate::cancel::CancelCheck::new();
2755                        for mut row in rows {
2756                            cancel.tick()?;
2757                            if !row.is_empty() {
2758                                values.push(value_to_expr(row.swap_remove(0)));
2759                            }
2760                        }
2761                        values
2762                    }
2763                    _ => Vec::new(),
2764                };
2765                // WS2: byte-budget guard on the per-row materialized IN-list.
2766                self.charge_in_list(&values)?;
2767                Ok(Expr::InList {
2768                    expr: Box::new(inner),
2769                    list: values,
2770                    negated: *negated,
2771                })
2772            }
2773            Expr::ExistsSubquery { subquery, negated } => {
2774                let mut sub = *subquery.clone();
2775                if let Some(ref filter) = sub.filter {
2776                    sub.filter = Some(substitute_outer_refs(
2777                        filter,
2778                        &sub.source,
2779                        &self.catalog,
2780                        outer_row,
2781                        outer_columns,
2782                    ));
2783                }
2784                let sub_plan = self.plan_and_lower(Statement::Query(sub))?;
2785                let result = self.execute_plan_readonly(&sub_plan)?;
2786                let has_rows = match result {
2787                    QueryResult::Rows { rows, .. } => !rows.is_empty(),
2788                    _ => false,
2789                };
2790                let truth = if *negated { !has_rows } else { has_rows };
2791                Ok(Expr::Literal(Literal::Bool(truth)))
2792            }
2793            Expr::BinaryOp(l, op, r) => {
2794                let l =
2795                    self.materialize_correlated_for_row_readonly(l, outer_row, outer_columns)?;
2796                let r =
2797                    self.materialize_correlated_for_row_readonly(r, outer_row, outer_columns)?;
2798                Ok(Expr::BinaryOp(Box::new(l), *op, Box::new(r)))
2799            }
2800            Expr::UnaryOp(op, inner) => {
2801                let inner =
2802                    self.materialize_correlated_for_row_readonly(inner, outer_row, outer_columns)?;
2803                Ok(Expr::UnaryOp(*op, Box::new(inner)))
2804            }
2805            other => Ok(other.clone()),
2806        }
2807    }
2808
2809    pub fn catalog(&self) -> &Catalog {
2810        &self.catalog
2811    }
2812
2813    pub fn catalog_mut(&mut self) -> &mut Catalog {
2814        &mut self.catalog
2815    }
2816}
2817
2818impl Drop for Engine {
2819    fn drop(&mut self) {
2820        let Some(hook) = self.wal_archive_hook.clone() else {
2821            return;
2822        };
2823        if let Err(err) = self
2824            .catalog
2825            .checkpoint_with_wal_archive(move |dir, records| hook(dir, records))
2826        {
2827            error!(error = %err, "sync-aware engine checkpoint on drop failed");
2828        }
2829    }
2830}