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, 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;
60type WalArchiveHook =
61    Arc<dyn Fn(&Path, &[powdb_storage::wal::WalRecord]) -> io::Result<()> + Send + Sync>;
62
63/// Maximum number of rows a join may produce before the executor aborts.
64/// Prevents Cartesian-product blowups (e.g. `T cross join T` on 10K rows
65/// would produce 100M rows in memory without this cap).
66pub(super) const MAX_JOIN_ROWS: usize = 1_000_000;
67
68/// Maximum number of rows that may be materialized for sorting.
69/// Queries that exceed this should add a LIMIT clause to narrow the input
70/// before sorting.
71pub(super) const MAX_SORT_ROWS: usize = 10_000_000;
72
73#[inline]
74pub(super) fn check_join_limit(row_count: usize) -> Result<(), QueryError> {
75    if row_count > MAX_JOIN_ROWS {
76        return Err(QueryError::JoinLimitExceeded);
77    }
78    Ok(())
79}
80
81// ─── Mission D11 Phase 1: scalar hot-loop helpers ─────────────────────────
82//
83// These macros expand into the scan body of `agg_single_col_fast` and sit
84// inside the `for_each_row_raw` closure. They exist to:
85//
86//   1. Split the loop on presence of a predicate *outside* the hot body,
87//      so the no-predicate path (agg_sum/agg_min/agg_max bench workloads)
88//      never pays the `Option<CompiledPredicate>` branch per row.
89//   2. Drop two bounds checks per row by reading the null bitmap byte
90//      and the 8-byte value via raw pointer casts.
91//
92// SAFETY (shared across every call site below):
93//
94//   - `$bmp_byte` is `col_idx / 8` where `col_idx < n_cols`, and the row body
95//     encoding stores `bitmap_size = n_cols.div_ceil(8)` bytes of bitmap
96//     starting at body offset 2. So `bmp_off = row_body_base(row) + 2 +
97//     $bmp_byte < row_len`, and `get_unchecked(bmp_off)` is inside the
98//     row slice.
99//   - `$off = 2 + bitmap_size + fixed_offsets[col_idx]` is body-relative for a fixed-size
100//     column. Every fixed-size column contributes `fixed_size(type_id)`
101//     bytes to the fixed region, so the row always has
102//     `[data_off .. data_off + 8]` available for any i64/f64 column, where
103//     `data_off = row_body_base(row) + $off` — enforced by the row encoder
104//     (`storage/src/row.rs`) and the schema invariant that a row with a
105//     given schema has enough body bytes for `2 + bitmap_size + fixed_region_size`.
106//   - Both macros are only invoked from `agg_single_col_fast`, which
107//     early-returns if the column isn't Int/Float (8-byte fixed) and
108//     early-returns if `fast.fixed_offsets[col_idx]` is `None`.
109macro_rules! agg_int_loop {
110    (
111        $self:expr, $table:expr, $pred:expr,
112        $bmp_byte:expr, $bmp_bit:expr, $off:expr,
113        |$v:ident : i64| $body:block
114    ) => {{
115        let bmp_byte = $bmp_byte;
116        let bmp_bit = $bmp_bit;
117        let off = $off;
118        if let Some(pred) = &$pred {
119            $self
120                .catalog
121                .for_each_row_raw($table, |_rid, data| {
122                    if !pred(data) {
123                        return;
124                    }
125                    let base = row_body_base(data);
126                    let bmp_off = base + 2 + bmp_byte;
127                    let data_off = base + off;
128                    // Bounds guard: skip corrupt/truncated rows that are too
129                    // short to contain the bitmap byte or the 8-byte value.
130                    if bmp_off >= data.len() || data_off + 8 > data.len() {
131                        return;
132                    }
133                    // SAFETY: `bmp_off < data.len()` is checked above.
134                    // The bitmap byte lives at body offset 2..2+bitmap_size in
135                    // the row encoding, and bmp_byte = col_idx / 8 < bitmap_size.
136                    // Corrupt rows are rejected by the bounds guard.
137                    let bmp = unsafe { *data.get_unchecked(bmp_off) };
138                    if (bmp >> bmp_bit) & 1 == 1 {
139                        return;
140                    }
141                    // SAFETY: `data_off + 8 <= data.len()` is checked above.
142                    // `data_off = base + 2 + bitmap_size + fixed_offsets[col_idx]`
143                    // points to an 8-byte i64 in the fixed-size region of the row.
144                    // The pointer cast is valid because we read exactly 8
145                    // bytes via from_le_bytes. Corrupt rows are rejected by
146                    // the bounds guard.
147                    let $v: i64 = unsafe {
148                        i64::from_le_bytes(*(data.as_ptr().add(data_off) as *const [u8; 8]))
149                    };
150                    $body
151                })
152                .map_err(|e| QueryError::StorageError(e.to_string()))?;
153        } else {
154            $self
155                .catalog
156                .for_each_row_raw($table, |_rid, data| {
157                    let base = row_body_base(data);
158                    let bmp_off = base + 2 + bmp_byte;
159                    let data_off = base + off;
160                    // Bounds guard: skip corrupt/truncated rows.
161                    if bmp_off >= data.len() || data_off + 8 > data.len() {
162                        return;
163                    }
164                    // SAFETY: `bmp_off < data.len()` is checked above.
165                    // See the predicate branch for the full invariant.
166                    let bmp = unsafe { *data.get_unchecked(bmp_off) };
167                    if (bmp >> bmp_bit) & 1 == 1 {
168                        return;
169                    }
170                    // SAFETY: `data_off + 8 <= data.len()` is checked above.
171                    // See the predicate branch for the full invariant.
172                    let $v: i64 = unsafe {
173                        i64::from_le_bytes(*(data.as_ptr().add(data_off) as *const [u8; 8]))
174                    };
175                    $body
176                })
177                .map_err(|e| QueryError::StorageError(e.to_string()))?;
178        }
179    }};
180}
181
182macro_rules! agg_float_loop {
183    (
184        $self:expr, $table:expr, $pred:expr,
185        $bmp_byte:expr, $bmp_bit:expr, $off:expr,
186        |$v:ident : f64| $body:block
187    ) => {{
188        let bmp_byte = $bmp_byte;
189        let bmp_bit = $bmp_bit;
190        let off = $off;
191        if let Some(pred) = &$pred {
192            $self
193                .catalog
194                .for_each_row_raw($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 = unsafe {
221                        f64::from_le_bytes(*(data.as_ptr().add(data_off) as *const [u8; 8]))
222                    };
223                    $body
224                })
225                .map_err(|e| QueryError::StorageError(e.to_string()))?;
226        } else {
227            $self
228                .catalog
229                .for_each_row_raw($table, |_rid, data| {
230                    let base = row_body_base(data);
231                    let bmp_off = base + 2 + bmp_byte;
232                    let data_off = base + off;
233                    // Bounds guard: skip corrupt/truncated rows.
234                    if bmp_off >= data.len() || data_off + 8 > data.len() {
235                        return;
236                    }
237                    // SAFETY: `bmp_off < data.len()` is checked above.
238                    // See the predicate branch for the full invariant.
239                    let bmp = unsafe { *data.get_unchecked(bmp_off) };
240                    if (bmp >> bmp_bit) & 1 == 1 {
241                        return;
242                    }
243                    // SAFETY: `data_off + 8 <= data.len()` is checked above.
244                    // See the predicate branch for the full invariant.
245                    let $v: f64 = unsafe {
246                        f64::from_le_bytes(*(data.as_ptr().add(data_off) as *const [u8; 8]))
247                    };
248                    $body
249                })
250                .map_err(|e| QueryError::StorageError(e.to_string()))?;
251        }
252    }};
253}
254
255// Submodules that use the macros above — must be declared after macro_rules!.
256mod plan_exec;
257mod prepared;
258
259#[cfg(test)]
260mod tests;
261
262// Re-exports for the public API
263pub use self::prepared::PreparedQuery;
264
265use self::plan_exec::{
266    exec_group_by, execute_window, format_plan_tree, hash_join, lower_unindexed_scans,
267    range_matches, synthesize_range_predicate, try_extract_equi_join_keys,
268    validate_no_stray_aggregates,
269};
270
271/// Mission infra-1: classify a parsed statement as read-only vs. mutating.
272/// Used by [`Engine::execute_powql_readonly`] and by the server handler
273/// to decide between the RwLock reader and writer sides. `Union` recurses
274/// because each side can independently be read/write (though in practice
275/// both sides are reads — the parser only builds Union from query shapes).
276pub fn is_read_only_statement(stmt: &Statement) -> bool {
277    match stmt {
278        Statement::Query(_) => true,
279        Statement::ListTypes | Statement::Describe(_) => true,
280        Statement::Union(u) => is_read_only_statement(&u.left) && is_read_only_statement(&u.right),
281        Statement::Insert(_)
282        | Statement::Upsert(_)
283        | Statement::UpdateQuery(_)
284        | Statement::DeleteQuery(_)
285        | Statement::CreateType(_)
286        | Statement::AlterTable(_)
287        | Statement::DropTable(_)
288        | Statement::CreateView(_)
289        | Statement::RefreshView(_)
290        | Statement::DropView(_) => false,
291        Statement::Begin | Statement::Commit | Statement::Rollback => false,
292        Statement::Explain(inner) => is_read_only_statement(inner),
293    }
294}
295
296pub struct Engine {
297    catalog: Catalog,
298    /// Exclusive PID-based lock on the data directory, held for the engine's
299    /// lifetime so two separate processes can't open the same dir and corrupt
300    /// the heap/WAL. Released on clean drop; a `mem::forget` crash leaves a
301    /// stale lock the next open takes over. Leading `_`: it does its work
302    /// through `Drop`, never read directly.
303    _dir_lock: powdb_storage::dir_lock::DirLock,
304    /// Mission D9 — cached parsed+planned query trees keyed by canonical
305    /// hash. Saves the ~3μs parse+plan cost on repeat queries that differ
306    /// only in literal values.
307    ///
308    /// Mission infra-1: wrapped in `Mutex` so the read path can be driven
309    /// by `&self`. The critical section is extremely short — a single
310    /// hashmap lookup + plan clone on a hit, or a single insert on a miss.
311    /// A full `RwLock` would be over-engineered here; the contention window
312    /// is smaller than the read-path scan work it gates.
313    plan_cache: Mutex<PlanCache>,
314    /// Mission C Phase 13: reusable `Vec<Value>` scratch buffer for the
315    /// prepared-insert fast path. `execute_prepared` used to allocate a
316    /// fresh `vec![Value::Empty; n_cols]` on every insert; recycling this
317    /// buffer shaves one heap alloc per row on `insert_batch_1k`.
318    insert_values_scratch: Vec<Value>,
319    /// Materialized view registry: tracks view definitions, dependencies,
320    /// and dirty state. Views are backed by regular catalog tables; this
321    /// registry adds the lifecycle metadata.
322    view_registry: ViewRegistry,
323    in_transaction: bool,
324    /// WS2 — per-query memory budget ceiling (bytes). The running total lives
325    /// in a thread-local (see [`mem_budget`]) and is reset at every top-level
326    /// query entry, so sort/join/GROUP BY/IN-list materialization can be capped
327    /// without OOM-killing the process. This field holds only the *limit* (a
328    /// plain `usize`, so `Engine` stays `Sync` for the concurrent read path).
329    /// Default [`mem_budget::DEFAULT_QUERY_MEMORY_LIMIT`] (256 MB); overridable
330    /// via `Engine::with_memory_limit` (server reads `POWDB_QUERY_MEMORY_LIMIT`).
331    query_memory_limit: usize,
332    wal_archive_hook: Option<WalArchiveHook>,
333}
334
335impl Engine {
336    /// Open or create a PowDB engine rooted at `data_dir`.
337    ///
338    /// If the directory already contains a catalog, it is reopened.
339    /// Otherwise a fresh empty database is created.
340    ///
341    /// # Examples
342    ///
343    /// ```
344    /// use powdb_query::executor::Engine;
345    ///
346    /// let dir = tempfile::tempdir().unwrap();
347    /// let engine = Engine::new(dir.path()).unwrap();
348    /// // Engine is ready — the directory now contains a catalog.
349    /// ```
350    pub fn new(data_dir: &Path) -> io::Result<Self> {
351        Self::new_inner(data_dir, None)
352    }
353
354    /// Open or create an engine that archives WAL records before any recovery,
355    /// rollback, or drop checkpoint truncates them. This keeps the query crate
356    /// independent of replication metadata while giving sync-aware callers one
357    /// lifecycle boundary for retained-history preservation.
358    pub fn new_with_wal_archive<F>(data_dir: &Path, archive: F) -> io::Result<Self>
359    where
360        F: Fn(&Path, &[powdb_storage::wal::WalRecord]) -> io::Result<()> + Send + Sync + 'static,
361    {
362        Self::new_inner(data_dir, Some(Arc::new(archive)))
363    }
364
365    fn new_inner(data_dir: &Path, wal_archive_hook: Option<WalArchiveHook>) -> io::Result<Self> {
366        powdb_storage::create_data_dir_secure(data_dir)?;
367        // Refuse to open a directory another live process already holds, before
368        // touching any on-disk state (concurrent writers corrupt the heap/WAL).
369        let dir_lock = powdb_storage::dir_lock::DirLock::acquire(data_dir)?;
370        // Try to reopen an existing database first; only create a fresh
371        // catalog when there isn't one already on disk.
372        let catalog_result = match &wal_archive_hook {
373            Some(hook) => {
374                let hook = Arc::clone(hook);
375                Catalog::open_with_wal_archive(data_dir, move |dir, records| hook(dir, records))
376            }
377            None => Catalog::open(data_dir),
378        };
379        let catalog = match catalog_result {
380            Ok(c) => {
381                info!(data_dir = %data_dir.display(), "engine reopened existing database");
382                c
383            }
384            Err(e) if e.kind() == io::ErrorKind::NotFound => {
385                info!(data_dir = %data_dir.display(), "engine initialized fresh database");
386                Catalog::create(data_dir)?
387            }
388            Err(e) => return Err(e),
389        };
390        let view_registry =
391            ViewRegistry::open(data_dir).unwrap_or_else(|_| ViewRegistry::new(data_dir));
392        Ok(Engine {
393            catalog,
394            _dir_lock: dir_lock,
395            plan_cache: Mutex::new(PlanCache::new(PLAN_CACHE_CAPACITY)),
396            insert_values_scratch: Vec::new(),
397            view_registry,
398            in_transaction: false,
399            query_memory_limit: mem_budget::DEFAULT_QUERY_MEMORY_LIMIT,
400            wal_archive_hook,
401        })
402    }
403
404    /// Open or create an engine with an explicit per-query memory limit
405    /// (bytes). Used by the server to apply `POWDB_QUERY_MEMORY_LIMIT`, and by
406    /// tests that need a tiny limit to exercise the budget guard.
407    pub fn with_memory_limit(data_dir: &Path, limit_bytes: usize) -> io::Result<Self> {
408        let mut engine = Engine::new(data_dir)?;
409        engine.set_query_memory_limit(limit_bytes);
410        Ok(engine)
411    }
412
413    /// Open or create an archive-aware engine with an explicit per-query memory
414    /// limit.
415    pub fn with_memory_limit_and_wal_archive<F>(
416        data_dir: &Path,
417        limit_bytes: usize,
418        archive: F,
419    ) -> io::Result<Self>
420    where
421        F: Fn(&Path, &[powdb_storage::wal::WalRecord]) -> io::Result<()> + Send + Sync + 'static,
422    {
423        let mut engine = Engine::new_with_wal_archive(data_dir, archive)?;
424        engine.set_query_memory_limit(limit_bytes);
425        Ok(engine)
426    }
427
428    /// Current per-query memory limit in bytes.
429    pub fn query_memory_limit(&self) -> usize {
430        self.query_memory_limit
431    }
432
433    /// Override the per-query memory limit in bytes (builder-style).
434    pub fn set_query_memory_limit(&mut self, limit_bytes: usize) {
435        self.query_memory_limit = limit_bytes;
436    }
437
438    /// Set the WAL durability mode (see [`WalSyncMode`]). `Full` (the default)
439    /// fsyncs every commit; `Normal` moves the fsync to a background flusher
440    /// with a bounded crash-loss window; `Off` is bench-only (no durability).
441    /// Wired from the server's `POWDB_SYNC_MODE` / `--sync-mode` config.
442    pub fn set_wal_sync_mode(&mut self, mode: WalSyncMode) {
443        self.catalog.set_wal_sync_mode(mode);
444    }
445
446    /// Run `f` with commit durability deferred — the WAL group-commit entry
447    /// point for callers that serialize writers behind an exclusive lock.
448    ///
449    /// Inside `f`, Full-mode commit points register the WAL generation they
450    /// need durable instead of fsyncing inline. The returned ticket (if any)
451    /// must be waited on before the statement's result is acknowledged; the
452    /// caller should release its exclusive engine lock first, so other
453    /// committers can append while the fsync runs. That overlap is what lets
454    /// one fsync cover many commits. A lone committer's wait performs the
455    /// fsync immediately — group commit never introduces a delay.
456    ///
457    /// `Normal`/`Off` sync modes return no ticket; their durability
458    /// contracts are unchanged. If `f` panics the engine must not be reused
459    /// (the deferral flag may still be set); lock poisoning enforces this
460    /// for callers that share the engine behind a lock.
461    pub fn run_with_deferred_durability<T>(
462        &mut self,
463        f: impl FnOnce(&mut Engine) -> T,
464    ) -> (T, Option<WalDurabilityTicket>) {
465        self.catalog.set_wal_sync_deferred(true);
466        let out = f(self);
467        self.catalog.set_wal_sync_deferred(false);
468        let ticket = self.catalog.take_wal_durability_ticket();
469        (out, ticket)
470    }
471
472    /// Number of fsyncs issued against the WAL (test/metrics hook).
473    pub fn wal_fsync_count(&self) -> u64 {
474        self.catalog.wal_fsync_count()
475    }
476
477    /// Roll back the active explicit transaction while archiving any committed
478    /// pre-transaction WAL records that recovery must replay and truncate.
479    /// This is the sync-aware counterpart to the ordinary `rollback` statement;
480    /// callers provide the archive hook so the query crate stays independent of
481    /// replication metadata.
482    pub fn rollback_transaction_with_wal_archive<F>(
483        &mut self,
484        archive: F,
485    ) -> Result<QueryResult, QueryError>
486    where
487        F: FnMut(&Path, &[powdb_storage::wal::WalRecord]) -> io::Result<()>,
488    {
489        if !self.in_transaction {
490            return Err(QueryError::Execution(
491                "no active transaction to roll back".into(),
492            ));
493        }
494        self.catalog
495            .rollback_to_last_sync_with_wal_archive(archive)
496            .map_err(|e| QueryError::StorageError(e.to_string()))?;
497        self.finish_rollback_after_catalog_restore()
498    }
499
500    pub fn rollback_transaction_preserving_wal_archive(
501        &mut self,
502    ) -> Result<QueryResult, QueryError> {
503        let Some(hook) = self.wal_archive_hook.clone() else {
504            if !self.in_transaction {
505                return Err(QueryError::Execution(
506                    "no active transaction to roll back".into(),
507                ));
508            }
509            self.catalog
510                .rollback_to_last_sync()
511                .map_err(|e| QueryError::StorageError(e.to_string()))?;
512            return self.finish_rollback_after_catalog_restore();
513        };
514        self.rollback_transaction_with_wal_archive(move |dir, records| hook(dir, records))
515    }
516
517    fn finish_rollback_after_catalog_restore(&mut self) -> Result<QueryResult, QueryError> {
518        self.in_transaction = false;
519        if let Ok(mut cache) = self.plan_cache.lock() {
520            cache.clear();
521        }
522        self.view_registry = ViewRegistry::open(self.catalog.data_dir())
523            .unwrap_or_else(|_| ViewRegistry::new(self.catalog.data_dir()));
524        Ok(QueryResult::Executed {
525            message: "transaction rolled back".to_string(),
526        })
527    }
528
529    /// Enter a budgeted-statement frame for the current query. The returned
530    /// guard must be held for the duration of the statement; on its drop the
531    /// reentrancy depth is decremented. Only the *outermost* statement entry
532    /// zeroes this thread's running total, so a nested `execute_powql` (the
533    /// source query of a `create_view`/`refresh_view`) does NOT discard the
534    /// outer frame's accounting. The accumulator is thread-local, so this never
535    /// touches another concurrent query's total.
536    #[must_use = "the budget guard must outlive the statement body"]
537    pub(super) fn enter_memory_budget(&self) -> mem_budget::EnterGuard {
538        mem_budget::enter()
539    }
540
541    /// Charge the estimated footprint of a freshly materialized batch of rows
542    /// against the current per-query budget. Returns
543    /// [`QueryError::MemoryLimitExceeded`] cleanly if the batch would push the
544    /// query over its limit. Used at every full-materialization point (sort
545    /// buffer, join build side, GROUP BY hash table, IN-list).
546    pub(super) fn charge_rows(&self, rows: &[Vec<Value>]) -> Result<(), QueryError> {
547        let mut total = 0usize;
548        for row in rows {
549            total = total.saturating_add(mem_budget::estimate_row_size(row));
550        }
551        mem_budget::charge(total, self.query_memory_limit)
552    }
553
554    /// Charge a materialized IN-list (the literal expressions pulled out of an
555    /// uncorrelated `IN (subquery)`) against the current per-query budget.
556    /// Each item is conservatively sized at the `Expr` slot plus, for string
557    /// literals, the owned heap bytes.
558    pub(super) fn charge_in_list(&self, list: &[crate::ast::Expr]) -> Result<(), QueryError> {
559        let base = std::mem::size_of::<crate::ast::Expr>();
560        let mut total = std::mem::size_of::<Vec<crate::ast::Expr>>();
561        for item in list {
562            total = total.saturating_add(base);
563            if let crate::ast::Expr::Literal(crate::ast::Literal::String(s)) = item {
564                total = total.saturating_add(s.capacity());
565            }
566        }
567        mem_budget::charge(total, self.query_memory_limit)
568    }
569
570    /// Dispatch to the requested query frontend.
571    pub fn execute_with_dialect(
572        &mut self,
573        dialect: QueryDialect,
574        input: &str,
575    ) -> Result<QueryResult, QueryError> {
576        match dialect {
577            QueryDialect::PowQL => self.execute_powql(input),
578            QueryDialect::Sql => self.execute_sql(input),
579        }
580    }
581
582    /// Read-only variant of [`Engine::execute_with_dialect`].
583    pub fn execute_readonly_with_dialect(
584        &self,
585        dialect: QueryDialect,
586        input: &str,
587    ) -> Result<QueryResult, QueryError> {
588        match dialect {
589            QueryDialect::PowQL => self.execute_powql_readonly(input),
590            QueryDialect::Sql => self.execute_sql_readonly(input),
591        }
592    }
593
594    /// Parse + plan + execute a PowQL query.
595    ///
596    /// # Examples
597    ///
598    /// ```
599    /// use powdb_query::executor::Engine;
600    /// use powdb_query::result::QueryResult;
601    ///
602    /// let dir = tempfile::tempdir().unwrap();
603    /// let mut engine = Engine::new(dir.path()).unwrap();
604    ///
605    /// // Create a table and insert a row.
606    /// engine.execute_powql("type User { required name: str, age: int }").unwrap();
607    /// engine.execute_powql(r#"insert User { name := "Alice", age := 30 }"#).unwrap();
608    ///
609    /// // Query rows back.
610    /// let result = engine.execute_powql("User").unwrap();
611    /// assert_eq!(result.row_count(), 1);
612    /// ```
613    ///
614    /// Mission D6 — tracing collapse: the previous implementation ran 4
615    /// `Instant::now()` + 3 `elapsed().as_micros()` calls + formatted an
616    /// `info!` span on every query, even when tracing was disabled. On a
617    /// sub-microsecond `point_lookup_indexed` call that overhead was
618    /// 100-200ns — 20%+ of the whole query. We now measure time only when
619    /// INFO is actually enabled via `tracing::enabled!`, and we moved the
620    /// noisy `debug!(?plan)` line behind the same gate so the Debug
621    /// formatter can't run unconditionally either.
622    ///
623    /// Mission D9 — plan cache: on the hot path we canonicalise the query
624    /// text (lex + FNV-1a hash with literal values stripped), check the
625    /// cache, and on a hit substitute the new literals into a clone of the
626    /// cached plan. This skips re-lexing, re-parsing, and re-planning —
627    /// around 3μs per call on bench workloads. On a miss we plan as before
628    /// and insert the plan under its canonical hash.
629    pub fn execute_powql(&mut self, input: &str) -> Result<QueryResult, QueryError> {
630        // WS2: each *outermost* statement starts with the full memory
631        // allowance. The guard holds the reentrancy depth so a nested
632        // `execute_powql` (e.g. a view's source query) does not reset the
633        // outer frame's accounting mid-statement.
634        let _budget = self.enter_memory_budget();
635        // Hot path: tracing disabled. Zero syscalls, zero formatting.
636        if !tracing::enabled!(Level::INFO) {
637            // D9: try the plan cache first. Canonicalisation lexes the
638            // query once; on a hit we skip the parser and planner entirely.
639            if let Ok((hash, literals)) = canonicalize(input) {
640                let cached = self
641                    .plan_cache
642                    .lock()
643                    .map_err(|e| QueryError::Execution(format!("plan cache lock poisoned: {e}")))?
644                    .get_with_substitution(hash, &literals);
645                if let Some(plan) = cached {
646                    let plan = lower_unindexed_scans(&self.catalog, &plan);
647                    let result = self.execute_plan(&plan);
648                    // Mission B (post-review): statement-boundary WAL
649                    // group commit. Catalog::wal_log now only appends;
650                    // the fsync happens here exactly once per statement.
651                    // `sync_wal` is a no-op when nothing was buffered
652                    // (pure reads pay zero fsync).
653                    if !self.in_transaction {
654                        self.catalog
655                            .commit_autocommit()
656                            .map_err(|e| QueryError::StorageError(e.to_string()))?;
657                    }
658                    return result;
659                }
660                // Miss — plan, insert, execute.
661                return match planner::plan(input) {
662                    Ok(plan) => {
663                        self.plan_cache
664                            .lock()
665                            .map_err(|e| {
666                                QueryError::Execution(format!("plan cache lock poisoned: {e}"))
667                            })?
668                            .insert(hash, plan.clone(), literals.len());
669                        let plan = lower_unindexed_scans(&self.catalog, &plan);
670                        let result = self.execute_plan(&plan);
671                        if !self.in_transaction {
672                            self.catalog
673                                .commit_autocommit()
674                                .map_err(|e| QueryError::StorageError(e.to_string()))?;
675                        }
676                        result
677                    }
678                    Err(e) => Err(QueryError::Parse(e.to_string())),
679                };
680            }
681            // Lex error — fall through to the planner so the caller gets a
682            // consistent error shape.
683            return match planner::plan(input) {
684                Ok(plan) => {
685                    let plan = lower_unindexed_scans(&self.catalog, &plan);
686                    let result = self.execute_plan(&plan);
687                    if !self.in_transaction {
688                        self.catalog
689                            .commit_autocommit()
690                            .map_err(|e| QueryError::StorageError(e.to_string()))?;
691                    }
692                    result
693                }
694                Err(e) => Err(QueryError::Parse(e.to_string())),
695            };
696        }
697
698        // Instrumented path — only taken under explicit tracing subscribers.
699        let total_start = Instant::now();
700        let plan_start = Instant::now();
701        let plan = planner::plan(input).map_err(|e| {
702            let msg = e.to_string();
703            error!(query = %input, error = %msg, "query plan failed");
704            QueryError::Parse(msg)
705        })?;
706        let plan_us = plan_start.elapsed().as_micros();
707
708        let exec_start = Instant::now();
709        let plan = lower_unindexed_scans(&self.catalog, &plan);
710        let result = self.execute_plan(&plan);
711        if !self.in_transaction {
712            self.catalog
713                .commit_autocommit()
714                .map_err(|e| QueryError::StorageError(e.to_string()))?;
715        }
716        let exec_us = exec_start.elapsed().as_micros();
717
718        let total_us = total_start.elapsed().as_micros();
719        match &result {
720            Ok(r) => {
721                info!(
722                    query = %input,
723                    plan_us = plan_us,
724                    exec_us = exec_us,
725                    total_us = total_us,
726                    rows = r.row_count(),
727                    "query ok"
728                );
729            }
730            Err(e) => {
731                error!(
732                    query = %input,
733                    plan_us = plan_us,
734                    exec_us = exec_us,
735                    error = %e,
736                    "query failed"
737                );
738            }
739        }
740        result
741    }
742
743    /// Parse + plan + execute a SQL query through the SQL frontend.
744    ///
745    /// SQL is lowered to the existing PowDB AST and to canonical PowQL text.
746    /// The canonical PowQL text is used as the plan-cache key, so equivalent
747    /// SQL and PowQL spellings share cached plans.
748    pub fn execute_sql(&mut self, input: &str) -> Result<QueryResult, QueryError> {
749        let _budget = self.enter_memory_budget();
750        let parsed = crate::sql::parse_sql_with_canonical(input)
751            .map_err(|e| QueryError::Parse(e.to_string()))?;
752
753        if !tracing::enabled!(Level::INFO) {
754            if let Ok((hash, literals)) = canonicalize(&parsed.canonical_powql) {
755                let cached = self
756                    .plan_cache
757                    .lock()
758                    .map_err(|e| QueryError::Execution(format!("plan cache lock poisoned: {e}")))?
759                    .get_with_substitution(hash, &literals);
760                if let Some(plan) = cached {
761                    let plan = lower_unindexed_scans(&self.catalog, &plan);
762                    let result = self.execute_plan(&plan);
763                    if !self.in_transaction {
764                        self.catalog
765                            .commit_autocommit()
766                            .map_err(|e| QueryError::StorageError(e.to_string()))?;
767                    }
768                    return result;
769                }
770
771                let plan = crate::planner::plan_statement(parsed.statement)
772                    .map_err(|e| QueryError::Parse(e.to_string()))?;
773                self.plan_cache
774                    .lock()
775                    .map_err(|e| QueryError::Execution(format!("plan cache lock poisoned: {e}")))?
776                    .insert(hash, plan.clone(), literals.len());
777                let plan = lower_unindexed_scans(&self.catalog, &plan);
778                let result = self.execute_plan(&plan);
779                if !self.in_transaction {
780                    self.catalog
781                        .commit_autocommit()
782                        .map_err(|e| QueryError::StorageError(e.to_string()))?;
783                }
784                return result;
785            }
786        }
787
788        let plan = crate::planner::plan_statement(parsed.statement)
789            .map_err(|e| QueryError::Parse(e.to_string()))?;
790        let plan = lower_unindexed_scans(&self.catalog, &plan);
791        let result = self.execute_plan(&plan);
792        if !self.in_transaction {
793            self.catalog
794                .commit_autocommit()
795                .map_err(|e| QueryError::StorageError(e.to_string()))?;
796        }
797        result
798    }
799
800    /// Read-only variant of [`Engine::execute_sql`].
801    pub fn execute_sql_readonly(&self, input: &str) -> Result<QueryResult, QueryError> {
802        let _budget = self.enter_memory_budget();
803        let parsed = crate::sql::parse_sql_with_canonical(input)
804            .map_err(|e| QueryError::Parse(e.to_string()))?;
805        if !is_read_only_statement(&parsed.statement) {
806            return Err(QueryError::ReadonlyNeedsWrite);
807        }
808
809        if let Ok((hash, literals)) = canonicalize(&parsed.canonical_powql) {
810            let cached = self
811                .plan_cache
812                .lock()
813                .map_err(|e| QueryError::Execution(format!("plan cache lock poisoned: {e}")))?
814                .get_with_substitution(hash, &literals);
815            if let Some(plan) = cached {
816                let plan = lower_unindexed_scans(&self.catalog, &plan);
817                return self.execute_plan_readonly(&plan);
818            }
819            let plan = crate::planner::plan_statement(parsed.statement)
820                .map_err(|e| QueryError::Parse(e.to_string()))?;
821            self.plan_cache
822                .lock()
823                .map_err(|e| QueryError::Execution(format!("plan cache lock poisoned: {e}")))?
824                .insert(hash, plan.clone(), literals.len());
825            let plan = lower_unindexed_scans(&self.catalog, &plan);
826            return self.execute_plan_readonly(&plan);
827        }
828
829        let plan = crate::planner::plan_statement(parsed.statement)
830            .map_err(|e| QueryError::Parse(e.to_string()))?;
831        let plan = lower_unindexed_scans(&self.catalog, &plan);
832        self.execute_plan_readonly(&plan)
833    }
834
835    /// Execute PowQL with `$N` placeholders bound to positional `params`.
836    ///
837    /// Task 4: parameters are substituted as literal *tokens* before
838    /// parsing (see [`crate::parser::parse_with_params`]), so untrusted
839    /// input can never change the query's shape. This path deliberately
840    /// **bypasses the plan cache** — template caching is a follow-up — and
841    /// otherwise mirrors the non-cached tail of [`Engine::execute_powql`].
842    pub fn execute_powql_with_params(
843        &mut self,
844        input: &str,
845        params: &[crate::ast::ParamValue],
846    ) -> Result<QueryResult, QueryError> {
847        let _budget = self.enter_memory_budget();
848        let stmt = crate::parser::parse_with_params(input, params)
849            .map_err(|e| QueryError::Parse(e.to_string()))?;
850        let plan =
851            crate::planner::plan_statement(stmt).map_err(|e| QueryError::Parse(e.to_string()))?;
852        let plan = lower_unindexed_scans(&self.catalog, &plan);
853        let result = self.execute_plan(&plan);
854        if !self.in_transaction {
855            self.catalog
856                .commit_autocommit()
857                .map_err(|e| QueryError::StorageError(e.to_string()))?;
858        }
859        result
860    }
861
862    /// Read-only variant of [`Engine::execute_powql_with_params`].
863    ///
864    /// Mirrors [`Engine::execute_powql_readonly`]: parses with bound
865    /// params, rejects any write statement with
866    /// [`QueryError::ReadonlyNeedsWrite`] so the caller can escalate to the
867    /// write lock, then executes under a shared borrow. No plan-cache
868    /// interaction.
869    pub fn execute_powql_readonly_with_params(
870        &self,
871        input: &str,
872        params: &[crate::ast::ParamValue],
873    ) -> Result<QueryResult, QueryError> {
874        let _budget = self.enter_memory_budget();
875        let stmt = crate::parser::parse_with_params(input, params)
876            .map_err(|e| QueryError::Parse(e.to_string()))?;
877        if !is_read_only_statement(&stmt) {
878            return Err(QueryError::ReadonlyNeedsWrite);
879        }
880        let plan =
881            crate::planner::plan_statement(stmt).map_err(|e| QueryError::Parse(e.to_string()))?;
882        let plan = lower_unindexed_scans(&self.catalog, &plan);
883        self.execute_plan_readonly(&plan)
884    }
885
886    /// Plan cache stats — useful for benches and debugging.
887    pub fn plan_cache_stats(&self) -> (u64, u64, usize) {
888        let cache = self.plan_cache.lock().unwrap_or_else(|e| e.into_inner());
889        (cache.hits, cache.misses, cache.len())
890    }
891
892    /// Mission infra-1: read-only entry point.
893    ///
894    /// Parses + plans + executes a PowQL query using only a shared borrow
895    /// on the engine. Rejects any statement that would mutate state
896    /// (Insert/Update/Delete/CreateTable/AlterTable/DropTable/CreateView/
897    /// RefreshView/DropView) by returning [`READONLY_NEEDS_WRITE`] so the
898    /// caller can escalate to the write lock.
899    ///
900    /// Also returns [`READONLY_NEEDS_WRITE`] if a materialized view in the
901    /// query is dirty — refreshing one requires `&mut self`, so the caller
902    /// must retake the write lock for the first refresh.
903    ///
904    /// This method is the concurrent-read fast path behind
905    /// `Arc<RwLock<Engine>>`: multiple threads can call it simultaneously
906    /// under a shared `.read()` lock and each will scan independently.
907    pub fn execute_powql_readonly(&self, input: &str) -> Result<QueryResult, QueryError> {
908        // WS2: each *outermost* statement starts with the full memory
909        // allowance. The guard holds the reentrancy depth so a nested
910        // `execute_powql*` does not reset the outer frame's accounting.
911        let _budget = self.enter_memory_budget();
912        // Parse the statement first so we can classify read vs. write
913        // without touching the catalog. This is the same lex+parse cost
914        // the hot path would pay anyway.
915        let stmt = crate::parser::parse(input).map_err(|e| QueryError::Parse(e.to_string()))?;
916        if !is_read_only_statement(&stmt) {
917            return Err(QueryError::ReadonlyNeedsWrite);
918        }
919
920        // Try the plan cache first — identical hash scheme to
921        // `execute_powql` so both paths share cache state. The mutex
922        // section is just a hashmap lookup + plan clone.
923        if let Ok((hash, literals)) = canonicalize(input) {
924            let cached = self
925                .plan_cache
926                .lock()
927                .map_err(|e| QueryError::Execution(format!("plan cache lock poisoned: {e}")))?
928                .get_with_substitution(hash, &literals);
929            if let Some(plan) = cached {
930                let plan = lower_unindexed_scans(&self.catalog, &plan);
931                return self.execute_plan_readonly(&plan);
932            }
933            // Miss: plan + insert + execute. The planner is pure, so this
934            // is safe from `&self`.
935            let plan = crate::planner::plan_statement(stmt)
936                .map_err(|e| QueryError::Parse(e.to_string()))?;
937            self.plan_cache
938                .lock()
939                .map_err(|e| QueryError::Execution(format!("plan cache lock poisoned: {e}")))?
940                .insert(hash, plan.clone(), literals.len());
941            let plan = lower_unindexed_scans(&self.catalog, &plan);
942            return self.execute_plan_readonly(&plan);
943        }
944        // Lex error — fall through to the planner for a consistent error
945        // shape (though `parse` above would usually have caught it).
946        let plan =
947            crate::planner::plan_statement(stmt).map_err(|e| QueryError::Parse(e.to_string()))?;
948        let plan = lower_unindexed_scans(&self.catalog, &plan);
949        self.execute_plan_readonly(&plan)
950    }
951
952    /// Read-only version of [`Engine::execute_plan`]. Dispatches the
953    /// read-path plan variants by calling `&self` helpers and errors with
954    /// [`READONLY_NEEDS_WRITE`] on any write variant. This is the
955    /// recursion target for composite read plans under the RwLock reader.
956    ///
957    /// The dispatch mirrors `execute_plan` for the read branches but does
958    /// not carry any of the fast-paths that need `&mut self` (e.g. plan-
959    /// cache mutation on inner subqueries is handled via the shared mutex
960    /// in [`Engine::execute_powql_readonly`]; in-flight subquery
961    /// materialisation uses [`Engine::materialize_subqueries_readonly`]).
962    fn execute_plan_readonly(&self, plan: &PlanNode) -> Result<QueryResult, QueryError> {
963        // Mirror the mutable path: reject a stray aggregate FunctionCall before
964        // evaluating any row (see execute_plan for the rationale).
965        validate_no_stray_aggregates(plan)?;
966        match plan {
967            PlanNode::SeqScan { table } => {
968                // Dirty view means we'd need to refresh it — can't do that
969                // under `&self`. Escalate to the write path.
970                if self.view_registry.is_dirty(table) {
971                    return Err(QueryError::ReadonlyNeedsWrite);
972                }
973                let schema = self
974                    .catalog
975                    .schema(table)
976                    .ok_or_else(|| QueryError::TableNotFound(table.clone()))?
977                    .clone();
978                let columns: Vec<String> = schema.columns.iter().map(|c| c.name.clone()).collect();
979                let rows: Vec<Vec<Value>> = self
980                    .catalog
981                    .scan(table)
982                    .map_err(|e| e.to_string())?
983                    .map(|(_, row)| row)
984                    .collect();
985                Ok(QueryResult::Rows { columns, rows })
986            }
987
988            PlanNode::AliasScan { table, alias } => {
989                let schema = self
990                    .catalog
991                    .schema(table)
992                    .ok_or_else(|| QueryError::TableNotFound(table.clone()))?
993                    .clone();
994                let columns: Vec<String> = schema
995                    .columns
996                    .iter()
997                    .map(|c| format!("{alias}.{}", c.name))
998                    .collect();
999                let rows: Vec<Vec<Value>> = self
1000                    .catalog
1001                    .scan(table)
1002                    .map_err(|e| e.to_string())?
1003                    .map(|(_, row)| row)
1004                    .collect();
1005                Ok(QueryResult::Rows { columns, rows })
1006            }
1007
1008            PlanNode::IndexScan { table, column, key } => {
1009                let schema = self
1010                    .catalog
1011                    .schema(table)
1012                    .ok_or_else(|| QueryError::TableNotFound(table.clone()))?
1013                    .clone();
1014                let columns: Vec<String> = schema.columns.iter().map(|c| c.name.clone()).collect();
1015                let key_value = literal_to_value(key)?;
1016                let tbl = self
1017                    .catalog
1018                    .get_table(table)
1019                    .ok_or_else(|| QueryError::TableNotFound(table.clone()))?;
1020
1021                if tbl.has_index(column) {
1022                    // Use index_lookup_all to handle both unique and
1023                    // non-unique indexes — returns all matching RowIds.
1024                    let rids = tbl.index_lookup_all(column, &key_value);
1025                    let mut rows: Vec<Vec<Value>> = Vec::with_capacity(rids.len());
1026                    for rid in rids {
1027                        // Overflow safety (P0-3/P0-4): `tbl.get` reassembles
1028                        // spilled columns (the old `heap.get` + `decode_row`
1029                        // returned Empty / wrapped a >= 64KB value).
1030                        if let Some(row) = tbl.get(rid) {
1031                            rows.push(row);
1032                        }
1033                    }
1034                    return Ok(QueryResult::Rows { columns, rows });
1035                }
1036
1037                // No index: synthetic eq predicate + compiled scan.
1038                // Overflow safety (P0-4/P1): v2-capable tables use the decoded
1039                // last-resort scan below (raw scan drops/mis-reads spilled cols).
1040                let fast = FastLayout::new(&schema);
1041                let synth_pred = Expr::BinaryOp(
1042                    Box::new(Expr::Field(column.clone())),
1043                    BinOp::Eq,
1044                    Box::new(key.clone()),
1045                );
1046                if !tbl.has_overflow_rows() {
1047                    if let Some(compiled) = compile_predicate(&synth_pred, &columns, &fast, &schema)
1048                    {
1049                        let mut rows: Vec<Vec<Value>> = Vec::with_capacity(64);
1050                        self.catalog
1051                            .for_each_row_raw(table, |_rid, data| {
1052                                if compiled(data) {
1053                                    rows.push(decode_row(&schema, data));
1054                                }
1055                            })
1056                            .map_err(|e| QueryError::StorageError(e.to_string()))?;
1057                        return Ok(QueryResult::Rows { columns, rows });
1058                    }
1059                }
1060
1061                // Last resort: slow eq-check.
1062                let col_idx =
1063                    schema
1064                        .column_index(column)
1065                        .ok_or_else(|| QueryError::ColumnNotFound {
1066                            table: String::new(),
1067                            column: column.clone(),
1068                        })?;
1069                let rows: Vec<Vec<Value>> = tbl
1070                    .scan()
1071                    .filter_map(|(_, row)| {
1072                        if row[col_idx] == key_value {
1073                            Some(row)
1074                        } else {
1075                            None
1076                        }
1077                    })
1078                    .collect();
1079                Ok(QueryResult::Rows { columns, rows })
1080            }
1081
1082            PlanNode::RangeScan {
1083                table,
1084                column,
1085                start,
1086                end,
1087            } => {
1088                let tbl = self
1089                    .catalog
1090                    .get_table(table)
1091                    .ok_or_else(|| QueryError::TableNotFound(table.clone()))?;
1092                let columns: Vec<String> =
1093                    tbl.schema.columns.iter().map(|c| c.name.clone()).collect();
1094                let schema = tbl.schema.clone();
1095
1096                let start_val = match start {
1097                    Some((expr, _)) => Some(literal_to_value(expr)?),
1098                    None => None,
1099                };
1100                let end_val = match end {
1101                    Some((expr, _)) => Some(literal_to_value(expr)?),
1102                    None => None,
1103                };
1104                let start_inclusive = start.as_ref().map(|(_, inc)| *inc).unwrap_or(true);
1105                let end_inclusive = end.as_ref().map(|(_, inc)| *inc).unwrap_or(true);
1106
1107                // Range scans only use the btree fast path for unique indexes.
1108                // Non-unique indexes store composite keys that don't compare
1109                // directly against raw column values.
1110                if tbl.is_index_unique(column) == Some(true) {
1111                    if let Some(btree) = tbl.index(column) {
1112                        let hits: Vec<(Value, RowId)> = match (&start_val, &end_val) {
1113                            (Some(s), Some(e)) => btree.range(s, e).collect(),
1114                            (Some(s), None) => btree.range_from(s),
1115                            (None, Some(e)) => btree.range_to(e),
1116                            (None, None) => {
1117                                // Unbounded both sides — equivalent to seq scan.
1118                                let rows: Vec<Vec<Value>> =
1119                                    tbl.scan().map(|(_, row)| row).collect();
1120                                return Ok(QueryResult::Rows { columns, rows });
1121                            }
1122                        };
1123                        let mut rows: Vec<Vec<Value>> = Vec::with_capacity(hits.len());
1124                        for (key, rid) in hits {
1125                            // Filter for exclusive bounds.
1126                            if !start_inclusive {
1127                                if let Some(ref s) = start_val {
1128                                    if &key == s {
1129                                        continue;
1130                                    }
1131                                }
1132                            }
1133                            if !end_inclusive {
1134                                if let Some(ref e) = end_val {
1135                                    if &key == e {
1136                                        continue;
1137                                    }
1138                                }
1139                            }
1140                            // Overflow safety (P0-3): reassemble spilled cols.
1141                            if let Some(row) = tbl.get(rid) {
1142                                rows.push(row);
1143                            }
1144                        }
1145                        return Ok(QueryResult::Rows { columns, rows });
1146                    }
1147                }
1148
1149                // Fallback: no index — synthesize the range predicate and scan.
1150                // Overflow safety (P0-4): v2-capable tables use the decoded
1151                // last-resort scan below.
1152                let fast = FastLayout::new(&schema);
1153                let synth = synthesize_range_predicate(column, start, end);
1154                if !tbl.has_overflow_rows() {
1155                    if let Some(compiled) = compile_predicate(&synth, &columns, &fast, &schema) {
1156                        let mut rows: Vec<Vec<Value>> = Vec::with_capacity(64);
1157                        self.catalog
1158                            .for_each_row_raw(table, |_rid, data| {
1159                                if compiled(data) {
1160                                    rows.push(decode_row(&schema, data));
1161                                }
1162                            })
1163                            .map_err(|e| QueryError::StorageError(e.to_string()))?;
1164                        return Ok(QueryResult::Rows { columns, rows });
1165                    }
1166                }
1167
1168                // Last resort: decoded row eval.
1169                let col_idx =
1170                    schema
1171                        .column_index(column)
1172                        .ok_or_else(|| QueryError::ColumnNotFound {
1173                            table: String::new(),
1174                            column: column.clone(),
1175                        })?;
1176                let rows: Vec<Vec<Value>> = tbl
1177                    .scan()
1178                    .filter(|(_, row)| {
1179                        range_matches(
1180                            &row[col_idx],
1181                            &start_val,
1182                            start_inclusive,
1183                            &end_val,
1184                            end_inclusive,
1185                        )
1186                    })
1187                    .map(|(_, row)| row)
1188                    .collect();
1189                Ok(QueryResult::Rows { columns, rows })
1190            }
1191
1192            PlanNode::Filter { input, predicate } => {
1193                // Materialise subqueries using the `&self` variant.
1194                // Uncorrelated subqueries are replaced with InList/Bool;
1195                // correlated ones are left as InSubquery/ExistsSubquery
1196                // for per-row materialisation below.
1197                let materialized;
1198                let predicate = if contains_subquery(predicate) {
1199                    materialized = self.materialize_subqueries_readonly(predicate)?;
1200                    &materialized
1201                } else {
1202                    predicate
1203                };
1204
1205                // Correlated subquery path: per-row materialisation.
1206                if contains_subquery(predicate) {
1207                    let result = self.execute_plan_readonly(input)?;
1208                    return match result {
1209                        QueryResult::Rows { columns, rows } => {
1210                            let mut filtered = Vec::new();
1211                            for row in rows {
1212                                let row_pred = self.materialize_correlated_for_row_readonly(
1213                                    predicate, &row, &columns,
1214                                )?;
1215                                if eval_predicate(&row_pred, &row, &columns) {
1216                                    filtered.push(row);
1217                                }
1218                            }
1219                            Ok(QueryResult::Rows {
1220                                columns,
1221                                rows: filtered,
1222                            })
1223                        }
1224                        _ => Err("filter requires row input".into()),
1225                    };
1226                }
1227
1228                // Fused Filter+SeqScan fast path.
1229                // Overflow safety (P0-4/P1): v2-capable tables fall through to
1230                // the decoded general path below.
1231                if let PlanNode::SeqScan { table } = input.as_ref() {
1232                    if !self.catalog.table_has_overflow(table) {
1233                        if self.view_registry.is_dirty(table) {
1234                            return Err(QueryError::ReadonlyNeedsWrite);
1235                        }
1236                        let schema = self
1237                            .catalog
1238                            .schema(table)
1239                            .ok_or_else(|| QueryError::TableNotFound(table.clone()))?
1240                            .clone();
1241                        let columns: Vec<String> =
1242                            schema.columns.iter().map(|c| c.name.clone()).collect();
1243                        let fast = FastLayout::new(&schema);
1244                        let row_layout = RowLayout::new(&schema);
1245                        let mut rows: Vec<Vec<Value>> = Vec::with_capacity(64);
1246
1247                        if let Some(compiled) =
1248                            compile_predicate(predicate, &columns, &fast, &schema)
1249                        {
1250                            self.catalog
1251                                .for_each_row_raw(table, |_rid, data| {
1252                                    if compiled(data) {
1253                                        rows.push(decode_row(&schema, data));
1254                                    }
1255                                })
1256                                .map_err(|e| QueryError::StorageError(e.to_string()))?;
1257                        } else {
1258                            let pred_cols = predicate_column_indices(predicate, &columns);
1259                            self.catalog
1260                                .for_each_row_raw(table, |_rid, data| {
1261                                    let pred_row =
1262                                        decode_selective(&schema, &row_layout, data, &pred_cols);
1263                                    if eval_predicate(predicate, &pred_row, &columns) {
1264                                        rows.push(decode_row(&schema, data));
1265                                    }
1266                                })
1267                                .map_err(|e| QueryError::StorageError(e.to_string()))?;
1268                        }
1269
1270                        return Ok(QueryResult::Rows { columns, rows });
1271                    }
1272                }
1273
1274                // General path.
1275                let result = self.execute_plan_readonly(input)?;
1276                match result {
1277                    QueryResult::Rows { columns, rows } => {
1278                        let filtered: Vec<Vec<Value>> = rows
1279                            .into_iter()
1280                            .filter(|row| eval_predicate(predicate, row, &columns))
1281                            .collect();
1282                        Ok(QueryResult::Rows {
1283                            columns,
1284                            rows: filtered,
1285                        })
1286                    }
1287                    _ => Err("filter requires row input".into()),
1288                }
1289            }
1290
1291            PlanNode::Project { input, fields } => {
1292                // Fast path: Project over IndexScan. Avoids full-row decode
1293                // by calling decode_column only for projected fields.
1294                if let PlanNode::IndexScan { table, column, key } = input.as_ref() {
1295                    let key_value = literal_to_value(key)?;
1296                    let tbl = self
1297                        .catalog
1298                        .get_table(table)
1299                        .ok_or_else(|| QueryError::TableNotFound(table.clone()))?;
1300                    let schema = &tbl.schema;
1301
1302                    let proj_columns: Vec<String> = fields
1303                        .iter()
1304                        .map(|f| {
1305                            f.alias.clone().unwrap_or_else(|| match &f.expr {
1306                                Expr::Field(name) => name.clone(),
1307                                _ => "?".into(),
1308                            })
1309                        })
1310                        .collect();
1311
1312                    let proj_indices: Vec<usize> = fields
1313                        .iter()
1314                        .filter_map(|f| {
1315                            if let Expr::Field(name) = &f.expr {
1316                                schema.column_index(name)
1317                            } else {
1318                                None
1319                            }
1320                        })
1321                        .collect();
1322
1323                    // Plain-field projections only; a computed projection
1324                    // (e.g. `length(.v)`) falls through to the generic
1325                    // expression-evaluating path (its column is otherwise
1326                    // dropped — proj_indices only collects Fields).
1327                    let all_plain_fields = fields.iter().all(|f| matches!(f.expr, Expr::Field(_)));
1328                    if tbl.has_index(column) && all_plain_fields {
1329                        let rids = tbl.index_lookup_all(column, &key_value);
1330                        let mut rows: Vec<Vec<Value>> = Vec::with_capacity(rids.len());
1331                        for rid in rids {
1332                            // Overflow safety (P0-3/P0-4): reassemble via
1333                            // `tbl.get` so spilled projected columns return
1334                            // their value, not Empty / a wrapped >= 64KB blob.
1335                            if let Some(full) = tbl.get(rid) {
1336                                let row: Vec<Value> =
1337                                    proj_indices.iter().map(|&ci| full[ci].clone()).collect();
1338                                rows.push(row);
1339                            }
1340                        }
1341                        return Ok(QueryResult::Rows {
1342                            columns: proj_columns,
1343                            rows,
1344                        });
1345                    }
1346                }
1347
1348                // Fast paths over Limit(Sort(...)) / Limit(Filter(...)) / Limit(SeqScan).
1349                if let PlanNode::Limit {
1350                    input: inner,
1351                    count: limit_expr,
1352                } = input.as_ref()
1353                {
1354                    if let PlanNode::Sort {
1355                        input: sort_input,
1356                        keys,
1357                    } = inner.as_ref()
1358                    {
1359                        if keys.len() == 1 {
1360                            let sort_field = &keys[0].field;
1361                            let descending = keys[0].descending;
1362                            let limit = match limit_expr {
1363                                Expr::Literal(Literal::Int(v)) if *v >= 0 => *v as usize,
1364                                _ => usize::MAX,
1365                            };
1366                            let (table_opt, pred_opt): (Option<&str>, Option<&Expr>) =
1367                                match sort_input.as_ref() {
1368                                    PlanNode::SeqScan { table } => (Some(table.as_str()), None),
1369                                    PlanNode::Filter {
1370                                        input: fi,
1371                                        predicate,
1372                                    } => {
1373                                        if let PlanNode::SeqScan { table } = fi.as_ref() {
1374                                            (Some(table.as_str()), Some(predicate))
1375                                        } else {
1376                                            (None, None)
1377                                        }
1378                                    }
1379                                    _ => (None, None),
1380                                };
1381                            if let Some(table) = table_opt {
1382                                if let Some(result) = self.project_filter_sort_limit_fast(
1383                                    table, fields, sort_field, descending, limit, pred_opt,
1384                                )? {
1385                                    return Ok(result);
1386                                }
1387                            }
1388                        }
1389                    }
1390                    if let PlanNode::Filter {
1391                        input: fi,
1392                        predicate,
1393                    } = inner.as_ref()
1394                    {
1395                        if let PlanNode::SeqScan { table } = fi.as_ref() {
1396                            let limit = match limit_expr {
1397                                Expr::Literal(Literal::Int(v)) if *v >= 0 => *v as usize,
1398                                _ => usize::MAX,
1399                            };
1400                            if let Some(result) = self.project_filter_limit_fast(
1401                                table,
1402                                fields,
1403                                limit,
1404                                Some(predicate),
1405                            )? {
1406                                return Ok(result);
1407                            }
1408                        }
1409                    }
1410                    if let PlanNode::SeqScan { table } = inner.as_ref() {
1411                        let limit = match limit_expr {
1412                            Expr::Literal(Literal::Int(v)) if *v >= 0 => *v as usize,
1413                            _ => usize::MAX,
1414                        };
1415                        if let Some(result) =
1416                            self.project_filter_limit_fast(table, fields, limit, None)?
1417                        {
1418                            return Ok(result);
1419                        }
1420                    }
1421                }
1422
1423                // Project(Filter(SeqScan)) without Limit.
1424                if let PlanNode::Filter {
1425                    input: fi,
1426                    predicate,
1427                } = input.as_ref()
1428                {
1429                    if let PlanNode::SeqScan { table } = fi.as_ref() {
1430                        if let Some(result) = self.project_filter_limit_fast(
1431                            table,
1432                            fields,
1433                            usize::MAX,
1434                            Some(predicate),
1435                        )? {
1436                            return Ok(result);
1437                        }
1438                    }
1439                }
1440
1441                // Project(SeqScan) without Filter or Limit.
1442                if let PlanNode::SeqScan { table } = input.as_ref() {
1443                    if let Some(result) =
1444                        self.project_filter_limit_fast(table, fields, usize::MAX, None)?
1445                    {
1446                        return Ok(result);
1447                    }
1448                }
1449
1450                // Generic path.
1451                let result = self.execute_plan_readonly(input)?;
1452                match result {
1453                    QueryResult::Rows { columns, rows } => {
1454                        let proj_columns: Vec<String> = fields
1455                            .iter()
1456                            .map(|f| {
1457                                f.alias.clone().unwrap_or_else(|| match &f.expr {
1458                                    Expr::Field(name) => name.clone(),
1459                                    Expr::QualifiedField { qualifier, field } => {
1460                                        format!("{qualifier}.{field}")
1461                                    }
1462                                    _ => "?".into(),
1463                                })
1464                            })
1465                            .collect();
1466                        let proj_rows: Vec<Vec<Value>> = rows
1467                            .iter()
1468                            .map(|row| {
1469                                fields
1470                                    .iter()
1471                                    .map(|f| eval_expr(&f.expr, row, &columns))
1472                                    .collect()
1473                            })
1474                            .collect();
1475                        Ok(QueryResult::Rows {
1476                            columns: proj_columns,
1477                            rows: proj_rows,
1478                        })
1479                    }
1480                    _ => Err("project requires row input".into()),
1481                }
1482            }
1483
1484            PlanNode::Sort { input, keys } => {
1485                let result = self.execute_plan_readonly(input)?;
1486                match result {
1487                    QueryResult::Rows { columns, mut rows } => {
1488                        if rows.len() > MAX_SORT_ROWS {
1489                            return Err(QueryError::SortLimitExceeded);
1490                        }
1491                        // WS2: byte-budget guard on the sort buffer.
1492                        self.charge_rows(&rows)?;
1493                        let key_indices: Vec<(usize, bool)> = keys
1494                            .iter()
1495                            .map(|k| {
1496                                columns
1497                                    .iter()
1498                                    .position(|c| c == &k.field)
1499                                    .map(|idx| (idx, k.descending))
1500                                    .ok_or_else(|| QueryError::ColumnNotFound {
1501                                        table: String::new(),
1502                                        column: k.field.clone(),
1503                                    })
1504                            })
1505                            .collect::<Result<_, QueryError>>()?;
1506                        rows.sort_by(|a, b| {
1507                            for &(col_idx, descending) in &key_indices {
1508                                let cmp = a[col_idx].cmp(&b[col_idx]);
1509                                let cmp = if descending { cmp.reverse() } else { cmp };
1510                                if cmp != std::cmp::Ordering::Equal {
1511                                    return cmp;
1512                                }
1513                            }
1514                            std::cmp::Ordering::Equal
1515                        });
1516                        Ok(QueryResult::Rows { columns, rows })
1517                    }
1518                    _ => Err("sort requires row input".into()),
1519                }
1520            }
1521
1522            PlanNode::Limit { input, count } => {
1523                let result = self.execute_plan_readonly(input)?;
1524                let n = match count {
1525                    Expr::Literal(Literal::Int(v)) => *v as usize,
1526                    _ => return Err("limit must be integer literal".into()),
1527                };
1528                match result {
1529                    QueryResult::Rows { columns, rows } => Ok(QueryResult::Rows {
1530                        columns,
1531                        rows: rows.into_iter().take(n).collect(),
1532                    }),
1533                    _ => Err("limit requires row input".into()),
1534                }
1535            }
1536
1537            PlanNode::Offset { input, count } => {
1538                let result = self.execute_plan_readonly(input)?;
1539                let n = match count {
1540                    Expr::Literal(Literal::Int(v)) => *v as usize,
1541                    _ => return Err("offset must be integer literal".into()),
1542                };
1543                match result {
1544                    QueryResult::Rows { columns, rows } => Ok(QueryResult::Rows {
1545                        columns,
1546                        rows: rows.into_iter().skip(n).collect(),
1547                    }),
1548                    _ => Err("offset requires row input".into()),
1549                }
1550            }
1551
1552            PlanNode::Aggregate {
1553                input,
1554                function,
1555                field,
1556            } => {
1557                // Fast path: count() over SeqScan.
1558                // Overflow safety (P0-4): v2-capable tables use the decoded
1559                // generic path (raw count drops >= 64KB rows).
1560                if *function == AggFunc::Count {
1561                    if let PlanNode::SeqScan { table } = input.as_ref() {
1562                        if !self.catalog.table_has_overflow(table) {
1563                            // A dirty materialized view must be refreshed before
1564                            // it can be counted, which needs `&mut self`. Escalate
1565                            // to the write path (F3: count(View) returned stale).
1566                            if self.view_registry.is_dirty(table) {
1567                                return Err(QueryError::ReadonlyNeedsWrite);
1568                            }
1569                            let mut count: i64 = 0;
1570                            self.catalog
1571                                .for_each_row_raw(table, |_rid, _data| {
1572                                    count += 1;
1573                                })
1574                                .map_err(|e| QueryError::StorageError(e.to_string()))?;
1575                            return Ok(QueryResult::Scalar(Value::Int(count)));
1576                        }
1577                    }
1578                    if let PlanNode::Filter {
1579                        input: inner,
1580                        predicate,
1581                    } = input.as_ref()
1582                    {
1583                        // Only take the fast path for a plain Filter(SeqScan)
1584                        // with no subquery in the predicate. A subquery
1585                        // predicate (`count(T filter .x in (...))`) must be
1586                        // resolved first; the fast path evaluates the raw
1587                        // predicate with no subquery materialisation, which
1588                        // silently yields 0 (F1). Falling through routes it to
1589                        // the generic path that runs the subquery correctly.
1590                        if let PlanNode::SeqScan { table } = inner.as_ref() {
1591                            if self.view_registry.is_dirty(table) {
1592                                // F3: count(View filter ...) over a dirty view.
1593                                return Err(QueryError::ReadonlyNeedsWrite);
1594                            }
1595                        }
1596                        if let (PlanNode::SeqScan { table }, false) =
1597                            (inner.as_ref(), contains_subquery(predicate))
1598                        {
1599                            if !self.catalog.table_has_overflow(table) {
1600                                let schema = self
1601                                    .catalog
1602                                    .schema(table)
1603                                    .ok_or_else(|| QueryError::TableNotFound(table.clone()))?
1604                                    .clone();
1605                                let columns: Vec<String> =
1606                                    schema.columns.iter().map(|c| c.name.clone()).collect();
1607                                let fast = FastLayout::new(&schema);
1608                                let row_layout = RowLayout::new(&schema);
1609
1610                                if let Some(compiled) =
1611                                    compile_predicate(predicate, &columns, &fast, &schema)
1612                                {
1613                                    let mut count: i64 = 0;
1614                                    self.catalog
1615                                        .for_each_row_raw(table, |_rid, data| {
1616                                            if compiled(data) {
1617                                                count += 1;
1618                                            }
1619                                        })
1620                                        .map_err(|e| QueryError::StorageError(e.to_string()))?;
1621                                    return Ok(QueryResult::Scalar(Value::Int(count)));
1622                                }
1623
1624                                let pred_cols = predicate_column_indices(predicate, &columns);
1625                                let mut count: i64 = 0;
1626                                self.catalog
1627                                    .for_each_row_raw(table, |_rid, data| {
1628                                        let pred_row = decode_selective(
1629                                            &schema,
1630                                            &row_layout,
1631                                            data,
1632                                            &pred_cols,
1633                                        );
1634                                        if eval_predicate(predicate, &pred_row, &columns) {
1635                                            count += 1;
1636                                        }
1637                                    })
1638                                    .map_err(|e| QueryError::StorageError(e.to_string()))?;
1639                                return Ok(QueryResult::Scalar(Value::Int(count)));
1640                            }
1641                        }
1642                    }
1643                }
1644
1645                // Fast path: sum/avg/min/max over single fixed-size numeric.
1646                if matches!(
1647                    function,
1648                    AggFunc::Sum
1649                        | AggFunc::Avg
1650                        | AggFunc::Min
1651                        | AggFunc::Max
1652                        | AggFunc::CountDistinct
1653                ) {
1654                    if let Some(col) = field.as_ref() {
1655                        let (table_opt, pred_opt): (Option<&str>, Option<&Expr>) =
1656                            match input.as_ref() {
1657                                PlanNode::SeqScan { table } => (Some(table.as_str()), None),
1658                                PlanNode::Filter {
1659                                    input: inner,
1660                                    predicate,
1661                                } => {
1662                                    if let PlanNode::SeqScan { table } = inner.as_ref() {
1663                                        (Some(table.as_str()), Some(predicate))
1664                                    } else {
1665                                        (None, None)
1666                                    }
1667                                }
1668                                _ => (None, None),
1669                            };
1670                        if let Some(table) = table_opt {
1671                            if let Some(result) =
1672                                self.agg_single_col_fast(table, col, *function, pred_opt)?
1673                            {
1674                                return Ok(result);
1675                            }
1676                        }
1677                    }
1678                }
1679
1680                // Generic path.
1681                let result = self.execute_plan_readonly(input)?;
1682                match result {
1683                    QueryResult::Rows { columns, rows } => match function {
1684                        AggFunc::Count => Ok(QueryResult::Scalar(Value::Int(rows.len() as i64))),
1685                        AggFunc::CountDistinct => {
1686                            let col = field.as_ref().ok_or("count distinct requires field")?;
1687                            let idx = columns
1688                                .iter()
1689                                .position(|c| c == col)
1690                                .ok_or("col not found")?;
1691                            let mut seen = std::collections::HashSet::new();
1692                            for row in &rows {
1693                                let v = &row[idx];
1694                                if !v.is_empty() {
1695                                    seen.insert(v.clone());
1696                                }
1697                            }
1698                            Ok(QueryResult::Scalar(Value::Int(seen.len() as i64)))
1699                        }
1700                        AggFunc::Avg => {
1701                            let col = field.as_ref().ok_or("avg requires field")?;
1702                            let idx = columns
1703                                .iter()
1704                                .position(|c| c == col)
1705                                .ok_or("col not found")?;
1706                            let mut count: u64 = 0;
1707                            let sum: f64 = rows
1708                                .iter()
1709                                .filter_map(|r| match &r[idx] {
1710                                    Value::Int(v) => Some(*v as f64),
1711                                    Value::Float(v) => Some(*v),
1712                                    _ => None,
1713                                })
1714                                .inspect(|_| count += 1)
1715                                .sum();
1716                            if count == 0 {
1717                                Ok(QueryResult::Scalar(Value::Empty))
1718                            } else {
1719                                Ok(QueryResult::Scalar(Value::Float(sum / count as f64)))
1720                            }
1721                        }
1722                        AggFunc::Sum => {
1723                            let col = field.as_ref().ok_or("sum requires field")?;
1724                            let idx = columns
1725                                .iter()
1726                                .position(|c| c == col)
1727                                .ok_or("col not found")?;
1728                            let mut int_sum: i64 = 0;
1729                            let mut float_sum: f64 = 0.0;
1730                            let mut saw_float = false;
1731                            for r in &rows {
1732                                match &r[idx] {
1733                                    Value::Int(v) => int_sum += *v,
1734                                    Value::Float(v) => {
1735                                        float_sum += *v;
1736                                        saw_float = true;
1737                                    }
1738                                    _ => {}
1739                                }
1740                            }
1741                            let result = if saw_float {
1742                                Value::Float(float_sum + int_sum as f64)
1743                            } else {
1744                                Value::Int(int_sum)
1745                            };
1746                            Ok(QueryResult::Scalar(result))
1747                        }
1748                        AggFunc::Min | AggFunc::Max => {
1749                            let col = field.as_ref().ok_or("min/max requires field")?;
1750                            let idx = columns
1751                                .iter()
1752                                .position(|c| c == col)
1753                                .ok_or("col not found")?;
1754                            let vals: Vec<&Value> = rows.iter().map(|r| &r[idx]).collect();
1755                            let result = if *function == AggFunc::Min {
1756                                vals.into_iter().min().cloned()
1757                            } else {
1758                                vals.into_iter().max().cloned()
1759                            };
1760                            Ok(QueryResult::Scalar(result.unwrap_or(Value::Empty)))
1761                        }
1762                    },
1763                    _ => Err("aggregate requires row input".into()),
1764                }
1765            }
1766
1767            PlanNode::Distinct { input } => {
1768                let result = self.execute_plan_readonly(input)?;
1769                match result {
1770                    QueryResult::Rows { columns, rows } => {
1771                        let mut seen = std::collections::HashSet::new();
1772                        let mut unique_rows = Vec::new();
1773                        for row in rows {
1774                            if seen.insert(row.clone()) {
1775                                unique_rows.push(row);
1776                            }
1777                        }
1778                        Ok(QueryResult::Rows {
1779                            columns,
1780                            rows: unique_rows,
1781                        })
1782                    }
1783                    other => Ok(other),
1784                }
1785            }
1786
1787            PlanNode::GroupBy {
1788                input,
1789                keys,
1790                aggregates,
1791                having,
1792            } => {
1793                let result = self.execute_plan_readonly(input)?;
1794                match result {
1795                    QueryResult::Rows { columns, rows } => {
1796                        // WS2: byte-budget guard on the GROUP BY input buffer
1797                        // (the hash table is bounded by the input it groups).
1798                        self.charge_rows(&rows)?;
1799                        exec_group_by(columns, rows, keys, aggregates, having)
1800                    }
1801                    _ => Err("group by requires row input".into()),
1802                }
1803            }
1804
1805            PlanNode::NestedLoopJoin {
1806                left,
1807                right,
1808                on,
1809                kind,
1810            } => {
1811                let left_result = self.execute_plan_readonly(left)?;
1812                let right_result = self.execute_plan_readonly(right)?;
1813                let (left_columns, left_rows) = match left_result {
1814                    QueryResult::Rows { columns, rows } => (columns, rows),
1815                    _ => return Err("join left side must produce rows".into()),
1816                };
1817                let (right_columns, right_rows) = match right_result {
1818                    QueryResult::Rows { columns, rows } => (columns, rows),
1819                    _ => return Err("join right side must produce rows".into()),
1820                };
1821
1822                // WS2: byte-budget guard on the join build side.
1823                self.charge_rows(&left_rows)?;
1824                self.charge_rows(&right_rows)?;
1825
1826                if !matches!(kind, JoinKind::Cross) {
1827                    if let Some(pred) = on {
1828                        if let Some((l_idx, r_idx)) =
1829                            try_extract_equi_join_keys(pred, &left_columns, &right_columns)
1830                        {
1831                            let result = hash_join(
1832                                left_columns,
1833                                left_rows,
1834                                right_columns,
1835                                right_rows,
1836                                l_idx,
1837                                r_idx,
1838                                *kind,
1839                            );
1840                            if let QueryResult::Rows { ref rows, .. } = result {
1841                                check_join_limit(rows.len())?;
1842                            }
1843                            return Ok(result);
1844                        }
1845                    }
1846                }
1847
1848                let n_left = left_columns.len();
1849                let n_right = right_columns.len();
1850                let mut columns = Vec::with_capacity(n_left + n_right);
1851                columns.extend(left_columns);
1852                columns.extend(right_columns);
1853
1854                let mut rows: Vec<Vec<Value>> = Vec::with_capacity(left_rows.len());
1855                let mut combined: Vec<Value> = Vec::with_capacity(n_left + n_right);
1856
1857                for left_row in &left_rows {
1858                    let mut matched = false;
1859                    for right_row in &right_rows {
1860                        combined.clear();
1861                        combined.extend_from_slice(left_row);
1862                        combined.extend_from_slice(right_row);
1863                        let keep = match kind {
1864                            JoinKind::Cross => true,
1865                            JoinKind::Inner | JoinKind::LeftOuter => match on {
1866                                Some(pred) => eval_predicate(pred, &combined, &columns),
1867                                None => true,
1868                            },
1869                            JoinKind::RightOuter => {
1870                                unreachable!("planner rewrites RightOuter to LeftOuter")
1871                            }
1872                        };
1873                        if keep {
1874                            rows.push(combined.clone());
1875                            check_join_limit(rows.len())?;
1876                            matched = true;
1877                        }
1878                    }
1879                    if !matched && matches!(kind, JoinKind::LeftOuter) {
1880                        let mut row = Vec::with_capacity(n_left + n_right);
1881                        row.extend_from_slice(left_row);
1882                        row.resize(n_left + n_right, Value::Empty);
1883                        rows.push(row);
1884                        check_join_limit(rows.len())?;
1885                    }
1886                }
1887
1888                Ok(QueryResult::Rows { columns, rows })
1889            }
1890
1891            PlanNode::Window { input, windows } => {
1892                let result = self.execute_plan_readonly(input)?;
1893                execute_window(result, windows)
1894            }
1895
1896            PlanNode::Union { left, right, all } => {
1897                let left_result = self.execute_plan_readonly(left)?;
1898                let right_result = self.execute_plan_readonly(right)?;
1899                let (left_cols, left_rows) = match left_result {
1900                    QueryResult::Rows { columns, rows } => (columns, rows),
1901                    _ => return Err("UNION requires query results on left side".into()),
1902                };
1903                let (_, right_rows) = match right_result {
1904                    QueryResult::Rows { columns, rows } => (columns, rows),
1905                    _ => return Err("UNION requires query results on right side".into()),
1906                };
1907                let mut combined = left_rows;
1908                if *all {
1909                    combined.extend(right_rows);
1910                } else {
1911                    let mut seen = std::collections::HashSet::new();
1912                    for row in &combined {
1913                        seen.insert(row.clone());
1914                    }
1915                    for row in right_rows {
1916                        if seen.insert(row.clone()) {
1917                            combined.push(row);
1918                        }
1919                    }
1920                }
1921                Ok(QueryResult::Rows {
1922                    columns: left_cols,
1923                    rows: combined,
1924                })
1925            }
1926
1927            PlanNode::Explain { input } => {
1928                let text = format_plan_tree(input, 0);
1929                Ok(QueryResult::Rows {
1930                    columns: vec!["plan".to_string()],
1931                    rows: text
1932                        .lines()
1933                        .map(|line| vec![Value::Str(line.to_string())])
1934                        .collect(),
1935                })
1936            }
1937
1938            PlanNode::ListTypes => self.introspect_list_types(),
1939
1940            PlanNode::Describe { table } => self.introspect_describe(table),
1941
1942            // All write variants — caller must escalate to the write lock.
1943            PlanNode::Insert { .. }
1944            | PlanNode::Update { .. }
1945            | PlanNode::Delete { .. }
1946            | PlanNode::Upsert { .. }
1947            | PlanNode::CreateTable { .. }
1948            | PlanNode::AlterTable { .. }
1949            | PlanNode::DropTable { .. }
1950            | PlanNode::CreateView { .. }
1951            | PlanNode::RefreshView { .. }
1952            | PlanNode::DropView { .. }
1953            | PlanNode::Begin
1954            | PlanNode::Commit
1955            | PlanNode::Rollback => Err(QueryError::ReadonlyNeedsWrite),
1956        }
1957    }
1958
1959    /// `&self` variant of [`Engine::materialize_subqueries`]. Used by the
1960    /// read path so `Filter` predicates with `InSubquery`/`ExistsSubquery`
1961    /// children can evaluate their inner queries without taking the write
1962    /// lock. Inner queries that would themselves need a write (e.g. dirty
1963    /// view) escalate via [`READONLY_NEEDS_WRITE`] just like the top-level
1964    /// read path does.
1965    fn materialize_subqueries_readonly(&self, expr: &Expr) -> Result<Expr, QueryError> {
1966        match expr {
1967            Expr::InSubquery {
1968                expr: inner,
1969                subquery,
1970                negated,
1971            } => {
1972                if is_correlated_subquery(subquery, &self.catalog) {
1973                    // Pass through — will be materialized per-row in the
1974                    // Filter handler's correlated subquery path.
1975                    let inner = self.materialize_subqueries_readonly(inner)?;
1976                    return Ok(Expr::InSubquery {
1977                        expr: Box::new(inner),
1978                        subquery: subquery.clone(),
1979                        negated: *negated,
1980                    });
1981                }
1982                let inner = self.materialize_subqueries_readonly(inner)?;
1983                let sub_plan = crate::planner::plan_statement(Statement::Query(*subquery.clone()))
1984                    .map_err(|e| QueryError::StorageError(e.to_string()))?;
1985                let result = self.execute_plan_readonly(&sub_plan)?;
1986                let values = match result {
1987                    QueryResult::Rows { rows, .. } => rows
1988                        .into_iter()
1989                        .filter_map(|mut row| {
1990                            if row.is_empty() {
1991                                None
1992                            } else {
1993                                Some(value_to_expr(row.swap_remove(0)))
1994                            }
1995                        })
1996                        .collect(),
1997                    _ => Vec::new(),
1998                };
1999                // WS2: byte-budget guard on the materialized IN-list.
2000                self.charge_in_list(&values)?;
2001                Ok(Expr::InList {
2002                    expr: Box::new(inner),
2003                    list: values,
2004                    negated: *negated,
2005                })
2006            }
2007            Expr::ExistsSubquery { subquery, negated } => {
2008                if is_correlated_subquery(subquery, &self.catalog) {
2009                    return Ok(expr.clone());
2010                }
2011                let sub_plan = crate::planner::plan_statement(Statement::Query(*subquery.clone()))
2012                    .map_err(|e| QueryError::StorageError(e.to_string()))?;
2013                let result = self.execute_plan_readonly(&sub_plan)?;
2014                let has_rows = match result {
2015                    QueryResult::Rows { rows, .. } => !rows.is_empty(),
2016                    _ => false,
2017                };
2018                let truth = if *negated { !has_rows } else { has_rows };
2019                Ok(Expr::Literal(Literal::Bool(truth)))
2020            }
2021            Expr::BinaryOp(l, op, r) => {
2022                let l = self.materialize_subqueries_readonly(l)?;
2023                let r = self.materialize_subqueries_readonly(r)?;
2024                Ok(Expr::BinaryOp(Box::new(l), *op, Box::new(r)))
2025            }
2026            Expr::UnaryOp(op, inner) => {
2027                let inner = self.materialize_subqueries_readonly(inner)?;
2028                Ok(Expr::UnaryOp(*op, Box::new(inner)))
2029            }
2030            Expr::Case { whens, else_expr } => {
2031                let whens = whens
2032                    .iter()
2033                    .map(|(c, r)| {
2034                        let c = self.materialize_subqueries_readonly(c)?;
2035                        let r = self.materialize_subqueries_readonly(r)?;
2036                        Ok((Box::new(c), Box::new(r)))
2037                    })
2038                    .collect::<Result<Vec<_>, QueryError>>()?;
2039                let else_expr = match else_expr {
2040                    Some(e) => Some(Box::new(self.materialize_subqueries_readonly(e)?)),
2041                    None => None,
2042                };
2043                Ok(Expr::Case { whens, else_expr })
2044            }
2045            other => Ok(other.clone()),
2046        }
2047    }
2048
2049    /// Per-row materialisation of correlated subqueries. For each row in the
2050    /// outer query, substitute outer column references in the subquery's
2051    /// filter with the current row's literal values, execute the modified
2052    /// subquery, and return the result as an InList or Bool literal.
2053    fn materialize_correlated_for_row_readonly(
2054        &self,
2055        expr: &Expr,
2056        outer_row: &[Value],
2057        outer_columns: &[String],
2058    ) -> Result<Expr, QueryError> {
2059        match expr {
2060            Expr::InSubquery {
2061                expr: inner,
2062                subquery,
2063                negated,
2064            } => {
2065                let inner =
2066                    self.materialize_correlated_for_row_readonly(inner, outer_row, outer_columns)?;
2067                let mut sub = *subquery.clone();
2068                if let Some(ref filter) = sub.filter {
2069                    sub.filter = Some(substitute_outer_refs(
2070                        filter,
2071                        &sub.source,
2072                        &self.catalog,
2073                        outer_row,
2074                        outer_columns,
2075                    ));
2076                }
2077                let sub_plan = crate::planner::plan_statement(Statement::Query(sub))
2078                    .map_err(|e| QueryError::StorageError(e.to_string()))?;
2079                let result = self.execute_plan_readonly(&sub_plan)?;
2080                let values = match result {
2081                    QueryResult::Rows { rows, .. } => rows
2082                        .into_iter()
2083                        .filter_map(|mut row| {
2084                            if row.is_empty() {
2085                                None
2086                            } else {
2087                                Some(value_to_expr(row.swap_remove(0)))
2088                            }
2089                        })
2090                        .collect(),
2091                    _ => Vec::new(),
2092                };
2093                // WS2: byte-budget guard on the per-row materialized IN-list.
2094                self.charge_in_list(&values)?;
2095                Ok(Expr::InList {
2096                    expr: Box::new(inner),
2097                    list: values,
2098                    negated: *negated,
2099                })
2100            }
2101            Expr::ExistsSubquery { subquery, negated } => {
2102                let mut sub = *subquery.clone();
2103                if let Some(ref filter) = sub.filter {
2104                    sub.filter = Some(substitute_outer_refs(
2105                        filter,
2106                        &sub.source,
2107                        &self.catalog,
2108                        outer_row,
2109                        outer_columns,
2110                    ));
2111                }
2112                let sub_plan = crate::planner::plan_statement(Statement::Query(sub))
2113                    .map_err(|e| QueryError::StorageError(e.to_string()))?;
2114                let result = self.execute_plan_readonly(&sub_plan)?;
2115                let has_rows = match result {
2116                    QueryResult::Rows { rows, .. } => !rows.is_empty(),
2117                    _ => false,
2118                };
2119                let truth = if *negated { !has_rows } else { has_rows };
2120                Ok(Expr::Literal(Literal::Bool(truth)))
2121            }
2122            Expr::BinaryOp(l, op, r) => {
2123                let l =
2124                    self.materialize_correlated_for_row_readonly(l, outer_row, outer_columns)?;
2125                let r =
2126                    self.materialize_correlated_for_row_readonly(r, outer_row, outer_columns)?;
2127                Ok(Expr::BinaryOp(Box::new(l), *op, Box::new(r)))
2128            }
2129            Expr::UnaryOp(op, inner) => {
2130                let inner =
2131                    self.materialize_correlated_for_row_readonly(inner, outer_row, outer_columns)?;
2132                Ok(Expr::UnaryOp(*op, Box::new(inner)))
2133            }
2134            other => Ok(other.clone()),
2135        }
2136    }
2137
2138    pub fn catalog(&self) -> &Catalog {
2139        &self.catalog
2140    }
2141
2142    pub fn catalog_mut(&mut self) -> &mut Catalog {
2143        &mut self.catalog
2144    }
2145}
2146
2147impl Drop for Engine {
2148    fn drop(&mut self) {
2149        let Some(hook) = self.wal_archive_hook.clone() else {
2150            return;
2151        };
2152        if let Err(err) = self
2153            .catalog
2154            .checkpoint_with_wal_archive(move |dir, records| hook(dir, records))
2155        {
2156            error!(error = %err, "sync-aware engine checkpoint on drop failed");
2157        }
2158    }
2159}