Skip to main content

omgbase_surface/
planner.rs

1//! The tier-3 pushdown planner: reduces the row set a query scans by
2//! translating its pushable top-level `where` conjuncts into ONE SQL
3//! statement against the store, then handing the produced rows (plus the
4//! untranslatable residual) back to the in-memory engine to finish. Port of
5//! `packages/core/src/oqx-js/planner.ts` over the [`oqx`] seam
6//! ([`QueryPlanner`], [`Plan`], [`oqx::partition_pushable`],
7//! [`oqx::residual_query`], [`oqx::ROWS_ROOT`]).
8//!
9//! Correctness is guaranteed by the residual fallback — anything
10//! [`crate::translate`] declines stays in-memory — and verified by the
11//! differential gate (planned == in-memory over every corpus-backed query
12//! case and the conformance list). Deliberately conservative: only simple
13//! top-level target scans (no `follow`, no `from E` re-projection) whose
14//! source is a bare `docs|blocks|nodes|edges` or `$repo.<target>`, with at
15//! least one pushable scalar conjunct, are planned; everything else declines
16//! to a full in-memory run.
17//!
18//! One shape difference from the reference, forced by ownership: the
19//! reference attaches a store context to its plan (`makeStoreContext(…,
20//! rowsRoot)`), but a [`crate::StoreContext`] borrows the store's connection
21//! and `Plan::context` must be `'static`, so the plan carries no context and
22//! the runner ([`mod@crate::query`]) builds the rows-root context itself
23//! ([`crate::StoreContext::with_rows_root`]) — the same six lines
24//! `oqx::PlannedEngine::run` would execute.
25
26use oqx::Consumer;
27use oqx::ast::{Expr, Follow, FollowDestination, OpNode, Query, SelectItem, Subquery, Where};
28use oqx::{Plan, QueryPlanner, Value, partition_pushable, residual_query};
29use rusqlite::Connection;
30use rusqlite::types::Value as SqlValue;
31
32use crate::context::{Target, fetch_rows, tag_rows};
33use crate::translate::{RESERVED_DOC_BASENAMES, TranslateCtx, translate_predicate};
34
35/// The SQL aliases of the scanned row (`self`) and its owning doc (`doc`).
36fn aliases(t: Target) -> (&'static str, &'static str) {
37    match t {
38        Target::Docs => ("d", "d"),
39        Target::Blocks => ("b", "d"),
40        Target::Nodes => ("n", "d"),
41        Target::Edges => ("e", "d"),
42    }
43}
44
45pub(crate) fn from_clause(t: Target) -> &'static str {
46    match t {
47        Target::Docs => "docs d",
48        Target::Blocks => "blocks b JOIN docs d ON d.doc_id = b.doc_id",
49        Target::Nodes => "nodes n JOIN docs d ON d.doc_id = n.doc_id",
50        Target::Edges => "edges e JOIN docs d ON d.doc_id = e.src_doc",
51    }
52}
53
54/// Row columns + the owning-doc path as `__path` (matches the context's
55/// roots so produced rows are indistinguishable from a full scan's).
56pub(crate) fn columns(t: Target) -> &'static str {
57    match t {
58        Target::Docs => "d.*",
59        Target::Blocks => "b.*, d.path AS __path",
60        Target::Nodes => "n.*, d.path AS __path",
61        Target::Edges => "e.*, d.path AS __path",
62    }
63}
64
65/// The root order (`spec/surface` §1.1).
66pub(crate) fn order_clause(t: Target) -> &'static str {
67    match t {
68        Target::Docs => "d.path, d.doc_id",
69        Target::Blocks => "d.path, b.block_id",
70        Target::Nodes => "d.path, n.node_id",
71        Target::Edges => "d.path, e.edge_id",
72    }
73}
74
75/// The liveness guards of the root scan, with the repo id bound.
76pub(crate) fn guards(t: Target) -> &'static str {
77    match t {
78        Target::Docs => "d.repo_id = ? AND d.deleted_commit IS NULL",
79        Target::Blocks => "b.repo_id = ? AND b.deleted_commit IS NULL AND d.deleted_commit IS NULL",
80        Target::Nodes => "n.repo_id = ? AND d.deleted_commit IS NULL",
81        Target::Edges => "e.repo_id = ? AND e.to_commit IS NULL AND d.deleted_commit IS NULL",
82    }
83}
84
85/// The joined targets driven FROM the document: the same rows and columns as
86/// [`from_clause`], with the loop order fixed by `CROSS JOIN` so a predicate on
87/// the document (`d.path = ?`) is the outer search and the target's rows are
88/// reached through their `doc_id` / `src_doc` index (the store indexes'
89/// `$path` probes). [`guards_by_doc`] goes with it; `Docs` is `from_clause`.
90pub(crate) fn from_by_doc(t: Target) -> &'static str {
91    match t {
92        Target::Docs => from_clause(t),
93        Target::Blocks => "docs d CROSS JOIN blocks b ON b.doc_id = d.doc_id",
94        Target::Nodes => "docs d CROSS JOIN nodes n ON n.doc_id = d.doc_id",
95        Target::Edges => "docs d CROSS JOIN edges e ON e.src_doc = d.doc_id",
96    }
97}
98
99/// [`guards`] for a [`from_by_doc`] statement: the same tests, with the
100/// document's repo first and the target's repo term behind SQLite's unary `+`
101/// so it stays a filter and never selects a `(repo_id, …)` index over the
102/// `doc_id` one. Two repo-id binds (`Docs`: one, as `guards`).
103pub(crate) fn guards_by_doc(t: Target) -> &'static str {
104    match t {
105        Target::Docs => guards(t),
106        Target::Blocks => {
107            "d.repo_id = ? AND +b.repo_id = ? AND b.deleted_commit IS NULL AND d.deleted_commit IS NULL"
108        }
109        Target::Nodes => "d.repo_id = ? AND +n.repo_id = ? AND d.deleted_commit IS NULL",
110        Target::Edges => {
111            "d.repo_id = ? AND +e.repo_id = ? AND e.to_commit IS NULL AND d.deleted_commit IS NULL"
112        }
113    }
114}
115
116/// The root collection a query scans, if it is a bare `docs|blocks|nodes|edges`
117/// or `$repo.<target>` source (else `None` — not a pushable shape).
118fn root_target(source: &Expr) -> Option<Target> {
119    match source {
120        Expr::Ident { name, .. } => Target::parse(name),
121        Expr::Member { recv, name, .. } => match &**recv {
122            Expr::Ident { name: r, .. } if r == "$repo" => Target::parse(name),
123            _ => None,
124        },
125        _ => None,
126    }
127}
128
129// ---- the residual-error decline (surface 1.1 patch, §1) ---------------------------------
130
131/// Whether a residual `where` could raise an OQX eval error the pushed
132/// conjuncts might hide by emptying the scan. In memory every conjunct of the
133/// original `&&` is evaluated for the first row and a throwing one aborts the
134/// run; planned, a pushed conjunct that matches no row means the residual
135/// never runs and the error vanishes. So a residual containing any function
136/// or method call (an unknown function, a bad regex, a wrong arity…), a
137/// nested block with the `single` consumer (more than one row raises), a
138/// `^`-escaped name (no enclosing scope at the top level) or a bare reserved
139/// docs basename (`path` for `$path`…, the guard in `get`) sends the whole
140/// query to the in-memory engine unplanned. Only comparisons, logical
141/// operators, `in`, `!`, literals, bindings and plain reads keep the push.
142///
143/// The walk is generic over the whole `oqx` AST — every `Where` node, every
144/// nested block (its `from`, `where`, `select`, `order by`, `follow`,
145/// `limit` / `offset`) and every `Expr`. A `^name:` lift in a nested select
146/// counts as a `^`-escaped name. Inside a block the rows are a different
147/// scope (a relation's rows), so a bare reserved name is an ordinary read
148/// there (`root` is false) — only `doc.<reserved>` still raises at any depth.
149/// Same decisions as the reference's `residualMayRaise`.
150fn residual_may_raise(w: &Where, target: Target) -> bool {
151    where_may_raise(w, target, true)
152}
153
154fn where_may_raise(w: &Where, target: Target, root: bool) -> bool {
155    match w {
156        Where::And { parts, .. } | Where::Or { parts, .. } => {
157            parts.iter().any(|p| where_may_raise(p, target, root))
158        }
159        Where::Not { expr, .. } => where_may_raise(expr, target, root),
160        Where::Scalar { expr, .. } => expr_may_raise(expr, target, root),
161        Where::Op(op) => op_may_raise(op, target, root),
162    }
163}
164
165fn op_may_raise(op: &OpNode, target: Target, root: bool) -> bool {
166    op.op == Consumer::Single
167        || expr_may_raise(&op.receiver, target, root)
168        || subquery_may_raise(&op.sub, target)
169}
170
171fn subquery_may_raise(sub: &Subquery, target: Target) -> bool {
172    let inner = |e: &Expr| expr_may_raise(e, target, false);
173    sub.from.iter().any(inner)
174        || sub
175            .r#where
176            .as_ref()
177            .is_some_and(|w| where_may_raise(w, target, false))
178        || sub.select.iter().any(|item| match item {
179            SelectItem::Field { expr, lift, .. } => *lift > 0 || inner(expr),
180            SelectItem::Collect { op, .. } => op_may_raise(op, target, false),
181        })
182        || sub.order_by.iter().flatten().any(|o| inner(&o.expr))
183        || sub
184            .follow
185            .as_ref()
186            .is_some_and(|f| follow_may_raise(f, target))
187        || sub.limit.as_ref().is_some_and(inner)
188        || sub.offset.as_ref().is_some_and(inner)
189}
190
191fn follow_may_raise(f: &Follow, target: Target) -> bool {
192    let inner = |e: &Expr| expr_may_raise(e, target, false);
193    f.destinations.iter().any(|d| match d {
194        FollowDestination::Relation(e) => inner(e),
195        FollowDestination::Block(op) => op_may_raise(op, target, false),
196    }) || f.r#where.as_ref().is_some_and(inner)
197        || f.frontier.as_ref().is_some_and(inner)
198        || f.by.as_ref().is_some_and(inner)
199}
200
201fn is_reserved(name: &str) -> bool {
202    RESERVED_DOC_BASENAMES.contains(&name)
203}
204
205fn expr_may_raise(e: &Expr, target: Target, root: bool) -> bool {
206    let again = |e: &Expr| expr_may_raise(e, target, root);
207    match e {
208        Expr::Lit { .. } | Expr::Binding { .. } => false,
209        Expr::Ident { name, .. } => root && target == Target::Docs && is_reserved(name),
210        Expr::Outer { .. } | Expr::Call { .. } => true,
211        // `doc.<reserved>`: the reach-through row is a doc (the row itself on
212        // docs), so the guard fires on any target at any depth.
213        Expr::Member { recv, name, .. } => {
214            (is_reserved(name) && matches!(&**recv, Expr::Ident { name, .. } if name == "doc"))
215                || again(recv)
216        }
217        Expr::Unary { expr, .. } => again(expr),
218        Expr::Binary { left, right, .. }
219        | Expr::Logical { left, right, .. }
220        | Expr::In { left, right, .. } => again(left) || again(right),
221        Expr::Range { lo, hi, .. } => {
222            lo.as_deref().is_some_and(again) || hi.as_deref().is_some_and(again)
223        }
224    }
225}
226
227/// A compiled plan before execution: the statement, its params and the
228/// residual query. Pure — what the planner would run, for inspection.
229#[derive(Clone, Debug, PartialEq)]
230pub struct Compiled {
231    pub target: Target,
232    pub sql: String,
233    pub params: Vec<SqlValue>,
234    pub residual: Query,
235}
236
237/// Compile `query` against `repo_id`, or `None` when the shape declines: a
238/// `follow`, a `from E` re-projection, a source that is not a root scan, or
239/// no pushable conjunct at all (the engine then does everything).
240#[must_use]
241pub fn compile(query: &Query, params: &[Value], repo_id: &str) -> Option<Compiled> {
242    if query.follow.is_some() || !query.from.is_empty() {
243        return None;
244    }
245    let target = root_target(&query.source)?;
246    let (self_alias, doc_alias) = aliases(target);
247    let ctx = TranslateCtx {
248        target,
249        self_alias,
250        doc_alias,
251        params,
252    };
253    let (pushed, residual) = partition_pushable(query.r#where.as_ref(), |e| {
254        translate_predicate(e, &ctx).is_some()
255    });
256    if pushed.is_empty() {
257        return None;
258    }
259    // Decline (c): a residual that could raise must not be hidden behind an
260    // emptied scan — the whole query runs in memory.
261    if residual
262        .as_ref()
263        .is_some_and(|w| residual_may_raise(w, target))
264    {
265        return None;
266    }
267    let mut where_sql = guards(target).to_owned();
268    let mut sql_params = vec![SqlValue::Text(repo_id.to_owned())];
269    for e in &pushed {
270        let frag = translate_predicate(e, &ctx).expect("accepted by partition_pushable");
271        where_sql.push_str(" AND (");
272        where_sql.push_str(&frag.sql);
273        where_sql.push(')');
274        sql_params.extend(frag.params);
275    }
276    let sql = format!(
277        "SELECT {} FROM {} WHERE {where_sql} ORDER BY {}",
278        columns(target),
279        from_clause(target),
280        order_clause(target)
281    );
282    Some(Compiled {
283        target,
284        sql,
285        params: sql_params,
286        residual: residual_query(query, residual),
287    })
288}
289
290/// The SQLite planner over one repo of the store.
291pub struct SqlitePlanner<'a> {
292    conn: &'a Connection,
293    repo_id: String,
294}
295
296impl<'a> SqlitePlanner<'a> {
297    #[must_use]
298    pub fn new(conn: &'a Connection, repo_id: &str) -> Self {
299        Self {
300            conn,
301            repo_id: repo_id.to_owned(),
302        }
303    }
304
305    /// Plan `query`: `Ok(None)` when the shape declines, `Ok(Some(plan))`
306    /// with the produced rows (tagged like the context's root rows) and the
307    /// residual, `Err` when the statement itself failed (a store error, not
308    /// a decline — the runner reports it rather than silently rescanning).
309    pub fn try_plan(&self, query: &Query, params: &[Value]) -> rusqlite::Result<Option<Plan>> {
310        let Some(compiled) = compile(query, params, &self.repo_id) else {
311            return Ok(None);
312        };
313        let rows = fetch_rows(self.conn, &compiled.sql, &compiled.params)?;
314        Ok(Some(Plan::new(
315            tag_rows(rows, compiled.target),
316            compiled.residual,
317        )))
318    }
319}
320
321impl QueryPlanner for SqlitePlanner<'_> {
322    /// The seam's shape: a failed statement declines (the engine falls back
323    /// to a full scan). The runner uses [`Self::try_plan`] to surface it.
324    fn plan(&self, query: &Query, params: &[Value]) -> Option<Plan> {
325        self.try_plan(query, params).ok().flatten()
326    }
327}
328
329#[cfg(test)]
330mod tests {
331    use super::*;
332    use oqx::ROWS_ROOT;
333    use oqx::ast::Where;
334
335    fn parse(src: &str) -> Query {
336        oqx::parse_string(src).expect("parses")
337    }
338
339    fn text(s: &str) -> SqlValue {
340        SqlValue::Text(s.to_owned())
341    }
342
343    #[test]
344    fn a_pushable_scan_compiles_to_one_statement_in_root_order() {
345        let c =
346            compile(&parse("from docs where $path == \"index.md\""), &[], "r_1").expect("planned");
347        assert_eq!(c.target, Target::Docs);
348        assert_eq!(
349            c.sql,
350            "SELECT d.* FROM docs d WHERE d.repo_id = ? AND d.deleted_commit IS NULL AND ((d.path IS ?)) ORDER BY d.path, d.doc_id"
351        );
352        assert_eq!(c.params, vec![text("r_1"), text("index.md")]);
353        assert_eq!(
354            c.residual.source,
355            Expr::Ident {
356                name: ROWS_ROOT.to_owned(),
357                span: oqx::Span::EMPTY,
358            }
359        );
360        assert_eq!(c.residual.r#where, None);
361    }
362
363    #[test]
364    fn every_target_has_its_join_columns_guards_and_order() {
365        let b = compile(
366            &parse("from blocks where $path.startsWith(\"lab/\")"),
367            &[],
368            "r",
369        )
370        .unwrap();
371        assert_eq!(
372            b.sql,
373            "SELECT b.*, d.path AS __path FROM blocks b JOIN docs d ON d.doc_id = b.doc_id \
374             WHERE b.repo_id = ? AND b.deleted_commit IS NULL AND d.deleted_commit IS NULL \
375             AND ((substr(d.path, 1, length(?)) = ?)) ORDER BY d.path, b.block_id"
376        );
377        assert_eq!(b.params, vec![text("r"), text("lab/"), text("lab/")]);
378        let n = compile(
379            &parse("$repo.nodes count { where kind == \"md:task\" }"),
380            &[],
381            "r",
382        )
383        .unwrap();
384        assert_eq!(n.target, Target::Nodes);
385        assert!(n.sql.starts_with(
386            "SELECT n.*, d.path AS __path FROM nodes n JOIN docs d ON d.doc_id = n.doc_id WHERE n.repo_id = ? AND d.deleted_commit IS NULL AND ((n.kind IS ?))"
387        ));
388        assert!(n.sql.ends_with("ORDER BY d.path, n.node_id"));
389        let e = compile(
390            &parse("from edges where predicate == \"references\""),
391            &[],
392            "r",
393        )
394        .unwrap();
395        assert!(e.sql.starts_with(
396            "SELECT e.*, d.path AS __path FROM edges e JOIN docs d ON d.doc_id = e.src_doc WHERE e.repo_id = ? AND e.to_commit IS NULL AND d.deleted_commit IS NULL AND ((e.predicate IS ?))"
397        ));
398        assert!(e.sql.ends_with("ORDER BY d.path, e.edge_id"));
399    }
400
401    #[test]
402    fn mixed_conjunctions_push_the_translatable_parts_and_keep_the_rest() {
403        let q = parse(
404            "from docs where $path.startsWith(\"processes/\") && nodes exists { where kind == \"md:task\" } && layer == \"canon\"",
405        );
406        let c = compile(&q, &[], "r").expect("planned");
407        assert!(
408            c.sql.contains("(substr(d.path, 1, length(?)) = ?)"),
409            "{}",
410            c.sql
411        );
412        assert!(c.sql.contains("p.key = 'layer'"), "{}", c.sql);
413        // Guards first, then the fragments' params in statement order.
414        assert_eq!(
415            c.params,
416            vec![
417                text("r"),
418                text("processes/"),
419                text("processes/"),
420                text("canon")
421            ]
422        );
423        // One conjunct left → it stands alone, not wrapped in an `and`.
424        assert!(
425            matches!(c.residual.r#where, Some(Where::Op(_))),
426            "{:?}",
427            c.residual.r#where
428        );
429        assert!(c.residual.from.is_empty());
430        assert_eq!(c.residual.select, q.select);
431        assert_eq!(c.residual.consumer, q.consumer);
432    }
433
434    #[test]
435    fn declined_shapes_return_none() {
436        // nothing pushable → let the engine do it all
437        assert!(compile(&parse("from docs"), &[], "r").is_none());
438        assert!(compile(&parse("from docs where era in 800..1680"), &[], "r").is_none());
439        assert!(compile(&parse("from docs where !verified"), &[], "r").is_none());
440        assert!(
441            compile(
442                &parse("from docs where $path == \"a\" || $path == \"b\""),
443                &[],
444                "r"
445            )
446            .is_none()
447        );
448        assert!(
449            compile(
450                &parse("from docs where nodes exists { where kind == \"md:task\" }"),
451                &[],
452                "r"
453            )
454            .is_none()
455        );
456        // follow
457        assert!(
458            compile(
459                &parse("from docs where $path == \"a.md\" follow distinct doc.out"),
460                &[],
461                "r"
462            )
463            .is_none()
464        );
465        // follow with several destinations: relations and a destination block
466        // decline exactly like a single relation (0.14)
467        assert!(
468            compile(
469                &parse("from docs where $path == \"a.md\" follow doc.out, doc.in"),
470                &[],
471                "r"
472            )
473            .is_none()
474        );
475        assert!(
476            compile(
477                &parse(
478                    "from docs where $path == \"a.md\" follow $repo.docs collect { where after.contains(^$path) }"
479                ),
480                &[],
481                "r"
482            )
483            .is_none()
484        );
485        // not a root scan
486        assert!(compile(&parse("from things where $path == \"a.md\""), &[], "r").is_none());
487        assert!(compile(&parse("from $repo where $path == \"a.md\""), &[], "r").is_none());
488        assert!(compile(&parse("from docs.nodes where kind == \"x\""), &[], "r").is_none());
489        // a `from E` re-projection (an AST-level shape)
490        let mut q = parse("from docs where $path == \"a.md\"");
491        q.from.push(Expr::Ident {
492            name: "nodes".to_owned(),
493            span: oqx::Span::EMPTY,
494        });
495        assert!(compile(&q, &[], "r").is_none());
496    }
497
498    // -- decline (c): a residual that could raise sends the whole query in memory --
499
500    #[test]
501    fn a_residual_that_could_raise_declines_the_whole_query() {
502        let declined = |src: &str| {
503            assert!(
504                compile(&parse(src), &[], "r").is_none(),
505                "should decline: {src}"
506            );
507        };
508        let planned = |src: &str| {
509            assert!(
510                compile(&parse(src), &[], "r").is_some(),
511                "should plan: {src}"
512            );
513        };
514        // a bare reserved docs basename (the guard in `get`)
515        declined("from docs where path == \"x\" && $path == \"nope.md\"");
516        declined("from docs where $path == \"nope.md\" && !body");
517        // `doc.<reserved>` on any target, at any depth
518        declined("from blocks where $path == \"x\" && doc.path == \"y\"");
519        declined("from blocks where $path == \"x\" && nodes exists { where doc.path == \"y\" }");
520        // a function or method call
521        declined("from docs where $path.matches(\"[\") && $path == \"nope.md\"");
522        declined("from docs where nope(\"x\") && $path == \"nope.md\"");
523        declined("from docs where $path == \"x\" && size(tags) > 1");
524        declined("from docs where $path == \"x\" && nodes exists { where name.lower() == \"a\" }");
525        declined(
526            "from docs where $path == \"x\" && nodes count { where kind == \"a\" order by size(name) } > 1",
527        );
528        // a `^`-escaped name: an outer reference or a lift
529        declined("from docs where $path == \"x\" && ^slug == \"y\"");
530        declined("from docs where $path == \"x\" && nodes exists { where name == ^title }");
531        declined("from docs where $path == \"x\" && nodes collect { ^first_task: name }");
532        // a nested block with the `single` consumer
533        declined(
534            "from docs where $path == \"x\" && blocks exists { select t: nodes single { where kind == \"md:task\" } }",
535        );
536        // the pushed side raising is impossible; only the residual matters
537        planned("from docs where $path.startsWith(\"lab/\") && $path == \"x\"");
538        // plain reads, comparisons, `in`, `!`, literals and bindings keep the push
539        planned("from docs where $path == \"x\" && era in 800..1680");
540        planned("from docs where $path == \"x\" && !verified");
541        planned("from docs where $path == \"x\" && (layer == \"a\" || layer == \"b\")");
542        planned("from docs where $path == \"x\" && verified == true");
543        planned("from docs where $path == \"x\" && nodes exists { where kind == \"md:task\" }");
544        planned(
545            "from docs where $path == \"x\" && nodes count { where kind == \"md:task\" limit 5 } > 1",
546        );
547        // on blocks a bare `path` is an attribute, and inside a block the rows
548        // are another scope — an ordinary read, not the guard
549        planned("from blocks where $path == \"x\" && !path");
550        planned("from docs where $path == \"x\" && nodes exists { where path == \"y\" }");
551        planned("from docs where $path == \"x\" && frontmatter.path == \"y\"");
552    }
553
554    #[test]
555    fn a_top_level_not_or_or_is_the_whole_residual_and_declines() {
556        // `!(…)` and `||` at the top are `Where::Not` / `Where::Or`, never scalar
557        // parts, so nothing is pushed even when their leaves would be.
558        assert!(compile(&parse("from docs where !($path == \"a\")"), &[], "r").is_none());
559        assert!(
560            compile(
561                &parse("from docs where ($path == \"a\" || $path == \"b\") && layer == \"canon\""),
562                &[],
563                "r"
564            )
565            .is_some()
566        );
567    }
568}