Skip to main content

omgbase_surface/
query.rs

1//! The runner (`spec/surface/README.md` §1.4): parse the source, rewrite the
2//! row functions to `$self` methods, run it through the engine over the
3//! store context, and shape the engine's result into the surface's
4//! `OqxResult` (lean `{ id, path, … }` hits, keyset paging, the consumer
5//! scalars). Port of `packages/core/src/oqx-js/run.ts`.
6//!
7//! By default the tier-3 planner ([`crate::planner`]) pre-filters the scan in
8//! SQL and the in-memory engine finishes the residual over the produced rows;
9//! [`QueryOptions::in_memory`] forces the pure in-memory engine (the
10//! differential gate runs every case both ways — a planner must be invisible).
11
12use std::collections::HashMap;
13
14use omgbase_search::{EmbeddingProvider, f32_to_blob};
15use omgbase_store::Store;
16use oqx::ast::{Expr, Follow, OpNode, OrderSpec, Query, SelectItem, Subquery, Where};
17use oqx::{Consumer, Engine, InMemoryEngine, Value};
18use serde_json::{Map, Value as Json};
19
20use crate::context::{SemanticVec, StoreContext, strip_tags};
21use crate::cursor::{decode_cursor, encode_cursor};
22use crate::error::{Result, SurfaceError};
23use crate::planner::SqlitePlanner;
24
25/// The default page size.
26pub const DEFAULT_LIMIT: usize = 50;
27
28/// Row-scoped domain functions: authored as free calls that implicitly
29/// reference the current row; rewritten to `$self.fn(…)`.
30const ROW_FNS: [&str; 12] = [
31    "text",
32    "semantic",
33    "under",
34    "under_heading",
35    "within",
36    "under_kind",
37    "yaml_path",
38    "json_pointer",
39    "has_edge",
40    "has_anchor",
41    "child_count",
42    "parent_type",
43];
44
45const ID_KEY: &str = "__oqx_id";
46const PATH_KEY: &str = "__oqx_path";
47/// The reserved key a top-level `values` projection's single item is renamed
48/// to, so it rides through id/path injection, paging and distinct as an
49/// ordinary field and is peeled off at the end.
50const VALUE_KEY: &str = "__oqx_value";
51
52/// `query`'s options.
53#[derive(Clone, Copy, Default)]
54pub struct QueryOptions<'a> {
55    /// The page cap (default 50).
56    pub limit: Option<usize>,
57    /// Resume after a truncated page's cursor.
58    pub cursor: Option<&'a str>,
59    /// The provider behind `semantic(...)`; `None` → `semantic_unavailable`
60    /// when the query names a phrase.
61    pub provider: Option<&'a dyn EmbeddingProvider>,
62    /// Force the pure in-memory engine (skip the tier-3 pushdown planner).
63    /// The default plans; the differential gate runs both and compares.
64    pub in_memory: bool,
65}
66
67/// §1.4 `OqxResult`.
68#[derive(Clone, Debug, PartialEq)]
69pub struct OqxResult {
70    pub hits: Vec<Json>,
71    pub truncated: bool,
72    pub cursor: Option<String>,
73    pub consumer: Consumer,
74    pub count: Option<f64>,
75    pub exists: Option<bool>,
76    pub none: Option<bool>,
77    /// A top-level `values` projection's bare values, in place of `hits`.
78    pub values: Option<Vec<Json>>,
79}
80
81impl OqxResult {
82    fn scalar(consumer: Consumer) -> Self {
83        Self {
84            hits: Vec::new(),
85            truncated: false,
86            cursor: None,
87            consumer,
88            count: None,
89            exists: None,
90            none: None,
91            values: None,
92        }
93    }
94
95    /// The wire shape: `{ hits, truncated, cursor, consumer, count?, exists?,
96    /// none?, values? }`.
97    #[must_use]
98    pub fn to_json(&self) -> Json {
99        let mut m = Map::new();
100        m.insert("hits".to_owned(), Json::Array(self.hits.clone()));
101        m.insert("truncated".to_owned(), Json::Bool(self.truncated));
102        m.insert(
103            "cursor".to_owned(),
104            self.cursor.clone().map_or(Json::Null, Json::String),
105        );
106        m.insert(
107            "consumer".to_owned(),
108            Json::String(self.consumer.as_str().to_owned()),
109        );
110        if let Some(n) = self.count {
111            m.insert("count".to_owned(), Value::Number(n).to_canonical_json());
112        }
113        if let Some(b) = self.exists {
114            m.insert("exists".to_owned(), Json::Bool(b));
115        }
116        if let Some(b) = self.none {
117            m.insert("none".to_owned(), Json::Bool(b));
118        }
119        if let Some(v) = &self.values {
120            m.insert("values".to_owned(), Json::Array(v.clone()));
121        }
122        Json::Object(m)
123    }
124}
125
126// ---- the `$self` rewrite -----------------------------------------------------------
127
128fn self_ref() -> Expr {
129    Expr::Ident {
130        name: "$self".to_owned(),
131    }
132}
133
134fn rewrite_expr(e: &Expr) -> Expr {
135    match e {
136        Expr::Member { recv, name } => Expr::Member {
137            recv: Box::new(rewrite_expr(recv)),
138            name: name.clone(),
139        },
140        Expr::Index { recv, index } => Expr::Index {
141            recv: Box::new(rewrite_expr(recv)),
142            index: Box::new(rewrite_expr(index)),
143        },
144        Expr::Unary { op, expr } => Expr::Unary {
145            op: *op,
146            expr: Box::new(rewrite_expr(expr)),
147        },
148        Expr::Binary { op, left, right } => Expr::Binary {
149            op: *op,
150            left: Box::new(rewrite_expr(left)),
151            right: Box::new(rewrite_expr(right)),
152        },
153        Expr::Logical { op, left, right } => Expr::Logical {
154            op: *op,
155            left: Box::new(rewrite_expr(left)),
156            right: Box::new(rewrite_expr(right)),
157        },
158        Expr::In { left, right } => Expr::In {
159            left: Box::new(rewrite_expr(left)),
160            right: Box::new(rewrite_expr(right)),
161        },
162        Expr::Range {
163            lo,
164            hi,
165            exclusive_end,
166        } => Expr::Range {
167            lo: lo.as_ref().map(|x| Box::new(rewrite_expr(x))),
168            hi: hi.as_ref().map(|x| Box::new(rewrite_expr(x))),
169            exclusive_end: *exclusive_end,
170        },
171        Expr::Call { recv, name, args } => {
172            let args = args.iter().map(rewrite_expr).collect();
173            match recv {
174                None if ROW_FNS.contains(&name.as_str()) => Expr::Call {
175                    recv: Some(Box::new(self_ref())),
176                    name: name.clone(),
177                    args,
178                },
179                None => Expr::Call {
180                    recv: None,
181                    name: name.clone(),
182                    args,
183                },
184                Some(r) => Expr::Call {
185                    recv: Some(Box::new(rewrite_expr(r))),
186                    name: name.clone(),
187                    args,
188                },
189            }
190        }
191        Expr::Lit(_) | Expr::Ident { .. } | Expr::Outer { .. } | Expr::Binding { .. } => e.clone(),
192    }
193}
194
195fn rewrite_where(w: &Where) -> Where {
196    match w {
197        Where::And { parts } => Where::And {
198            parts: parts.iter().map(rewrite_where).collect(),
199        },
200        Where::Or { parts } => Where::Or {
201            parts: parts.iter().map(rewrite_where).collect(),
202        },
203        Where::Not { expr } => Where::Not {
204            expr: Box::new(rewrite_where(expr)),
205        },
206        Where::Scalar { expr } => Where::Scalar {
207            expr: rewrite_expr(expr),
208        },
209        Where::Op(op) => Where::Op(Box::new(rewrite_op(op))),
210    }
211}
212
213fn rewrite_op(op: &OpNode) -> OpNode {
214    OpNode {
215        receiver: rewrite_expr(&op.receiver),
216        op: op.op,
217        sub: rewrite_sub(&op.sub),
218        count_cmp: op.count_cmp.clone(),
219        distinct: op.distinct,
220    }
221}
222
223fn rewrite_follow(f: &Follow) -> Follow {
224    Follow {
225        receiver: rewrite_expr(&f.receiver),
226        distinct: f.distinct,
227        r#where: f.r#where.as_ref().map(rewrite_expr),
228        frontier: f.frontier.as_ref().map(rewrite_expr),
229        depth: f.depth,
230        by: f.by.as_ref().map(rewrite_expr),
231    }
232}
233
234fn rewrite_select(items: &[SelectItem]) -> Vec<SelectItem> {
235    items
236        .iter()
237        .map(|it| match it {
238            SelectItem::Field { name, expr, lift } => SelectItem::Field {
239                name: name.clone(),
240                expr: rewrite_expr(expr),
241                lift: *lift,
242            },
243            SelectItem::Collect { name, op } => SelectItem::Collect {
244                name: name.clone(),
245                op: Box::new(rewrite_op(op)),
246            },
247        })
248        .collect()
249}
250
251fn rewrite_order(o: Option<&Vec<OrderSpec>>) -> Option<Vec<OrderSpec>> {
252    o.map(|specs| {
253        specs
254            .iter()
255            .map(|s| OrderSpec {
256                expr: rewrite_expr(&s.expr),
257                desc: s.desc,
258            })
259            .collect()
260    })
261}
262
263fn rewrite_sub(s: &Subquery) -> Subquery {
264    Subquery {
265        from: s.from.iter().map(rewrite_expr).collect(),
266        r#where: s.r#where.as_ref().map(rewrite_where),
267        select: rewrite_select(&s.select),
268        order_by: rewrite_order(s.order_by.as_ref()),
269        follow: s.follow.as_ref().map(rewrite_follow),
270        values: s.values,
271        limit: s.limit.as_ref().map(rewrite_expr),
272        offset: s.offset.as_ref().map(rewrite_expr),
273    }
274}
275
276/// Rewrite every row function in a parsed query to a `$self` method call.
277#[must_use]
278pub fn rewrite_query(q: &Query) -> Query {
279    Query {
280        source: rewrite_expr(&q.source),
281        from: q.from.iter().map(rewrite_expr).collect(),
282        r#where: q.r#where.as_ref().map(rewrite_where),
283        select: rewrite_select(&q.select),
284        order_by: rewrite_order(q.order_by.as_ref()),
285        consumer: q.consumer,
286        follow: q.follow.as_ref().map(rewrite_follow),
287        distinct: q.distinct,
288        values: q.values,
289        limit: q.limit.as_ref().map(rewrite_expr),
290        offset: q.offset.as_ref().map(rewrite_expr),
291    }
292}
293
294// ---- semantic phrases -----------------------------------------------------------------
295
296fn visit_expr(e: &Expr, out: &mut Vec<String>) {
297    match e {
298        Expr::Call { recv, name, args } => {
299            if recv.is_none() && name == "semantic" {
300                if let Some(Expr::Lit(Value::Str(s))) = args.first() {
301                    if !out.contains(s) {
302                        out.push(s.clone());
303                    }
304                }
305            }
306            if let Some(r) = recv {
307                visit_expr(r, out);
308            }
309            for a in args {
310                visit_expr(a, out);
311            }
312        }
313        Expr::Member { recv, .. } => visit_expr(recv, out),
314        Expr::Index { recv, index } => {
315            visit_expr(recv, out);
316            visit_expr(index, out);
317        }
318        Expr::Unary { expr, .. } => visit_expr(expr, out),
319        Expr::Binary { left, right, .. }
320        | Expr::Logical { left, right, .. }
321        | Expr::In { left, right } => {
322            visit_expr(left, out);
323            visit_expr(right, out);
324        }
325        Expr::Range { lo, hi, .. } => {
326            if let Some(l) = lo {
327                visit_expr(l, out);
328            }
329            if let Some(h) = hi {
330                visit_expr(h, out);
331            }
332        }
333        Expr::Lit(_) | Expr::Ident { .. } | Expr::Outer { .. } | Expr::Binding { .. } => {}
334    }
335}
336
337fn visit_where(w: &Where, out: &mut Vec<String>) {
338    match w {
339        Where::And { parts } | Where::Or { parts } => {
340            parts.iter().for_each(|p| visit_where(p, out))
341        }
342        Where::Not { expr } => visit_where(expr, out),
343        Where::Scalar { expr } => visit_expr(expr, out),
344        Where::Op(op) => visit_op(op, out),
345    }
346}
347
348fn visit_op(op: &OpNode, out: &mut Vec<String>) {
349    visit_expr(&op.receiver, out);
350    visit_sub(&op.sub, out);
351}
352
353fn visit_select(items: &[SelectItem], out: &mut Vec<String>) {
354    for it in items {
355        match it {
356            SelectItem::Field { expr, .. } => visit_expr(expr, out),
357            SelectItem::Collect { op, .. } => visit_op(op, out),
358        }
359    }
360}
361
362fn visit_follow(f: &Follow, out: &mut Vec<String>) {
363    visit_expr(&f.receiver, out);
364    for x in [&f.r#where, &f.frontier, &f.by].into_iter().flatten() {
365        visit_expr(x, out);
366    }
367}
368
369fn visit_sub(s: &Subquery, out: &mut Vec<String>) {
370    s.from.iter().for_each(|e| visit_expr(e, out));
371    if let Some(w) = &s.r#where {
372        visit_where(w, out);
373    }
374    visit_select(&s.select, out);
375    if let Some(o) = &s.order_by {
376        o.iter().for_each(|spec| visit_expr(&spec.expr, out));
377    }
378    if let Some(f) = &s.follow {
379        visit_follow(f, out);
380    }
381}
382
383/// The distinct phrases `semantic("…")` names (free calls in the raw parse);
384/// empty when the source does not parse.
385#[must_use]
386pub fn collect_semantic_phrases(source: &str) -> Vec<String> {
387    let Ok(q) = oqx::parse_string(source) else {
388        return Vec::new();
389    };
390    let mut out = Vec::new();
391    visit_expr(&q.source, &mut out);
392    q.from.iter().for_each(|e| visit_expr(e, &mut out));
393    if let Some(w) = &q.r#where {
394        visit_where(w, &mut out);
395    }
396    visit_select(&q.select, &mut out);
397    if let Some(o) = &q.order_by {
398        o.iter().for_each(|spec| visit_expr(&spec.expr, &mut out));
399    }
400    if let Some(f) = &q.follow {
401        visit_follow(f, &mut out);
402    }
403    out
404}
405
406// ---- hits ----------------------------------------------------------------------------
407
408/// A projected row as a hit: `{ id, path, ...rest }` with the injected
409/// columns peeled off (JavaScript's `String()` on the id, `""` for an absent
410/// path).
411fn to_hit(row: Value) -> Value {
412    let Value::Object(o) = strip_tags(row) else {
413        return Value::Object(oqx::Object::new());
414    };
415    let mut id = Value::Undefined;
416    let mut path = Value::Undefined;
417    let mut rest = Vec::new();
418    for (k, v) in o {
419        match k.as_str() {
420            ID_KEY => id = v,
421            PATH_KEY => path = v,
422            _ => rest.push((k, v)),
423        }
424    }
425    let mut hit = oqx::Object::with_capacity(rest.len() + 2);
426    hit.insert("id", Value::Str(id.to_string()));
427    hit.insert(
428        "path",
429        Value::Str(if path.is_absent() {
430            String::new()
431        } else {
432            path.to_string()
433        }),
434    );
435    for (k, v) in rest {
436        hit.insert(k, v);
437    }
438    Value::Object(hit)
439}
440
441fn hit_str(hit: &Value, key: &str) -> String {
442    hit.as_object()
443        .and_then(|o| o.get(key))
444        .map(|v| v.to_string())
445        .unwrap_or_default()
446}
447
448/// Top-level `select distinct`: dedup hits by their USER projection (every
449/// field but `id`/`path`), keeping the first. The key is the canonical JSON
450/// of the sorted `[key, value]` pairs (`JSON.stringify` in the reference).
451fn dedup_hits_by_projection(hits: Vec<Value>) -> Vec<Value> {
452    let mut seen: Vec<String> = Vec::new();
453    let mut out = Vec::new();
454    for h in hits {
455        let mut pairs: Vec<(String, Value)> = h
456            .as_object()
457            .map(|o| {
458                o.iter()
459                    .filter(|(k, _)| *k != "id" && *k != "path")
460                    .map(|(k, v)| (k.to_owned(), v.clone()))
461                    .collect()
462            })
463            .unwrap_or_default();
464        pairs.sort_by(|a, b| a.0.cmp(&b.0));
465        let key = Value::Array(
466            pairs
467                .into_iter()
468                .map(|(k, v)| Value::Array(vec![Value::Str(k), v]))
469                .collect(),
470        )
471        .to_canonical_json()
472        .to_string();
473        if seen.contains(&key) {
474            continue;
475        }
476        seen.push(key);
477        out.push(h);
478    }
479    out
480}
481
482/// A top-level `limit`/`offset` on the collect path is applied by the runner,
483/// so it must be a plain non-negative integer literal.
484fn const_bound(e: Option<&Expr>, word: &str) -> Result<Option<usize>> {
485    match e {
486        None => Ok(None),
487        Some(Expr::Lit(Value::Number(n))) if n.fract() == 0.0 && *n >= 0.0 && n.is_finite() => {
488            Ok(Some(*n as usize))
489        }
490        Some(_) => Err(SurfaceError::filter_invalid(
491            format!("top-level {word} must be a non-negative integer literal"),
492            "OQX",
493        )),
494    }
495}
496
497fn value_of(hit: &Value) -> Value {
498    hit.as_object()
499        .and_then(|o| o.get(VALUE_KEY))
500        .cloned()
501        .unwrap_or(Value::Undefined)
502}
503
504fn without_value_key(hit: Value) -> Json {
505    strip_tags(hit).to_canonical_json()
506}
507
508// ---- the run --------------------------------------------------------------------------
509
510/// Run an OQX query against `repo_id` (§1.4).
511pub fn query(
512    store: &Store,
513    repo_id: &str,
514    source: &str,
515    opts: QueryOptions<'_>,
516) -> Result<OqxResult> {
517    // Without a provider the phrases stay unembedded and the context reports
518    // `filter_invalid` ("needs an embedding provider") when one is reached —
519    // after its target check, so `semantic()` on nodes names the targets
520    // (§9; the `query` tool's pre-check is what reports `semantic_unavailable`).
521    let phrases = collect_semantic_phrases(source);
522    let mut semantic: HashMap<String, SemanticVec> = HashMap::new();
523    if let Some(provider) = opts.provider.filter(|_| !phrases.is_empty()) {
524        for phrase in phrases {
525            let vec = provider
526                .embed_query(&phrase)
527                .map_err(|e| SurfaceError::new(e.code(), e.to_string()))?;
528            semantic.insert(
529                phrase,
530                SemanticVec {
531                    model: provider.model().to_owned(),
532                    vec: f32_to_blob(&vec),
533                },
534            );
535        }
536    }
537    let runner = Runner {
538        store,
539        repo_id,
540        semantic,
541        planned: !opts.in_memory,
542    };
543    run_inner(&runner, source, opts)
544}
545
546/// One query's engine: a fresh store context per run (the planned path gives
547/// the residual a context serving the produced rows as its root). A failure
548/// inside a property read or row function is the engine's own error (the
549/// context's `get` / `call_method` return `Err`); only a failed root scan,
550/// which the `root` seam cannot raise, is read back after the run.
551struct Runner<'a> {
552    store: &'a Store,
553    repo_id: &'a str,
554    semantic: HashMap<String, SemanticVec>,
555    planned: bool,
556}
557
558impl Runner<'_> {
559    /// Tier-3 pushdown reduces the scan in SQL and the in-memory engine
560    /// finishes the residual over the produced rows (a declined plan, or
561    /// `in_memory`, runs the whole query in memory over a full scan), so
562    /// results match a pure scan. This is `oqx::PlannedEngine::run` inlined:
563    /// the store context borrows the connection, so it cannot be the
564    /// `'static` context a `Plan` carries.
565    fn run(&self, q: &Query) -> Result<oqx::OqxResult> {
566        let conn = self.store.conn();
567        let ctx = StoreContext::new(conn, self.repo_id, self.semantic.clone());
568        let plan = if self.planned {
569            SqlitePlanner::new(conn, self.repo_id)
570                .try_plan(q, &[])
571                .map_err(|e| SurfaceError::other(format!("sqlite: {e}")))?
572        } else {
573            None
574        };
575        let (ctx, residual) = match plan {
576            Some(plan) => (ctx.with_rows_root(plan.rows), Some(plan.residual)),
577            None => (ctx, None),
578        };
579        let engine = InMemoryEngine::new(ctx);
580        let out = engine.run(residual.as_ref().unwrap_or(q), &[]);
581        // `root` has no error channel: a store failure during a root scan was
582        // served as an empty scan and wins over whatever the run made of it.
583        if let Some(failed) = engine.context().take_root_failure() {
584            return Err(failed.into());
585        }
586        Ok(out?)
587    }
588}
589
590fn run_inner(engine: &Runner<'_>, source: &str, opts: QueryOptions<'_>) -> Result<OqxResult> {
591    let parsed = rewrite_query(&oqx::parse_string(source)?);
592    let consumer = parsed.consumer;
593
594    match consumer {
595        Consumer::Exists => {
596            let res = engine.run(&parsed)?;
597            let mut r = OqxResult::scalar(consumer);
598            r.exists = Some(matches!(res, oqx::OqxResult::Exists(true)));
599            return Ok(r);
600        }
601        Consumer::Count => {
602            let res = engine.run(&parsed)?;
603            let mut r = OqxResult::scalar(consumer);
604            r.count = Some(match res {
605                oqx::OqxResult::Count(n) => n,
606                _ => 0.0,
607            });
608            return Ok(r);
609        }
610        Consumer::None => {
611            let res = engine.run(&parsed)?;
612            let mut r = OqxResult::scalar(consumer);
613            r.none = Some(match res {
614                oqx::OqxResult::None(b) => b,
615                _ => true,
616            });
617            return Ok(r);
618        }
619        Consumer::Collect | Consumer::First | Consumer::Single => {}
620    }
621
622    // collect / first / single: inject id + path so every hit carries them. A
623    // top-level `select distinct` is applied HERE, not in the engine (the
624    // injected id/path are unique per row and would defeat the engine's
625    // projection dedup). A top-level `values` projection runs as a RECORD
626    // projection whose single item is renamed to VALUE_KEY.
627    let top_distinct = parsed.distinct;
628    let top_values = parsed.values;
629    let user_select: Vec<SelectItem> = if top_values {
630        parsed
631            .select
632            .first()
633            .map(|it| match it {
634                SelectItem::Field { expr, lift, .. } => SelectItem::Field {
635                    name: VALUE_KEY.to_owned(),
636                    expr: expr.clone(),
637                    lift: *lift,
638                },
639                SelectItem::Collect { op, .. } => SelectItem::Collect {
640                    name: VALUE_KEY.to_owned(),
641                    op: op.clone(),
642                },
643            })
644            .into_iter()
645            .collect()
646    } else {
647        parsed.select.clone()
648    };
649    let id_item = SelectItem::Field {
650        name: ID_KEY.to_owned(),
651        expr: Expr::Ident {
652            name: "$id".to_owned(),
653        },
654        lift: 0,
655    };
656    let path_item = SelectItem::Field {
657        name: PATH_KEY.to_owned(),
658        expr: Expr::Ident {
659            name: "$path".to_owned(),
660        },
661        lift: 0,
662    };
663    let mut select = vec![id_item, path_item];
664    select.extend(user_select);
665    // On the collect path the query's own limit/offset is taken out of the
666    // engine query and applied after the runner's distinct; first/single keep
667    // theirs (the engine's offset-aware cap is exactly right for them).
668    let (top_limit, top_offset) = (parsed.limit.clone(), parsed.offset.clone());
669    let q = Query {
670        distinct: false,
671        values: false,
672        select,
673        limit: if consumer == Consumer::Collect {
674            None
675        } else {
676            parsed.limit.clone()
677        },
678        offset: if consumer == Consumer::Collect {
679            None
680        } else {
681            parsed.offset.clone()
682        },
683        ..parsed.clone()
684    };
685    let res = engine.run(&q)?;
686
687    if matches!(consumer, Consumer::First | Consumer::Single) {
688        let row = match res {
689            oqx::OqxResult::First(r) | oqx::OqxResult::Single(r) => r,
690            _ => None,
691        };
692        let mut out = OqxResult::scalar(consumer);
693        match row {
694            None => {
695                if top_values {
696                    out.values = Some(Vec::new());
697                }
698            }
699            Some(r) => {
700                let hit = to_hit(r);
701                if top_values {
702                    out.values = Some(vec![strip_tags(value_of(&hit)).to_canonical_json()]);
703                } else {
704                    out.hits = vec![without_value_key(hit)];
705                }
706            }
707        }
708        return Ok(out);
709    }
710
711    // collect: keyset pagination on (path, id) when the order is the default.
712    let mut rows: Vec<Value> = match res {
713        oqx::OqxResult::Collect(rows) => rows.into_iter().map(to_hit).collect(),
714        _ => Vec::new(),
715    };
716    if top_distinct {
717        rows = dedup_hits_by_projection(rows);
718    }
719    let offset = const_bound(top_offset.as_ref(), "offset")?.unwrap_or(0);
720    let limit = const_bound(top_limit.as_ref(), "limit")?;
721    if offset > 0 || limit.is_some() {
722        let end = limit.map_or(rows.len(), |l| (offset + l).min(rows.len()));
723        rows = if offset >= rows.len() {
724            Vec::new()
725        } else {
726            rows[offset..end].to_vec()
727        };
728    }
729    let custom = parsed.order_by.as_ref().is_some_and(|o| !o.is_empty());
730    let cap = opts.limit.unwrap_or(DEFAULT_LIMIT);
731    let mut page = rows;
732    if !custom {
733        if let Some(cursor) = opts.cursor.filter(|c| !c.is_empty()) {
734            let parts = decode_cursor(cursor, "query", 2)?;
735            let (path, id) = (&parts[0], &parts[1]);
736            page.retain(|h| {
737                let hp = hit_str(h, "path");
738                let hi = hit_str(h, "id");
739                hp > *path || (hp == *path && hi > *id)
740            });
741        }
742    }
743    let truncated = page.len() > cap;
744    page.truncate(cap);
745    let cursor = if truncated && !custom {
746        page.last()
747            .map(|last| encode_cursor(&[&hit_str(last, "path"), &hit_str(last, "id")]))
748    } else {
749        None
750    };
751    let mut out = OqxResult::scalar(Consumer::Collect);
752    out.truncated = truncated;
753    out.cursor = cursor;
754    if top_values {
755        out.values = Some(
756            page.iter()
757                .map(|h| strip_tags(value_of(h)).to_canonical_json())
758                .collect(),
759        );
760    } else {
761        out.hits = page.into_iter().map(without_value_key).collect();
762    }
763    Ok(out)
764}
765
766#[cfg(test)]
767mod tests {
768    use super::*;
769
770    #[test]
771    fn row_functions_become_self_methods() {
772        let q = oqx::parse_string(
773            "from blocks where text(\"x\") && under_heading(\"h\") && size(attrs) > 0 && doc.$path.startsWith(\"a\")",
774        )
775        .unwrap();
776        let r = rewrite_query(&q);
777        let Some(Where::And { parts }) = &r.r#where else {
778            panic!("and")
779        };
780        let Where::Scalar { expr } = &parts[0] else {
781            panic!("scalar")
782        };
783        assert!(
784            matches!(expr, Expr::Call { recv: Some(r), name, .. } if name == "text" && **r == self_ref())
785        );
786        let Where::Scalar { expr } = &parts[2] else {
787            panic!("scalar")
788        };
789        assert!(
790            matches!(expr, Expr::Binary { left, .. } if matches!(&**left, Expr::Call { recv: None, name, .. } if name == "size"))
791        );
792    }
793
794    #[test]
795    fn semantic_phrases_are_collected_distinct() {
796        let phrases = collect_semantic_phrases(
797            "select s: semantic(\"alpha\") from docs where semantic(\"alpha\") > 0.5 || nodes exists { where semantic(\"beta\") > 0 } order by semantic(\"gamma\") desc",
798        );
799        assert_eq!(phrases, ["alpha", "beta", "gamma"]);
800        assert!(collect_semantic_phrases("not a query {{").is_empty());
801        assert!(collect_semantic_phrases("from docs").is_empty());
802    }
803
804    #[test]
805    fn hits_peel_the_injected_columns() {
806        let mut o = oqx::Object::new();
807        o.insert(ID_KEY, Value::Str("d_1".into()));
808        o.insert(PATH_KEY, Value::Null);
809        o.insert("layer", Value::Str("canon".into()));
810        let hit = to_hit(Value::Object(o));
811        let ho = hit.as_object().unwrap();
812        assert_eq!(ho.keys().collect::<Vec<_>>(), ["id", "path", "layer"]);
813        assert_eq!(ho.get("path"), Some(&Value::Str(String::new())));
814        // A user field named `id` overrides the injected one in place.
815        let mut o = oqx::Object::new();
816        o.insert(ID_KEY, Value::Str("d_1".into()));
817        o.insert(PATH_KEY, Value::Str("a.md".into()));
818        o.insert("id", Value::Number(7.0));
819        let hit = to_hit(Value::Object(o));
820        let ho = hit.as_object().unwrap();
821        assert_eq!(ho.keys().collect::<Vec<_>>(), ["id", "path"]);
822        assert_eq!(ho.get("id"), Some(&Value::Number(7.0)));
823    }
824
825    #[test]
826    fn distinct_dedups_by_user_projection_first_wins() {
827        let mk = |id: &str, t: &str| {
828            let mut o = oqx::Object::new();
829            o.insert("id", Value::Str(id.into()));
830            o.insert("path", Value::Str("p".into()));
831            o.insert("type", Value::Str(t.into()));
832            Value::Object(o)
833        };
834        let out = dedup_hits_by_projection(vec![mk("1", "a"), mk("2", "b"), mk("3", "a")]);
835        assert_eq!(out.len(), 2);
836        assert_eq!(hit_str(&out[0], "id"), "1");
837        assert_eq!(hit_str(&out[1], "id"), "2");
838    }
839
840    #[test]
841    fn top_level_bounds_must_be_literals() {
842        assert_eq!(const_bound(None, "limit").unwrap(), None);
843        assert_eq!(
844            const_bound(Some(&Expr::Lit(Value::Number(3.0))), "limit").unwrap(),
845            Some(3)
846        );
847        let e = const_bound(Some(&Expr::Lit(Value::Number(-1.0))), "offset").unwrap_err();
848        assert_eq!(e.code, "filter_invalid");
849        assert!(e.message.contains("top-level offset"));
850    }
851}