omgbase-surface 4.9.0

omgbase surface: the OQX query binding over the store, the document/block reads, the history reads and the MCP tool catalog as a library — Rust implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
//! The tier-3 pushdown planner: reduces the row set a query scans by
//! translating its pushable top-level `where` conjuncts into ONE SQL
//! statement against the store, then handing the produced rows (plus the
//! untranslatable residual) back to the in-memory engine to finish. Port of
//! `packages/core/src/oqx-js/planner.ts` over the [`oqx`] seam
//! ([`QueryPlanner`], [`Plan`], [`oqx::partition_pushable`],
//! [`oqx::residual_query`], [`oqx::ROWS_ROOT`]).
//!
//! Correctness is guaranteed by the residual fallback — anything
//! [`crate::translate`] declines stays in-memory — and verified by the
//! differential gate (planned == in-memory over every corpus-backed query
//! case and the conformance list). Deliberately conservative: only simple
//! top-level target scans (no `follow`, no `from E` re-projection) whose
//! source is a bare `docs|blocks|nodes|links` or `<target>`, with at
//! least one pushable scalar conjunct, are planned; everything else declines
//! to a full in-memory run.
//!
//! One shape difference from the reference, forced by ownership: the
//! reference attaches a store context to its plan (`makeStoreContext(…,
//! rowsRoot)`), but a [`crate::StoreContext`] borrows the store's connection
//! and `Plan::context` must be `'static`, so the plan carries no context and
//! the runner ([`mod@crate::query`]) builds the rows-root context itself
//! ([`crate::StoreContext::with_rows_root`]) — the same six lines
//! `oqx::PlannedEngine::run` would execute.

use oqx::Consumer;
use oqx::ast::{Expr, Follow, FollowDestination, OpNode, Query, SelectItem, Subquery, Where};
use oqx::{Plan, QueryPlanner, Value, partition_pushable, residual_query};
use rusqlite::Connection;
use rusqlite::types::Value as SqlValue;

use crate::context::{REVISION_COLS, REVISION_FROM, Target, fetch_rows, tag_rows};
use crate::translate::{TranslateCtx, translate_predicate};

/// The SQL aliases of the scanned row (`self`) and its owning doc (`doc`).
fn aliases(t: Target) -> (&'static str, &'static str) {
    match t {
        Target::Docs => ("d", "d"),
        Target::Blocks => ("b", "d"),
        Target::Nodes => ("n", "d"),
        Target::Links => ("e", "d"),
        Target::Revisions => ("r", "d"),
    }
}

/// The scan's `FROM`. The `revisions` arms here and below (4.7) are the
/// context's own scan spelled as clauses, so a caller keyed by target
/// (`names::present`, a probe) can speak of the kind; the planner itself
/// never plans a revisions scan ([`compile`]).
pub(crate) fn from_clause(t: Target) -> &'static str {
    match t {
        Target::Docs => "docs d",
        Target::Blocks => "blocks b JOIN docs d ON d.doc_id = b.doc_id",
        Target::Nodes => "nodes n JOIN docs d ON d.doc_id = n.doc_id",
        Target::Links => "edges e JOIN docs d ON d.doc_id = e.src_doc",
        Target::Revisions => REVISION_FROM,
    }
}

/// Row columns + the owning-doc path as `__path` (matches the context's
/// roots so produced rows are indistinguishable from a full scan's).
pub(crate) fn columns(t: Target) -> &'static str {
    match t {
        Target::Docs => "d.*",
        Target::Blocks => "b.*, d.path AS __path",
        Target::Nodes => "n.*, d.path AS __path",
        Target::Links => "e.*, d.path AS __path",
        Target::Revisions => REVISION_COLS,
    }
}

/// The root order (`spec/surface` §1.1).
pub(crate) fn order_clause(t: Target) -> &'static str {
    match t {
        Target::Docs => "d.path, d.doc_id",
        Target::Blocks => "d.path, b.block_id",
        Target::Nodes => "d.path, n.node_id",
        Target::Links => "d.path, e.edge_id",
        Target::Revisions => "r.path, r.rev_id",
    }
}

