Skip to main content

velesdb_core/database/
query_engine.rs

1//! Query execution: `execute_query`, `explain_query`, `explain_analyze_query`, plan caching, and DML dispatch.
2
3use crate::observer::{AccessDecision, AccessScope, QueryAccessContext, QueryOperationKind};
4use crate::velesql::{
5    ActualStats, AdminStatement, Condition, DdlStatement, DmlStatement, ExplainOutput,
6    IntrospectionStatement, Query, TrainStatement,
7};
8use crate::{Error, Result, SearchResult};
9
10use super::Database;
11
12/// Outcome of the non-VelesQL read gate ([`Database::read_gate_raw`]).
13///
14/// Mirrors [`AccessDecision`] but is returned to in-crate callers — the `VelesQL`
15/// [`read_gate`](Database::read_gate) and the raw `gated_search` path — so each
16/// enforces the same decision in the shape it needs: `read_gate` maps it onto a
17/// [`Cow<Query>`](std::borrow::Cow), the raw path onto a filtered collection
18/// search. Keeping one resolver means the observer-consult logic is defined
19/// exactly once.
20pub(crate) enum RawGateOutcome {
21    /// Execute the read unmodified.
22    Allow,
23    /// Abort the read with this error and zero results (Requirement 1.4).
24    Deny(crate::Error),
25    /// Execute the read with this scope narrowing applied (Requirement 1.5).
26    Scope(AccessScope),
27}
28
29/// Statement type classification for dispatch routing.
30enum StatementType<'a> {
31    Admin(&'a AdminStatement),
32    Introspection(&'a IntrospectionStatement),
33    Ddl(&'a DdlStatement),
34    Train(&'a TrainStatement),
35    Dml(&'a DmlStatement),
36    Match,
37    Select,
38}
39
40/// Classifies a query into its statement type for routing.
41fn classify_statement(query: &Query) -> StatementType<'_> {
42    if let Some(admin) = query.admin.as_ref() {
43        return StatementType::Admin(admin);
44    }
45    if let Some(intro) = query.introspection.as_ref() {
46        return StatementType::Introspection(intro);
47    }
48    if let Some(ddl) = query.ddl.as_ref() {
49        return StatementType::Ddl(ddl);
50    }
51    if let Some(train) = query.train.as_ref() {
52        return StatementType::Train(train);
53    }
54    if let Some(dml) = query.dml.as_ref() {
55        return StatementType::Dml(dml);
56    }
57    if query.is_match_query() {
58        return StatementType::Match;
59    }
60    StatementType::Select
61}
62
63/// Returns `true` if `cond` (or any nested sub-condition) contains a full-text
64/// `MATCH` search.
65///
66/// Mirrors [`Condition::has_vector_search`] but for the BM25/full-text path.
67/// `CONTAINS_TEXT` is intentionally excluded: it is a strict substring metadata
68/// filter, not a scored full-text search.
69fn condition_has_text_search(cond: &Condition) -> bool {
70    match cond {
71        Condition::Match(_) => true,
72        Condition::And(left, right) | Condition::Or(left, right) => {
73            condition_has_text_search(left) || condition_has_text_search(right)
74        }
75        Condition::Group(inner) | Condition::Not(inner) => condition_has_text_search(inner),
76        _ => false,
77    }
78}
79
80/// Derives the [`QueryOperationKind`] for a resolved query.
81///
82/// MATCH queries are graph traversals. Otherwise the WHERE clause is inspected:
83/// vector + text ⇒ hybrid, vector only ⇒ vector, text only ⇒ text, neither ⇒
84/// a plain relational SELECT.
85fn derive_operation_kind(query: &Query) -> QueryOperationKind {
86    if query.is_match_query() {
87        return QueryOperationKind::GraphTraversal;
88    }
89    let where_clause = query.select.where_clause.as_ref();
90    let has_vector = where_clause.is_some_and(Condition::has_vector_search);
91    let has_text = where_clause.is_some_and(condition_has_text_search);
92    match (has_vector, has_text) {
93        (true, true) => QueryOperationKind::HybridSearch,
94        (true, false) => QueryOperationKind::VectorSearch,
95        (false, true) => QueryOperationKind::TextSearch,
96        (false, false) => QueryOperationKind::Select,
97    }
98}
99
100impl<'a> QueryAccessContext<'a> {
101    /// Builds a read-path [`QueryAccessContext`] from a resolved query.
102    ///
103    /// Borrows the collection name from `query.select.from` and derives the
104    /// [`QueryOperationKind`] from the query shape. `principal` and
105    /// `tenant_hint` are left unset here: they are opaque, caller-supplied
106    /// hints that core never derives from the query itself, so callers that
107    /// have them populate the context after construction.
108    #[must_use]
109    pub fn from_query(query: &'a Query) -> Self {
110        Self {
111            collection: query.select.from.as_str(),
112            operation: derive_operation_kind(query),
113            principal: None,
114            tenant_hint: None,
115        }
116    }
117}
118
119impl Database {
120    /// AND-composes a control-plane [`AccessScope`]'s filter into a query's
121    /// WHERE clause, returning a narrowed clone (Requirement 1.5).
122    ///
123    /// The scope filter is combined with any existing WHERE predicate via
124    /// [`Condition::And`], with the pre-existing predicate as the left operand
125    /// so it is never rewritten or removed — the composition can only *narrow*
126    /// the result set, never widen it. When the query has no WHERE clause, the
127    /// scope filter becomes the WHERE clause. A scope with no filter returns an
128    /// unmodified clone.
129    ///
130    /// `scope.tenant` is deliberately **not** turned into a data-plane
131    /// predicate here: it is an opaque hint the observer/adapter layer records
132    /// and forwards for audit and routing, kept policy-free in core.
133    #[must_use]
134    pub fn apply_scope(query: &Query, scope: &AccessScope) -> Query {
135        let mut narrowed = query.clone();
136        if let Some(filter) = scope.filter.clone() {
137            let scoped_where = match narrowed.select.where_clause.take() {
138                Some(existing) => Condition::And(Box::new(existing), Box::new(filter)),
139                None => filter,
140            };
141            narrowed.select.where_clause = Some(scoped_where);
142        }
143        narrowed
144    }
145
146    /// Produces a canonical JSON string for a `serde_json::Value`.
147    ///
148    /// Recursively sorts the keys of every JSON object so that two values
149    /// representing the same logical structure always produce identical bytes,
150    /// regardless of the `HashMap` iteration order used during serialization.
151    ///
152    /// This is required because `FusionConfig::params` and
153    /// `TrainStatement::params` are `HashMap`-backed; `serde_json` serialises
154    /// them in hash-order, which is non-deterministic across invocations.
155    fn canonical_json(value: serde_json::Value) -> serde_json::Value {
156        match value {
157            serde_json::Value::Object(map) => {
158                // Without the `preserve_order` feature flag, `serde_json::Map` is already
159                // backed by `BTreeMap` and therefore already sorted. This explicit sort
160                // step is kept as defense-in-depth: if `preserve_order` is ever enabled
161                // in `Cargo.toml` (which switches the backing store to `IndexMap` and
162                // preserves insertion order), the canonical key ordering is still upheld
163                // without any change to this function.
164                let sorted: serde_json::Map<String, serde_json::Value> = map
165                    .into_iter()
166                    .map(|(k, v)| (k, Self::canonical_json(v)))
167                    .collect::<std::collections::BTreeMap<_, _>>()
168                    .into_iter()
169                    .collect();
170                serde_json::Value::Object(sorted)
171            }
172            serde_json::Value::Array(arr) => {
173                serde_json::Value::Array(arr.into_iter().map(Self::canonical_json).collect())
174            }
175            other => other,
176        }
177    }
178
179    /// Builds a deterministic cache key for a query (CACHE-02).
180    ///
181    /// Serialises the query to canonical JSON (object keys sorted recursively),
182    /// reads the current `schema_version`, and gathers per-collection
183    /// `write_generation` counters (sorted by collection name) to form a
184    /// `PlanKey`.
185    ///
186    /// # Why canonical JSON instead of `Debug`
187    ///
188    /// `format!("{query:?}")` is non-deterministic when the `Query` AST
189    /// contains `HashMap`-backed fields (`FusionConfig::params`,
190    /// `TrainStatement::params`) because `HashMap` iteration order is not
191    /// guaranteed across invocations. Canonical JSON with sorted object keys
192    /// is stable and produces the same byte sequence for logically identical
193    /// queries.
194    #[must_use]
195    pub fn build_plan_key(&self, query: &crate::velesql::Query) -> crate::cache::PlanKey {
196        use std::hash::{BuildHasher, Hasher};
197
198        // Serialise via serde_json, then canonicalise (sort object keys) before hashing.
199        // Fallback to Debug representation if serialization fails (should never happen in
200        // practice since all Query fields are Serialize, but erring on the side of liveness).
201        let query_text = serde_json::to_value(query)
202            .map(Self::canonical_json)
203            .and_then(|v| serde_json::to_string(&v))
204            .unwrap_or_else(|_| format!("{query:?}"));
205
206        let mut hasher = rustc_hash::FxBuildHasher.build_hasher();
207        hasher.write(query_text.as_bytes());
208        let query_hash = hasher.finish();
209
210        let schema_version = self.schema_version();
211        let collection_names = Self::referenced_collection_names(query);
212
213        // Build generations vector in sorted collection order.
214        let collection_generations: smallvec::SmallVec<[u64; 4]> = collection_names
215            .iter()
216            .map(|name| self.collection_write_generation(name).unwrap_or(0))
217            .collect();
218
219        // Issue #608: parallel vector of analyze generations so that running
220        // ANALYZE alone (no data mutation) still flips the cache key and
221        // rebuilds plans with the fresh calibrated cost estimates.
222        let analyze_generations: smallvec::SmallVec<[u64; 4]> = collection_names
223            .iter()
224            .map(|name| self.collection_analyze_generation(name).unwrap_or(0))
225            .collect();
226
227        crate::cache::PlanKey {
228            // Issue #902: store the canonical text so PlanKey equality is
229            // collision-safe. query_hash stays a Hash accelerator only.
230            query_text: query_text.into(),
231            query_hash,
232            schema_version,
233            collection_generations,
234            analyze_generations,
235        }
236    }
237
238    /// Returns the query plan for a query, with cache status populated (CACHE-02).
239    ///
240    /// If the plan is cached, returns it with `cache_hit: Some(true)` and
241    /// `plan_reuse_count` set. Otherwise generates a fresh plan with
242    /// `cache_hit: Some(false)`.
243    ///
244    /// # Design decision: `explain_query` does not populate the cache
245    ///
246    /// `explain_query` intentionally does **not** insert a new plan into the
247    /// compiled plan cache. EXPLAIN is a diagnostic operation; allowing it to
248    /// influence cache state would make cache metrics (hit/miss ratios,
249    /// `plan_reuse_count`) unreliable because EXPLAIN calls would be
250    /// indistinguishable from real execution hits. Only `execute_query` is
251    /// authorised to write to the cache.
252    ///
253    /// # Errors
254    ///
255    /// Returns an error if the query is invalid.
256    pub fn explain_query(
257        &self,
258        query: &crate::velesql::Query,
259    ) -> Result<crate::velesql::QueryPlan> {
260        crate::velesql::QueryValidator::validate(query).map_err(|e| Error::Query(e.to_string()))?;
261
262        let plan_key = self.build_plan_key(query);
263
264        if let Some(cached) = self.compiled_plan_cache.get(&plan_key) {
265            let mut plan = cached.plan.clone();
266            plan.cache_hit = Some(true);
267            plan.plan_reuse_count = Some(
268                cached
269                    .reuse_count
270                    .load(std::sync::atomic::Ordering::Relaxed),
271            );
272            return Ok(plan);
273        }
274
275        let mut plan = self.build_plan_with_stats(query);
276        plan.cache_hit = Some(false);
277        plan.plan_reuse_count = Some(0);
278        Ok(plan)
279    }
280
281    /// Builds a query plan, resolving calibrated collection statistics AND
282    /// the registered secondary index set from the registry when available
283    /// (#471 — EXPLAIN real costs, #607 — `IndexLookup` wiring).
284    ///
285    /// The returned plan's `estimated_cost_ms` and `filter_strategy` are
286    /// calibrated via `CostEstimator` when stats exist for the query's
287    /// primary collection. Falls back to heuristics otherwise. The
288    /// `indexed_fields` argument is populated from
289    /// `Database::indexed_fields_for` so that `IndexLookup` nodes appear
290    /// in the EXPLAIN tree for WHERE clauses targeting indexed columns.
291    fn build_plan_with_stats(&self, query: &crate::velesql::Query) -> crate::velesql::QueryPlan {
292        let primary = &query.select.from;
293        let core_stats = self.get_collection_stats(primary).ok().flatten();
294        let indexed = self.indexed_fields_for(primary);
295        // For MATCH queries thread the live graph CollectionStats so the
296        // MatchTraversal strategy reflects the real graph shape (backlog #14).
297        let match_stats = query
298            .match_clause
299            .is_some()
300            .then(|| self.match_stats_for(primary))
301            .flatten();
302        crate::velesql::QueryPlan::from_query_with_all_stats(
303            query,
304            &indexed,
305            core_stats.as_ref(),
306            match_stats.as_ref(),
307        )
308    }
309
310    /// Executes a query with instrumentation and returns both plan and actual stats.
311    ///
312    /// Unlike `explain_query` (plan only) and `execute_query` (results only),
313    /// this method returns the full [`ExplainOutput`] with measured statistics.
314    /// The normal `execute_query` path is untouched — zero overhead on
315    /// non-ANALYZE queries.
316    ///
317    /// # Errors
318    ///
319    /// Returns an error if the query is invalid or execution fails.
320    pub fn explain_analyze_query(
321        &self,
322        query: &Query,
323        params: &std::collections::HashMap<String, serde_json::Value>,
324    ) -> Result<ExplainOutput> {
325        crate::velesql::QueryValidator::validate(query).map_err(|e| Error::Query(e.to_string()))?;
326
327        let plan = self.explain_query(query)?;
328        let start = std::time::Instant::now();
329        let (results, nodes, edges) = self.execute_query_counted(query, params)?;
330        let stats = ActualStats::from_counted(results.len() as u64, start.elapsed(), nodes, edges);
331        let node_stats = crate::velesql::build_leaf_node_stats(
332            &plan.root,
333            stats.actual_rows,
334            stats.actual_time_ms,
335        );
336        Ok(ExplainOutput::with_stats(plan, stats, node_stats))
337    }
338
339    /// Executes a `VelesQL` query with database-level JOIN resolution.
340    ///
341    /// This method resolves JOIN target collections from the database registry
342    /// and executes JOIN runtime in sequence. Query plans are cached and
343    /// reused for identical queries against unchanged collections (CACHE-02).
344    ///
345    /// # Errors
346    ///
347    /// Returns an error if the base collection or any JOIN collection is missing.
348    pub fn execute_query(
349        &self,
350        query: &crate::velesql::Query,
351        params: &std::collections::HashMap<String, serde_json::Value>,
352    ) -> Result<Vec<SearchResult>> {
353        // Resolve scalar subqueries (EPIC-039) into literals *before* validation
354        // so the validator and every downstream path see a subquery-free AST.
355        if let Some(rewritten) = self.resolve_subqueries(query, params)? {
356            return self.execute_query(&rewritten, params);
357        }
358
359        crate::velesql::QueryValidator::validate(query).map_err(|e| Error::Query(e.to_string()))?;
360
361        // Requirement 1: read-path control-plane gate. Fires exactly once here
362        // at the `Database` facade for read paths (SELECT + MATCH). Compound /
363        // JOIN sub-executions re-enter `execute_single_select`, not
364        // `execute_query`, so the gate never double-fires. Non-read statements
365        // (DDL/DML/admin/train/introspection) keep their own gates and are not
366        // gated here (Requirement 3.5).
367        //
368        // Requirement 2: `execute_query_timed` wraps the single top-level
369        // `execute_query_inner` call so `on_query` telemetry fires exactly once
370        // after the data-plane op completes. Resolving the `Cow` to a `&Query`
371        // (via deref coercion on `&gated`) keeps the timing in one place rather
372        // than duplicated across the borrowed / owned arms.
373        let gated = self.read_gate(query)?;
374        self.execute_query_timed(&gated, params)
375    }
376
377    /// Executes the resolved (post-gate) query and fires the `on_query`
378    /// telemetry hook exactly once after the data-plane op completes
379    /// (Requirement 2.2, 2.5).
380    ///
381    /// The timer wraps only the single top-level `execute_query_inner` call, so
382    /// compound / UNION / INTERSECT / EXCEPT and JOIN sub-executions that
383    /// re-enter `execute_single_select` are folded into this one measurement
384    /// and never fire their own telemetry.
385    ///
386    /// When no observer is registered, this is a single `Option` presence check
387    /// with no timer and no notification beyond that check (Requirement 2.4).
388    /// The duration is reported in microseconds; `elapsed().as_micros()` is a
389    /// `u128`, converted with a bounds-guarded `try_from` that saturates at
390    /// `u64::MAX` rather than panicking (no `unwrap`/`expect`).
391    fn execute_query_timed(
392        &self,
393        query: &crate::velesql::Query,
394        params: &std::collections::HashMap<String, serde_json::Value>,
395    ) -> Result<Vec<SearchResult>> {
396        let Some(observer) = self.observer.as_ref() else {
397            return self.execute_query_inner(query, params); // zero-overhead fast path
398        };
399        let started = std::time::Instant::now();
400        let results = self.execute_query_inner(query, params)?;
401        let duration_us = u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX);
402        observer.on_query(query.select.from.as_str(), duration_us);
403        Ok(results)
404    }
405
406    /// Applies the read-path control-plane gate (Requirement 1).
407    ///
408    /// Fast path: a single `Option` presence check when no observer is
409    /// registered returns [`Cow::Borrowed`](std::borrow::Cow::Borrowed) with
410    /// zero allocation and zero query clone (Requirement 1.8). When an observer
411    /// is present it is consulted only for read paths (SELECT + MATCH); other
412    /// statement types pass through borrowed because they carry their own
413    /// DDL/DML gates.
414    ///
415    /// * [`AccessDecision::Allow`] ⇒ borrowed, unmodified query (Requirement 1.6).
416    /// * [`AccessDecision::Deny`] ⇒ the supplied error, no results (Requirement 1.4).
417    /// * [`AccessDecision::AllowWithScope`] ⇒ an owned, scope-narrowed clone
418    ///   (Requirement 1.5).
419    ///
420    /// # Errors
421    ///
422    /// Returns the observer's `Err` for an internal failure, or the
423    /// `Deny`-supplied error when access is refused.
424    fn read_gate<'q>(
425        &self,
426        query: &'q crate::velesql::Query,
427    ) -> Result<std::borrow::Cow<'q, crate::velesql::Query>> {
428        // Non-read statements (DDL/DML/admin/train/introspection) carry their
429        // own control-plane gates and must never be double-gated here. The
430        // no-observer fast path is handled inside `read_gate_raw` (single
431        // `Option` check, Requirement 1.8).
432        if self.observer.is_none() || !Self::is_read_path(query) {
433            return Ok(std::borrow::Cow::Borrowed(query));
434        }
435        match self.read_gate_raw(
436            query.select.from.as_str(),
437            derive_operation_kind(query),
438            None,
439            None,
440        )? {
441            RawGateOutcome::Allow => Ok(std::borrow::Cow::Borrowed(query)),
442            RawGateOutcome::Deny(err) => Err(err),
443            RawGateOutcome::Scope(scope) => {
444                Ok(std::borrow::Cow::Owned(Self::apply_scope(query, &scope)))
445            }
446        }
447    }
448
449    /// Non-VelesQL read-path gate, shared by [`read_gate`](Self::read_gate) and
450    /// the raw `gated_search` read path (vector / text / hybrid / graph search
451    /// and memory recall that never build a `VelesQL` [`Query`]).
452    ///
453    /// Fast path: a single `Option` presence check when no observer is
454    /// registered returns [`RawGateOutcome::Allow`] with zero allocation and no
455    /// hook call, preserving the zero-overhead contract (Requirement 1.8). When
456    /// an observer is present it builds a [`QueryAccessContext`] from the
457    /// caller-supplied collection / operation / principal / tenant and consults
458    /// [`on_query_request`](crate::observer::DatabaseObserver::on_query_request).
459    ///
460    /// Unlike [`read_gate`](Self::read_gate), the caller is responsible for
461    /// having already established that this is a read path — the raw callers are
462    /// search primitives that are reads by construction.
463    ///
464    /// # Errors
465    ///
466    /// Returns the observer's `Err` for an internal failure. Access denial is
467    /// carried in [`RawGateOutcome::Deny`], not the `Result` error channel.
468    pub(crate) fn read_gate_raw(
469        &self,
470        collection: &str,
471        operation: QueryOperationKind,
472        principal: Option<&str>,
473        tenant_hint: Option<&str>,
474    ) -> Result<RawGateOutcome> {
475        let Some(observer) = self.observer.as_ref() else {
476            return Ok(RawGateOutcome::Allow); // zero-overhead fast path
477        };
478        let ctx = QueryAccessContext {
479            collection,
480            operation,
481            principal,
482            tenant_hint,
483        };
484        match observer.on_query_request(&ctx)? {
485            AccessDecision::Allow => Ok(RawGateOutcome::Allow),
486            AccessDecision::Deny(err) => Ok(RawGateOutcome::Deny(err)),
487            AccessDecision::AllowWithScope(scope) => Ok(RawGateOutcome::Scope(scope)),
488        }
489    }
490
491    /// Test-only accessor exposing [`read_gate`](Self::read_gate)'s [`Cow`]
492    /// result so tests can assert the no-observer read path is a single pointer
493    /// check that returns [`Cow::Borrowed`](std::borrow::Cow::Borrowed) with no
494    /// query clone (Requirement 8.2 — Quality Bar Gate 2, p50 latency).
495    ///
496    /// Compiled only under `cfg(test)`, so it adds nothing to the production
497    /// surface. The full ≤ 450 µs wall-clock p50 contract is enforced
498    /// separately by the `Perf Gate (E2E)` workflow
499    /// (`.github/workflows/perf-gate-e2e.yml`); this accessor pins the
500    /// structural "zero-overhead when no observer" half of the gate
501    /// deterministically, without a flaky timing threshold.
502    #[cfg(test)]
503    pub(crate) fn read_gate_cow_for_test<'q>(
504        &self,
505        query: &'q crate::velesql::Query,
506    ) -> Result<std::borrow::Cow<'q, crate::velesql::Query>> {
507        self.read_gate(query)
508    }
509
510    /// Returns `true` when the statement is a gated read path (SELECT or MATCH).
511    ///
512    /// Admin, introspection, DDL, TRAIN, and DML statements are excluded: they
513    /// route through their own control-plane gates and must not be double-gated
514    /// by the read-path hook.
515    fn is_read_path(query: &crate::velesql::Query) -> bool {
516        matches!(
517            classify_statement(query),
518            StatementType::Match | StatementType::Select
519        )
520    }
521
522    /// Executes a query after the read gate has resolved (Requirement 1).
523    ///
524    /// This is the single dispatch entry the gate delegates to; it fires
525    /// exactly once per top-level query and is *not* re-entered by compound /
526    /// JOIN sub-executions, so telemetry (Task 5.1) can wrap it cleanly without
527    /// double-counting.
528    fn execute_query_inner(
529        &self,
530        query: &crate::velesql::Query,
531        params: &std::collections::HashMap<String, serde_json::Value>,
532    ) -> Result<Vec<SearchResult>> {
533        if let Some(results) = self.dispatch_non_select(query, params)? {
534            return Ok(results);
535        }
536
537        // Build plan key and check cache WITHOUT recording hit/miss metrics (CACHE-02).
538        //
539        // `contains()` is used instead of `get().is_some()` so that this
540        // existence check does not increment the hit/miss counters or
541        // `reuse_count`. Only `explain_query` (which surfaces these values to
542        // callers) should call `get()`.
543        let pre_exec_key = self.build_plan_key(query);
544        let is_cached = self.compiled_plan_cache.contains(&pre_exec_key);
545
546        let results = self.execute_select_query(query, params)?;
547
548        // Populate cache on miss (CACHE-02).
549        //
550        // C-1 TOCTOU fix: rebuild the plan key AFTER execution. Between the
551        // pre-execution `contains()` check and here, a concurrent writer may
552        // have bumped a collection's `write_generation` (e.g. via `upsert` on
553        // another thread). Rebuilding the key captures the post-execution
554        // state, so the cached plan is associated with the generation that was
555        // live when the plan was actually compiled — not a potentially stale
556        // pre-execution snapshot.
557        if !is_cached {
558            self.populate_plan_cache(query);
559        }
560
561        Ok(results)
562    }
563
564    /// Classifies and dispatches non-SELECT statement types.
565    ///
566    /// Returns `Ok(Some(results))` if handled, `Ok(None)` for SELECT queries.
567    fn dispatch_non_select(
568        &self,
569        query: &crate::velesql::Query,
570        params: &std::collections::HashMap<String, serde_json::Value>,
571    ) -> Result<Option<Vec<SearchResult>>> {
572        // Classify the statement type (at most one is Some).
573        let stmt_type = classify_statement(query);
574        match stmt_type {
575            StatementType::Admin(admin) => Ok(Some(self.execute_admin(admin)?)),
576            StatementType::Introspection(intro) => Ok(Some(self.execute_introspection(intro)?)),
577            StatementType::Ddl(ddl) => Ok(Some(self.execute_ddl(ddl)?)),
578            StatementType::Train(train) => Ok(Some(self.execute_train(train)?)),
579            StatementType::Dml(dml) => Ok(Some(self.execute_dml(dml, params)?)),
580            StatementType::Match => Ok(Some(self.execute_match_routed(query, params)?.0)),
581            StatementType::Select => Ok(None),
582        }
583    }
584
585    /// Resolves the target collection for a MATCH query.
586    ///
587    /// Resolution order: `SELECT ... FROM <collection> WHERE MATCH ...`, then a
588    /// `"_collection"` key in `params` (programmatic API), else a guidance error.
589    fn resolve_match_collection(
590        &self,
591        query: &crate::velesql::Query,
592        params: &std::collections::HashMap<String, serde_json::Value>,
593    ) -> Result<crate::collection::Collection> {
594        let collection_name = if !query.select.from.is_empty() {
595            query.select.from.clone()
596        } else if let Some(serde_json::Value::String(name)) = params.get("_collection") {
597            name.clone()
598        } else {
599            return Err(Error::Query(
600                "MATCH query requires a target collection. Either use \
601                 SELECT ... FROM <collection> WHERE MATCH ..., or pass \
602                 {\"_collection\": \"name\"} in params."
603                    .to_string(),
604            ));
605        };
606        self.resolve_collection(&collection_name)
607    }
608
609    /// Routes a MATCH query to its target collection and applies cross-collection
610    /// enrichment, returning results plus the graph-traversal counters
611    /// `(nodes_visited, edges_traversed)` measured during execution (for
612    /// EXPLAIN ANALYZE; the plain execution path discards them).
613    fn execute_match_routed(
614        &self,
615        query: &crate::velesql::Query,
616        params: &std::collections::HashMap<String, serde_json::Value>,
617    ) -> Result<(Vec<SearchResult>, u64, u64)> {
618        let coll = self.resolve_match_collection(query, params)?;
619        let (mut results, nodes_visited, edges_traversed) =
620            coll.execute_query_counted(query, params)?;
621        // Cross-collection enrichment: if any node pattern has a @collection
622        // annotation, look up payloads from those collections and merge them
623        // into the projected fields.
624        if let Some(mc) = &query.match_clause {
625            self.enrich_match_results_cross_collection(mc, &mut results);
626        }
627        Ok((results, nodes_visited, edges_traversed))
628    }
629
630    /// Executes a query and returns graph-traversal counters for EXPLAIN ANALYZE.
631    ///
632    /// MATCH queries report real `(nodes_visited, edges_traversed)`; every other
633    /// statement type reports `(_, 0, 0)` (no graph traversal occurred).
634    fn execute_query_counted(
635        &self,
636        query: &Query,
637        params: &std::collections::HashMap<String, serde_json::Value>,
638    ) -> Result<(Vec<SearchResult>, u64, u64)> {
639        if query.is_match_query() {
640            // Apply the read-path gate before the MATCH executor. The non-EXPLAIN
641            // MATCH path is gated inside `execute_query`; this counted path (used
642            // by EXPLAIN ANALYZE) routes straight to `execute_match_routed`, so
643            // without this it would let EXPLAIN ANALYZE MATCH bypass governance.
644            let gated = self.read_gate(query)?;
645            return self.execute_match_routed(&gated, params);
646        }
647        Ok((self.execute_query(query, params)?, 0, 0))
648    }
649
650    /// Executes the SELECT portion of a query, resolving JOINs if present.
651    fn execute_select_query(
652        &self,
653        query: &crate::velesql::Query,
654        params: &std::collections::HashMap<String, serde_json::Value>,
655    ) -> Result<Vec<SearchResult>> {
656        // EPIC-040 US-006: For compound queries, strip LIMIT from each operand so
657        // the set operation sees the full result sets.  The final LIMIT is applied
658        // once on the merged output (SQL-standard behaviour).
659        // Use MAX_LIMIT (not None) to avoid the default-10 cap downstream.
660        const COMPOUND_LIMIT: usize = 100_000;
661        let compound_limit = Some(COMPOUND_LIMIT as u64); // 100_000 fits u64 exactly.
662        let left_results = if query.compound.is_some() {
663            let mut left_query = query.clone();
664            left_query.select.limit = compound_limit;
665            self.execute_single_select(&left_query, params)?
666        } else {
667            return self.execute_single_select(query, params);
668        };
669
670        // compound is guaranteed Some here (non-compound returns above).
671        if let Some(ref compound) = query.compound {
672            let mut accumulated = left_results;
673            for (operator, right_select) in &compound.operations {
674                let mut right_query = crate::velesql::Query::new_select(right_select.clone());
675                right_query.select.limit = compound_limit;
676                let right_results = self.execute_single_select(&right_query, params)?;
677                accumulated = crate::collection::search::query::set_operations::apply_set_operation(
678                    accumulated,
679                    right_results,
680                    *operator,
681                    // Intermediate ops keep the server-side ceiling: truncating to the
682                    // user LIMIT here would drop rows a later chained set op still needs.
683                    COMPOUND_LIMIT,
684                );
685            }
686            // SQL-standard: LIMIT from the left (outer) SELECT applies to the final result.
687            if let Some(limit) = query.select.limit {
688                accumulated.truncate(usize::try_from(limit).unwrap_or(usize::MAX));
689            }
690            return Ok(accumulated);
691        }
692
693        Ok(left_results)
694    }
695
696    /// Collects sorted, deduplicated collection names referenced by a query,
697    /// including all compound operands (UNION, INTERSECT, EXCEPT).
698    ///
699    /// RF-DEDUP: Shared by `build_plan_key` and `populate_plan_cache`, which
700    /// both need the same sorted collection-name list from the query AST.
701    fn referenced_collection_names(query: &crate::velesql::Query) -> Vec<String> {
702        let mut names = vec![query.select.from.clone()];
703        for join in &query.select.joins {
704            names.push(join.table.clone());
705        }
706        if let Some(ref compound) = query.compound {
707            for (_, right_select) in &compound.operations {
708                names.push(right_select.from.clone());
709                for join in &right_select.joins {
710                    names.push(join.table.clone());
711                }
712            }
713        }
714        names.sort();
715        names.dedup();
716        names
717    }
718
719    /// Resolves a collection by name from all typed registries.
720    ///
721    /// Priority: vector collections first, then graph, then metadata.
722    /// Returns the inner `Collection` for query execution.
723    pub(super) fn resolve_collection(&self, name: &str) -> Result<crate::collection::Collection> {
724        if let Some(vc) = self.get_vector_collection(name) {
725            return Ok(vc.inner);
726        }
727        if let Some(gc) = self.get_graph_collection(name) {
728            return Ok(gc.inner);
729        }
730        if let Some(mc) = self.get_metadata_collection(name) {
731            return Ok(mc.inner);
732        }
733        Err(Error::CollectionNotFound(name.to_string()))
734    }
735
736    /// Resolves a collection that supports write operations (INSERT/UPDATE/TRAIN).
737    ///
738    /// Checks vector, graph, and metadata collections. Metadata-only collections
739    /// support INSERT/UPDATE for metadata fields (no vectors).
740    pub(super) fn resolve_writable_collection(
741        &self,
742        name: &str,
743    ) -> Result<crate::collection::Collection> {
744        if let Some(vc) = self.get_vector_collection(name) {
745            return Ok(vc.inner);
746        }
747        if let Some(gc) = self.get_graph_collection(name) {
748            return Ok(gc.inner);
749        }
750        if let Some(mc) = self.get_metadata_collection(name) {
751            return Ok(mc.inner);
752        }
753        Err(Error::CollectionNotFound(name.to_string()))
754    }
755
756    /// Executes a single SELECT (no compound), resolving JOINs if present.
757    ///
758    /// Orchestrates filter pushdown and join strategy selection:
759    /// 1. Analyze WHERE for pushdown-eligible conditions
760    /// 2. Strip pushed conditions from base query
761    /// 3. For each JOIN: lookup, filtered, or full `ColumnStore` path
762    /// 4. Apply post-join filters (cross-source predicates)
763    fn execute_single_select(
764        &self,
765        query: &crate::velesql::Query,
766        params: &std::collections::HashMap<String, serde_json::Value>,
767    ) -> Result<Vec<SearchResult>> {
768        let base_collection = self.resolve_collection(&query.select.from)?;
769
770        let mut single_query = query.clone();
771        single_query.compound = None;
772
773        if single_query.select.joins.is_empty() {
774            return base_collection.execute_query(&single_query, params);
775        }
776
777        let analysis = Self::prepare_join_pushdown(&mut single_query, params)?;
778        let pushed = analysis.column_store_filters.clone();
779
780        let row_budget = Self::join_row_budget(&query.select, &analysis);
781
782        let mut results = base_collection.execute_query(&single_query, params)?;
783        for join in &query.select.joins {
784            results = self.execute_single_join(&results, join, &pushed, row_budget)?;
785        }
786
787        // Apply post-join filters: cross-source predicates that reference
788        // columns from both the base collection and joined ColumnStore tables.
789        if !analysis.post_join_filters.is_empty() {
790            results = Self::apply_post_join_filters(
791                &base_collection,
792                results,
793                &analysis.post_join_filters,
794                params,
795                &query.select.from_alias,
796            )?;
797        }
798
799        Ok(results)
800    }
801
802    /// Resolves WHERE parameters, runs pushdown analysis, and strips pushed
803    /// conditions from the base query (JOIN path of `execute_single_select`).
804    ///
805    /// Parameter placeholders are resolved before the analysis so pushed-down
806    /// filters never silently convert them to NULL at the `ColumnStore` layer
807    /// (the collection pipeline resolves its own copy independently).
808    fn prepare_join_pushdown(
809        single_query: &mut crate::velesql::Query,
810        params: &std::collections::HashMap<String, serde_json::Value>,
811    ) -> Result<crate::collection::search::query::pushdown::PushdownAnalysis> {
812        if let Some(cond) = single_query.select.where_clause.take() {
813            single_query.select.where_clause = Some(
814                crate::collection::Collection::resolve_condition_params(&cond, params)?,
815            );
816        }
817
818        let analysis = Self::analyze_join_pushdown_for_select(&single_query.select);
819
820        let resolved_where = single_query.select.where_clause.clone();
821        single_query.select.joins.clear();
822        if !analysis.column_store_filters.is_empty() {
823            single_query.select.where_clause = Self::strip_pushed_conditions(
824                resolved_where.as_ref(),
825                &analysis.column_store_filters,
826            );
827        }
828        Ok(analysis)
829    }
830
831    /// Computes the bound on joined rows to materialize.
832    ///
833    /// When the query has an explicit LIMIT, no post-join filters, and no
834    /// ORDER BY (which could reorder past the window), the bound is the
835    /// effective `LIMIT + OFFSET`. GROUP BY / HAVING / DISTINCT also disqualify
836    /// the bounded shape: SQL LIMIT bounds output *groups/rows*, not input rows,
837    /// so truncating joined input to `LIMIT` would drop rows that belong to
838    /// groups still inside the window. Otherwise downstream stages may reorder or
839    /// drop rows, so we fall back to the conservative server-side ceiling
840    /// [`JOIN_ROW_CEILING`] — still bounding OOM without affecting correctness.
841    pub(super) fn join_row_budget(
842        select: &crate::velesql::SelectStatement,
843        analysis: &crate::collection::search::query::pushdown::PushdownAnalysis,
844    ) -> usize {
845        use crate::collection::search::query::JOIN_ROW_CEILING;
846        use crate::velesql::DistinctMode;
847        let bounded_shape = analysis.post_join_filters.is_empty()
848            && select.order_by.is_none()
849            && select.group_by.is_none()
850            && select.having.is_none()
851            && select.distinct == DistinctMode::None;
852        match select.limit {
853            Some(limit) if bounded_shape => {
854                let limit = usize::try_from(limit).unwrap_or(JOIN_ROW_CEILING);
855                let offset = select
856                    .offset
857                    .map_or(0, |o| usize::try_from(o).unwrap_or(JOIN_ROW_CEILING));
858                limit.saturating_add(offset).min(JOIN_ROW_CEILING)
859            }
860            _ => JOIN_ROW_CEILING,
861        }
862    }
863
864    // NOTE: analyze_join_pushdown_for_select, apply_post_join_filters
865    // moved to join_pushdown.rs (NLOC/file reduction)
866
867    /// Inserts a compiled plan into the cache after a cache miss (CACHE-02).
868    fn populate_plan_cache(&self, query: &crate::velesql::Query) {
869        let compiled = std::sync::Arc::new(crate::cache::CompiledPlan {
870            plan: self.build_plan_with_stats(query),
871            referenced_collections: Self::referenced_collection_names(query),
872            compiled_at: std::time::Instant::now(),
873            reuse_count: std::sync::atomic::AtomicU64::new(0),
874        });
875        // Rebuild key after execution to reflect current write_generation (C-1).
876        let post_exec_key = self.build_plan_key(query);
877        self.compiled_plan_cache.insert(post_exec_key, compiled);
878    }
879
880    /// Dispatches a DML statement (INSERT, UPSERT, UPDATE, DELETE, or edge mutations).
881    pub(super) fn execute_dml(
882        &self,
883        dml: &crate::velesql::DmlStatement,
884        params: &std::collections::HashMap<String, serde_json::Value>,
885    ) -> Result<Vec<SearchResult>> {
886        match dml {
887            crate::velesql::DmlStatement::Insert(stmt)
888            | crate::velesql::DmlStatement::Upsert(stmt) => self.execute_insert(stmt, params),
889            crate::velesql::DmlStatement::Update(stmt) => self.execute_update(stmt, params),
890            crate::velesql::DmlStatement::InsertEdge(stmt) => self.execute_insert_edge(stmt),
891            crate::velesql::DmlStatement::Delete(stmt) => self.execute_delete(stmt),
892            crate::velesql::DmlStatement::DeleteEdge(stmt) => self.execute_delete_edge(stmt),
893            crate::velesql::DmlStatement::SelectEdges(stmt) => self.execute_select_edges(stmt),
894            crate::velesql::DmlStatement::InsertNode(stmt) => self.execute_insert_node(stmt),
895        }
896    }
897}