/// The liveness guards of the root scan, with the repo id bound. The history
/// has no liveness: every revision of every document of the repository,
/// tombstoned ones included (§1.1, 4.7) — the repository guard through the
/// owning `docs` row, since `revisions` carries no `repo_id`.
pub(crate) fn guards(t: Target) -> &'static str {
    match t {
        Target::Docs => "d.repo_id = ? AND d.deleted_commit IS NULL",
        Target::Blocks => "b.repo_id = ? AND b.deleted_commit IS NULL AND d.deleted_commit IS NULL",
        Target::Nodes => "n.repo_id = ? AND d.deleted_commit IS NULL",
        Target::Links => "e.repo_id = ? AND e.to_commit IS NULL AND d.deleted_commit IS NULL",
        Target::Revisions => "d.repo_id = ?",
    }
}

/// The joined targets driven FROM the document: the same rows and columns as
/// [`from_clause`], with the loop order fixed by `CROSS JOIN` so a predicate on
/// the document (`d.path = ?`) is the outer search and the target's rows are
/// reached through their `doc_id` / `src_doc` index (the store indexes'
/// `path` probes). [`guards_by_doc`] goes with it; `Docs` is `from_clause`.
pub(crate) fn from_by_doc(t: Target) -> &'static str {
    match t {
        Target::Docs | Target::Revisions => from_clause(t),
        Target::Blocks => "docs d CROSS JOIN blocks b ON b.doc_id = d.doc_id",
        Target::Nodes => "docs d CROSS JOIN nodes n ON n.doc_id = d.doc_id",
        Target::Links => "docs d CROSS JOIN edges e ON e.src_doc = d.doc_id",
    }
}

/// [`guards`] for a [`from_by_doc`] statement: the same tests, with the
/// document's repo first and the target's repo term behind SQLite's unary `+`
/// so it stays a filter and never selects a `(repo_id, …)` index over the
/// `doc_id` one. Two repo-id binds (`Docs`: one, as `guards`).
pub(crate) fn guards_by_doc(t: Target) -> &'static str {
    match t {
        Target::Docs | Target::Revisions => guards(t),
        Target::Blocks => {
            "d.repo_id = ? AND +b.repo_id = ? AND b.deleted_commit IS NULL AND d.deleted_commit IS NULL"
        }
        Target::Nodes => "d.repo_id = ? AND +n.repo_id = ? AND d.deleted_commit IS NULL",
        Target::Links => {
            "d.repo_id = ? AND +e.repo_id = ? AND e.to_commit IS NULL AND d.deleted_commit IS NULL"
        }
    }
}

/// The root collection a query scans, if it is a bare
/// `docs|blocks|nodes|links|revisions` source at the root scope (else `None` —
/// a nested `^docs` is a block's receiver, never the query's source). The
/// runner asks too: a bare root scan's rows are store rows by construction.
/// Five-wide (the reference's `ROOTS` test); [`compile`] plans four — a
/// `revisions` scan (4.7) always runs in memory.
pub(crate) fn root_target(source: &Expr) -> Option<Target> {
    match source {
        Expr::Ident { name, .. } => Target::parse(name),
        _ => None,
    }
}

/// Whether `name` is a relation of `target`'s rows that is spelled like a
/// target (§1.2: `docs.nodes`, `docs.blocks`, `docs.revisions` (4.7),
/// `blocks.nodes`, `section.blocks`).
fn is_target_relation_of(target: Target, name: &str) -> bool {
    matches!(
        (target, name),
        (Target::Docs, "nodes" | "blocks" | "revisions")
            | (Target::Blocks, "nodes")
            | (Target::Nodes, "blocks")
    )
}

/// The row a reach-through head reaches (`doc.x`, `block.x`, `section.x`,
/// and a link's `dst.x`).
fn reach_through(head: &str) -> Option<Target> {
    match head {
        "doc" | "dst" => Some(Target::Docs),
        "block" => Some(Target::Blocks),
        "section" => Some(Target::Nodes),
        _ => None,
    }
}

// ---- the residual-error decline (surface 1.1 patch, §1) ---------------------------------

/// Whether a residual `where` could raise an OQX eval error the pushed
/// conjuncts might hide by emptying the scan. In memory every conjunct of the
/// original `&&` is evaluated for the first row and a throwing one aborts the
/// run; planned, a pushed conjunct that matches no row means the residual
/// never runs and the error vanishes. So a residual containing any function
/// or method call (an unknown function, a bad regex, a wrong arity…), a
/// nested block with the `single` consumer (more than one row raises), a
/// `^`-escaped name (no enclosing scope at the top level) sends the whole
/// query to the in-memory engine unplanned (before this batch of 3.0 a bare
/// reserved docs basename did too; the attributes are bare now and never
/// raise). Only comparisons, logical
/// operators, `in`, `!`, literals, bindings and plain reads keep the push.
///
/// The walk is generic over the whole `oqx` AST — every `Where` node, every
/// nested block (its `from`, `where`, `select`, `order by`, `follow`,
/// `limit` / `offset`) and every `Expr`. A `^name:` lift in a nested select
/// counts as a `^`-escaped name. Same decisions as the reference's
/// `residualMayRaise`.
fn residual_may_raise(w: &Where, target: Target) -> bool {
    where_may_raise(w, target, true)
}

fn where_may_raise(w: &Where, target: Target, root: bool) -> bool {
    match w {
        Where::And { parts, .. } | Where::Or { parts, .. } => {
            parts.iter().any(|p| where_may_raise(p, target, root))
        }
        Where::Not { expr, .. } => where_may_raise(expr, target, root),
        Where::Scalar { expr, .. } => expr_may_raise(expr, target, root),
        Where::Op(op) => op_may_raise(op, target, root),
    }
}

fn op_may_raise(op: &OpNode, target: Target, root: bool) -> bool {
    op.op == Consumer::Single
        || expr_may_raise(&op.receiver, target, root)
        || subquery_may_raise(&op.sub, target)
}

fn subquery_may_raise(sub: &Subquery, target: Target) -> bool {
    let inner = |e: &Expr| expr_may_raise(e, target, false);
    sub.from.iter().any(inner)
        || sub
            .r#where
            .as_ref()
            .is_some_and(|w| where_may_raise(w, target, false))
        || sub.select.iter().any(|item| match item {
            SelectItem::Field { expr, lift, .. } => *lift > 0 || inner(expr),
            SelectItem::Collect { op, .. } => op_may_raise(op, target, false),
        })
        || sub.order_by.iter().flatten().any(|o| inner(&o.expr))
        || sub
            .follow
            .as_ref()
            .is_some_and(|f| follow_may_raise(f, target))
        || sub.frontier.as_ref().is_some_and(inner)
        // A grouped block (oqx 0.24) evaluates its keys, `having` and its
        // aggregates (`sum` over a string raises) per group.
        || sub
            .group_by
            .as_ref()
            .is_some_and(|g| g.keys.iter().any(|k| inner(&k.expr)))
        || sub
            .having
            .as_ref()
            .is_some_and(|h| where_may_raise(h, target, false))
        || sub.limit.as_ref().is_some_and(inner)
        || sub.offset.as_ref().is_some_and(inner)
}

// A destination is a relation read in the frontier row's scope, or a destination
// block (whose receiver, body, `frontier` and `depth` are its own — oqx 0.20).
fn follow_may_raise(f: &Follow, target: Target) -> bool {
    let inner = |e: &Expr| expr_may_raise(e, target, false);
    f.destinations.iter().any(|d| match d {
        FollowDestination::Relation(e) => inner(e),
        FollowDestination::Block(op) => op_may_raise(op, target, false),
    })
}

fn expr_may_raise(e: &Expr, target: Target, root: bool) -> bool {
    let again = |e: &Expr| expr_may_raise(e, target, root);
    match e {
        Expr::Lit { .. } | Expr::Binding { .. } => false,
        // A bare target name read as a property raises (the root-row rule,
        // `crate::query`) unless it is a relation of the rows at hand: known at
        // the root scope, unknown below.
        Expr::Ident { name, .. } if Target::parse(name).is_some() => {
            !root || !is_target_relation_of(target, name)
        }
        // A bare attribute never raises (3.0: there is no loud-error set).
        Expr::Ident { .. } => false,
        Expr::Outer { .. } | Expr::Call { .. } => true,
        // `<head>.<target>` raises unless the head is a reach-through whose row
        // has that relation.
        Expr::Member { recv, name, .. } => {
            (Target::parse(name).is_some()
                && !matches!(&**recv, Expr::Ident { name: head, .. }
                        if reach_through(head).is_some_and(|t| is_target_relation_of(t, name))))
                || again(recv)
        }
        Expr::Unary { expr, .. } => again(expr),
        // `x!` raises when absent; a value-position directive may `single`-fail
        // or read anything its block reads.
        Expr::Required { .. } => true,
        Expr::Op(op) => op_may_raise(op, target, root),
        // A regex operator (oqx 0.22) is a `matches` call: an invalid pattern
        // raises, exactly as the call would.
        Expr::Binary {
            op, left, right, ..
        } => op.is_regex() || again(left) || again(right),
        Expr::Logical { left, right, .. } | Expr::In { left, right, .. } => {
            again(left) || again(right)
        }
        Expr::Range { lo, hi, .. } => {
            lo.as_deref().is_some_and(again) || hi.as_deref().is_some_and(again)
        }
        // A tuple (oqx 0.20) is never pushed down; it raises iff an element does.
        Expr::Tuple { items, .. } => items.iter().any(again),
        // A template literal (oqx 0.21) is never pushed down; interpolating a
        // list or a record is an eval error only the data decides, so with any
        // interpolation it may raise.
        Expr::Template { parts, .. } => oqx::walk::template_exprs(parts).next().is_some(),
        // An aggregate (oqx 0.24) raises on a non-number under `sum`/`avg`,
        // which only the data decides; a grouped query is never planned anyway
        // (`compile`).
        Expr::Aggregate { .. } => true,
    }
}

/// A compiled plan before execution: the statement, its params and the
/// residual query. Pure — what the planner would run, for inspection.
#[derive(Clone, Debug, PartialEq)]
pub struct Compiled {
    pub target: Target,
    pub sql: String,
    pub params: Vec<SqlValue>,
    pub residual: Query,
}

/// Compile `query` against `repo_id`, or `None` when the shape declines: a
/// `follow`, a `from E` re-projection, a `group by` (oqx 0.24 — declined
/// whole: its `where` conjuncts could be pushed, grouping happens after them,
/// but a pushed conjunct that empties the scan would hide an eval error an
/// aggregate or `having` raises in memory, so decline (c) extends to the
/// post-group clauses; SQL `GROUP BY` pushdown is a later round), a source
/// that is not a root scan, or no pushable conjunct at all (the engine then
/// does everything).
#[must_use]
pub fn compile(query: &Query, params: &[Value], repo_id: &str) -> Option<Compiled> {
    if query.follow.is_some() || !query.from.is_empty() || query.group_by.is_some() {
        return None;
    }
    let target = root_target(&query.source)?;
    // The history (4.7) is never planned: no store index, no pushdown — the
    // scan runs in memory, as the reference's four-wide `rootTarget` decides.
    if target == Target::Revisions {
        return None;
    }
    let (self_alias, doc_alias) = aliases(target);
    let ctx = TranslateCtx {
        target,
        self_alias,
        doc_alias,
        params,
    };
    let (pushed, residual) = partition_pushable(query.r#where.as_ref(), |e| {
        translate_predicate(e, &ctx).is_some()
    });
    if pushed.is_empty() {
        return None;
    }
    // Decline (c): a residual that could raise must not be hidden behind an
    // emptied scan — the whole query runs in memory.
    if residual
        .as_ref()
        .is_some_and(|w| residual_may_raise(w, target))
    {
        return None;
    }
    let mut where_sql = guards(target).to_owned();
    let mut sql_params = vec![SqlValue::Text(repo_id.to_owned())];
    for e in &pushed {
        let frag = translate_predicate(e, &ctx).expect("accepted by partition_pushable");
        where_sql.push_str(" AND (");
        where_sql.push_str(&frag.sql);
        where_sql.push(')');
        sql_params.extend(frag.params);
    }
    let sql = format!(
        "SELECT {} FROM {} WHERE {where_sql} ORDER BY {}",
        columns(target),
        from_clause(target),
        order_clause(target)
    );
    Some(Compiled {
        target,
        sql,
        params: sql_params,
        residual: residual_query(query, residual),
    })
}

/// The SQLite planner over one repo of the store.
pub struct SqlitePlanner<'a> {
    conn: &'a Connection,
    repo_id: String,
}

impl<'a> SqlitePlanner<'a> {
    #[must_use]
    pub fn new(conn: &'a Connection, repo_id: &str) -> Self {
        Self {
            conn,
            repo_id: repo_id.to_owned(),
        }
    }

    /// Plan `query`: `Ok(None)` when the shape declines, `Ok(Some(plan))`
    /// with the produced rows (tagged like the context's root rows) and the
    /// residual, `Err` when the statement itself failed (a store error, not
    /// a decline — the runner reports it rather than silently rescanning).
    pub fn try_plan(&self, query: &Query, params: &[Value]) -> rusqlite::Result<Option<Plan>> {
        let Some(compiled) = compile(query, params, &self.repo_id) else {
            return Ok(None);
        };
        let rows = fetch_rows(self.conn, &compiled.sql, &compiled.params)?;
        Ok(Some(Plan::new(
            tag_rows(rows, compiled.target),
            compiled.residual,
        )))
    }
}

impl QueryPlanner for SqlitePlanner<'_> {
    /// The seam's shape: a failed statement declines (the engine falls back
    /// to a full scan). The runner uses [`Self::try_plan`] to surface it.
    fn plan(&self, query: &Query, params: &[Value]) -> Option<Plan> {
        self.try_plan(query, params).ok().flatten()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use oqx::ROWS_ROOT;
    use oqx::ast::Where;

    fn parse(src: &str) -> Query {
        oqx::parse_string(src).expect("parses")
    }

    fn text(s: &str) -> SqlValue {
        SqlValue::Text(s.to_owned())
    }

    #[test]
    fn a_pushable_scan_compiles_to_one_statement_in_root_order() {
        let c =
            compile(&parse("from docs where path == \"index.md\""), &[], "r_1").expect("planned");
        assert_eq!(c.target, Target::Docs);
        assert_eq!(
            c.sql,
            "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"
        );
        assert_eq!(c.params, vec![text("r_1"), text("index.md")]);
        assert_eq!(
            c.residual.source,
            Expr::Ident {
                name: ROWS_ROOT.to_owned(),
                span: oqx::Span::EMPTY,
            }
        );
        assert_eq!(c.residual.r#where, None);
    }

    #[test]
    fn every_target_has_its_join_columns_guards_and_order() {
        let b = compile(
            &parse("from blocks where path.startsWith(\"lab/\")"),
            &[],
            "r",
        )
        .unwrap();
        assert_eq!(
            b.sql,
            "SELECT b.*, d.path AS __path FROM blocks b JOIN docs d ON d.doc_id = b.doc_id \
             WHERE b.repo_id = ? AND b.deleted_commit IS NULL AND d.deleted_commit IS NULL \
             AND ((substr(('/' || d.path), 1, length(?)) = ?)) ORDER BY d.path, b.block_id"
        );
        assert_eq!(b.params, vec![text("r"), text("lab/"), text("lab/")]);
        let n = compile(
            &parse("nodes count { where kind == \"md:task\" }"),
            &[],
            "r",
        )
        .unwrap();
        assert_eq!(n.target, Target::Nodes);
        assert!(n.sql.starts_with(
            "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 ?))"
        ));
        assert!(n.sql.ends_with("ORDER BY d.path, n.node_id"));
        let e = compile(
            &parse("from links where predicate == \"references\""),
            &[],
            "r",
        )
        .unwrap();
        assert!(e.sql.starts_with(
            "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 ?))"
        ));
        assert!(e.sql.ends_with("ORDER BY d.path, e.edge_id"));
    }

    #[test]
    fn mixed_conjunctions_push_the_translatable_parts_and_keep_the_rest() {
        let q = parse(
            "from docs where path.startsWith(\"processes/\") && nodes exists { where kind == \"md:task\" } && layer == \"canon\"",
        );
        let c = compile(&q, &[], "r").expect("planned");
        assert!(
            c.sql
                .contains("(substr(('/' || d.path), 1, length(?)) = ?)"),
            "{}",
            c.sql
        );
        assert!(c.sql.contains("p.key = 'layer'"), "{}", c.sql);
        // Guards first, then the fragments' params in statement order.
        assert_eq!(
            c.params,
            vec![
                text("r"),
                text("processes/"),
                text("processes/"),
                text("canon")
            ]
        );
        // One conjunct left → it stands alone, not wrapped in an `and`.
        assert!(
            matches!(c.residual.r#where, Some(Where::Op(_))),
            "{:?}",
            c.residual.r#where
        );
        assert!(c.residual.from.is_empty());
        assert_eq!(c.residual.select, q.select);
        assert_eq!(c.residual.consumer, q.consumer);
    }

    #[test]
    fn declined_shapes_return_none() {
        // nothing pushable → let the engine do it all
        assert!(compile(&parse("from docs"), &[], "r").is_none());
        assert!(compile(&parse("from docs where era in 800..1680"), &[], "r").is_none());
        assert!(compile(&parse("from docs where !verified"), &[], "r").is_none());
        assert!(
            compile(
                &parse("from docs where path == \"a\" || path == \"b\""),
                &[],
                "r"
            )
            .is_none()
        );
        assert!(
            compile(
                &parse("from docs where nodes exists { where kind == \"md:task\" }"),
                &[],
                "r"
            )
            .is_none()
        );
        // follow
        assert!(
            compile(
                &parse("from docs where path == \"a.md\" follow distinct out_links collect { from dst }"),
                &[],
                "r"
            )
            .is_none()
        );
        // follow with several destinations: relations and a destination block
        // decline exactly like a single relation (0.14)
        assert!(
            compile(
                &parse("from docs where path == \"a.md\" follow out_links collect { from dst }, in_links collect { from doc }"),
                &[],
                "r"
            )
            .is_none()
        );
        assert!(
            compile(
                &parse(
                    "from docs where path == \"a.md\" follow ^docs collect { where after.contains(^path) }"
                ),
                &[],
                "r"
            )
            .is_none()
        );
        // a body-level `frontier` (oqx 0.20) plans like the `follow` it needs
        assert!(
            compile(
                &parse("from docs where path == \"a.md\" frontier type == \"hub\" follow distinct out_links collect { from dst frontier type == \"practitioner\" }"),
                &[],
                "r"
            )
            .is_none()
        );
        // a grouped query is declined whole (oqx 0.24), pushable `where` or not
        assert!(
            compile(
                &parse("select layer, n: count() from docs where path == \"a.md\" group by layer"),
                &[],
                "r"
            )
            .is_none()
        );
        // not a root scan
        assert!(compile(&parse("from things where path == \"a.md\""), &[], "r").is_none());
        assert!(compile(&parse("from nope where path == \"a.md\""), &[], "r").is_none());
        assert!(compile(&parse("from docs.nodes where kind == \"x\""), &[], "r").is_none());
        // a `from E` re-projection (an AST-level shape)
        let mut q = parse("from docs where path == \"a.md\"");
        q.from.push(Expr::Ident {
            name: "nodes".to_owned(),
            span: oqx::Span::EMPTY,
        });
        assert!(compile(&q, &[], "r").is_none());
    }

    // -- decline (c): a residual that could raise sends the whole query in memory --

    #[test]
    fn a_residual_that_could_raise_declines_the_whole_query() {
        let declined = |src: &str| {
            assert!(
                compile(&parse(src), &[], "r").is_none(),
                "should decline: {src}"
            );
        };
        let planned = |src: &str| {
            assert!(
                compile(&parse(src), &[], "r").is_some(),
                "should plan: {src}"
            );
        };
        // a bare attribute is never a raise (3.0: no loud-error set) — `path`
        // pushes, `raw`/`updated_at`/`tags` are plain residuals
        planned("from docs where path == \"x\" && path == \"nope.md\"");
        planned("from docs where path == \"nope.md\" && !raw");
        planned("from docs where path == \"nope.md\" && updated_at");
        planned("from docs where path == \"nope.md\" && tags");
        // `doc.<attribute>` on any target, at any depth, is a plain read too
        planned("from blocks where path == \"x\" && doc.path == \"y\"");
        planned("from blocks where path == \"x\" && nodes exists { where doc.path == \"y\" }");
        // a function or method call
        declined("from docs where path.matches(\"[\") && path == \"nope.md\"");
        declined("from docs where nope(\"x\") && path == \"nope.md\"");
        declined("from docs where path == \"x\" && size(tags) > 1");
        declined("from docs where path == \"x\" && nodes exists { where name.lower() == \"a\" }");
        declined(
            "from docs where path == \"x\" && nodes count { where kind == \"a\" order by size(name) } > 1",
        );
        // a `^`-escaped name: an outer reference or a lift
        declined("from docs where path == \"x\" && ^slug == \"y\"");
        declined("from docs where path == \"x\" && nodes exists { where name == ^title }");
        declined("from docs where path == \"x\" && nodes collect { ^first_task: name }");
        // a nested block with the `single` consumer
        declined(
            "from docs where path == \"x\" && blocks exists { select t: nodes single { where kind == \"md:task\" } }",
        );
        // the pushed side raising is impossible; only the residual matters
        planned("from docs where path.startsWith(\"lab/\") && path == \"x\"");
        // plain reads, comparisons, `in`, `!`, literals and bindings keep the push
        planned("from docs where path == \"x\" && era in 800..1680");
        planned("from docs where path == \"x\" && !verified");
        planned("from docs where path == \"x\" && (layer == \"a\" || layer == \"b\")");
        planned("from docs where path == \"x\" && verified == true");
        planned("from docs where path == \"x\" && nodes exists { where kind == \"md:task\" }");
        planned(
            "from docs where path == \"x\" && nodes count { where kind == \"md:task\" limit 5 } > 1",
        );
        // on blocks a bare `path` is an attribute, and inside a block the rows
        // are another scope — an ordinary read, not the guard
        planned("from blocks where path == \"x\" && !path");
        planned("from docs where path == \"x\" && nodes exists { where path == \"y\" }");
        planned("from docs where path == \"x\" && frontmatter.path == \"y\"");
        // a key read through a source handle is pushed (3.0), scoped to its
        // source; a WHOLE handle reference and `entries(…)` stay residual (and
        // the function call declines the query)
        let fm = compile(
            &parse("from docs where frontmatter.layer == \"canon\""),
            &[],
            "r",
        )
        .expect("planned");
        assert!(fm.sql.contains("p.source = 'frontmatter'"), "{}", fm.sql);
        let data =
            compile(&parse("from docs where data.layer == \"canon\""), &[], "r").expect("planned");
        assert!(!data.sql.contains("p.source"), "{}", data.sql);
        planned("from blocks where doc.inline.element == \"fire\"");
        planned("from docs where path == \"x\" && frontmatter == null");
        declined("from docs where path == \"x\" && entries(frontmatter) exists { }");
    }

    #[test]
    fn a_top_level_not_or_or_is_the_whole_residual_and_declines() {
        // `!(…)` and `||` at the top are `Where::Not` / `Where::Or`, never scalar
        // parts, so nothing is pushed even when their leaves would be.
        assert!(compile(&parse("from docs where !(path == \"a\")"), &[], "r").is_none());
        assert!(
            compile(
                &parse("from docs where (path == \"a\" || path == \"b\") && layer == \"canon\""),
                &[],
                "r"
            )
            .is_some()
        );
    }
}