Skip to main content

relate_executor/exec/
procedures.rs

1//! `CALL` procedure execution: registered + built-in procedures,
2//! fulltext and vector index query procedures. The dispatch path
3//! classifies a `CALL` name once ([`divert_call`]): a specialized executor
4//! (ontology, vector, fulltext) or the generic registry fallback. The
5//! built-in procedure row producers live in the sibling `procedure_rows`
6//! module.
7
8use std::borrow::Cow;
9use std::collections::BTreeMap;
10
11use relate_core::{Error, Result, Value};
12use relate_ir::{Expr, YieldItems};
13use relate_model::EntityKind;
14
15use crate::ctx::ExecCtx;
16use crate::eval::eval;
17use crate::exec::candidates::{materialize_candidate, resolve_search_index};
18use crate::graph::Procedure;
19use crate::procedure_registry::ProcSignature;
20use crate::row::Row;
21
22use super::fulltext;
23use super::ontology::{exec_ontology_call, OntologyProc};
24use super::procedure_rows::{builtin_procedure_rows, executable_signature, procedure_metadata};
25use super::vector::{vector_index_candidates, vector_operand, VectorSearchFilter};
26
27/// Whether a value satisfies a procedure argument type string (`STRING`,
28/// `INTEGER`, `LIST<FLOAT>`, …). `ANY`, an empty type, a nullable `?`
29/// suffix, and a null value match everything; the accepted type vocabulary
30/// is explicit and fails closed, so an unknown (typo'd or unmodelled) type
31/// name matches nothing. The precise element-type check of a list happens
32/// in the procedure body itself. Used by the executor's `CALL` dispatch
33/// and re-exported for `relate::Database`'s compile-time call
34/// validation.
35pub fn value_matches_proc_type(v: &Value, ty: &str) -> bool {
36    let ty = ty.trim().trim_end_matches('?').trim().to_ascii_uppercase();
37    if v.is_null() || ty.is_empty() || ty == "ANY" {
38        return true;
39    }
40    // A signature may declare several admissible types (`BOOLEAN|MAP`, the
41    // Cypher 25 and legacy forms of one argument).
42    if ty.contains('|') {
43        return ty
44            .split('|')
45            .any(|alternative| value_matches_proc_type(v, alternative));
46    }
47    // The accepted type vocabulary is explicit and fails closed: an unknown
48    // (typo'd or unmodelled) name does not silently disable checking.
49    // Generic lists (`LIST<FLOAT>`, `LIST<NODE>`, …) share the list check.
50    if ty == "LIST" || ty.starts_with("LIST<") {
51        return matches!(v, Value::List(_));
52    }
53    match ty.as_str() {
54        "STRING" => matches!(v, Value::String(_)),
55        "INTEGER" | "INT" => matches!(v, Value::Int(_)),
56        "FLOAT" => matches!(v, Value::Float(_) | Value::Int(_)),
57        "NUMBER" => matches!(v, Value::Int(_) | Value::Float(_)),
58        "BOOLEAN" | "BOOL" => matches!(v, Value::Bool(_)),
59        "MAP" => matches!(v, Value::Map(_)),
60        "NODE" => matches!(v, Value::Node(_)),
61        "RELATIONSHIP" | "REL" => matches!(v, Value::Relationship(_)),
62        "PATH" => matches!(v, Value::Path(_)),
63        "BYTES" => matches!(v, Value::Bytes(_)),
64        "DATE" | "DATETIME" | "LOCAL DATETIME" | "LOCALDATETIME" | "TIME" | "LOCAL TIME"
65        | "LOCALTIME" | "DURATION" => matches!(v, Value::Temporal(_)),
66        "POINT" => matches!(v, Value::Point(_)),
67        "UUID" => matches!(v, Value::Uuid(_)),
68        "VECTOR" => matches!(v, Value::Vector { .. }),
69        _ => false,
70    }
71}
72
73pub(crate) fn call_args_match(proc_val: &Value, given: &Value) -> bool {
74    // `eq_non_null` already covers the Int/Float cross-comparison with the
75    // exact rule (`relate_model::canonical_key::eq_i64_f64`); a separate
76    // `as f64` fallback here would reintroduce the lossy cast.
77    proc_val.eq_non_null(given) || (proc_val.is_null() && given.is_null())
78}
79
80/// Static shape of a `CALL` clause (name, arguments, yields, optionality).
81#[derive(Clone, Copy)]
82pub(crate) struct CallSpec<'a> {
83    pub name: &'a str,
84    pub args: &'a [Expr],
85    pub explicit: bool,
86    pub yield_items: &'a YieldItems,
87    pub optional: bool,
88    pub where_clause: Option<&'a Expr>,
89}
90
91/// The registry-driven explicit-arity check shared by the generic `CALL`
92/// path and the `db.ontology.*` executor (the divert's consumer): an
93/// explicit call passes between `required` and `total` arguments. (The
94/// facade's compile-time `validate_calls` already enforces the same
95/// contract.)
96pub fn check_explicit_arity(name: &str, required: usize, total: usize, given: usize) -> Result<()> {
97    if given < required || given > total {
98        return Err(Error::syntax(format!(
99            "InvalidNumberOfArguments: {name} expected {total}, got {given}"
100        )));
101    }
102    Ok(())
103}
104
105/// The passing-mode backstop shared by the generic `CALL` path and the
106/// `db.ontology.*` executor (the divert's consumer): an in-query implicit
107/// call — a `CALL` with a YIELD, in a clause pipeline — cannot pass
108/// arguments; the procedure's arguments resolve only in a standalone unit
109/// call. `required_args` is the caller's registry truth: the number of
110/// declared parameters *without a default* (LABS-389: a procedure whose
111/// parameters all carry defaults is callable implicitly). (The facade's
112/// compile-time `validate_calls` enforces the same contract before
113/// execution; this is the executor-side backstop.)
114pub fn check_implicit_passing_mode(
115    explicit: bool,
116    required_args: usize,
117    has_yield: bool,
118) -> Result<()> {
119    if !explicit && required_args > 0 && has_yield {
120        return Err(Error::syntax(
121            "InvalidArgumentPassingMode: in-query CALL cannot pass arguments implicitly",
122        ));
123    }
124    Ok(())
125}
126
127/// The generic void-procedure contract: an OPTIONAL `CALL` with no return
128/// columns over no input rows yields one unit row. Callers gate on the
129/// void shape themselves.
130pub(crate) fn void_optional_unit_row(rows_empty: bool, optional: bool) -> bool {
131    rows_empty && optional
132}
133
134/// Row composition shared by every built-in row-producing procedure
135/// executor (the generic registry path, fulltext, vector and
136/// `db.ontology.get`): resolve the effective YIELD list (the caller's
137/// `yield_items`, or — when empty or `*`-containing — `default_yields`),
138/// then per input row and per produced column→value map, clone the input,
139/// insert each yielded cell under `alias.unwrap_or(column)` (`Null` for a
140/// column the producer did not emit), apply the WHERE truthy filter, and
141/// pad one null row when an OPTIONAL call produced nothing for the input
142/// row.
143pub(crate) fn compose_rows<'a>(
144    ctx: ExecCtx<'_>,
145    rows: Vec<Row>,
146    default_yields: &[&str],
147    yield_items: &YieldItems,
148    optional: bool,
149    where_clause: Option<&Expr>,
150    mut produce: impl FnMut(&Row) -> Result<Vec<Cow<'a, BTreeMap<String, Value>>>>,
151) -> Result<Vec<Row>> {
152    let ExecCtx {
153        graph,
154        params,
155        cypher_version,
156        ..
157    } = ctx;
158    let yields: Vec<(String, Option<String>)> = yield_items.resolved_pairs(default_yields);
159    // The YIELD key rule (`alias`, else the column) resolved once; every
160    // loop below reads the same keys.
161    let keys: Vec<String> = yields
162        .iter()
163        .map(|(column, alias)| alias.clone().unwrap_or_else(|| column.clone()))
164        .collect();
165    let mut out = Vec::new();
166    for input in rows {
167        let mut produced = 0usize;
168        for values in produce(&input)? {
169            let mut row = input.clone();
170            for ((column, _), key) in yields.iter().zip(&keys) {
171                row.insert(
172                    key.clone(),
173                    values.get(column).cloned().unwrap_or(Value::Null),
174                );
175            }
176            if where_clause
177                .map(|predicate| eval(graph, &row, predicate, params, cypher_version))
178                .transpose()?
179                .is_none_or(|value| value.truthy() == Some(true))
180            {
181                out.push(row);
182                produced += 1;
183            }
184        }
185        if produced == 0 && optional {
186            let mut row = input;
187            for key in &keys {
188                row.insert(key.clone(), Value::Null);
189            }
190            out.push(row);
191        }
192    }
193    Ok(out)
194}
195
196/// The entity kind a `db.index.vector.query*` procedure targets — the typed
197/// fact its name selected, so the dispatch is an exhaustive match instead
198/// of a bool re-encoded downstream.
199#[derive(Clone, Copy, Debug, PartialEq, Eq)]
200enum VectorEntity {
201    Nodes,
202    Relationships,
203}
204
205impl VectorEntity {
206    fn relationship(self) -> bool {
207        self == VectorEntity::Relationships
208    }
209}
210
211/// The one classification step of the `CALL` dispatch path
212/// ([`exec_call`]): which specialized executor owns the name — or `None`
213/// for the generic registry fallback. The `db.ontology.*` procedures
214/// (ADR-0121/ADR-0227) classify by the single [`OntologyProc::try_from`]
215/// (their executor's exhaustive dispatch enum); the vector and fulltext
216/// query procedures classify by the canonical signature registry — the
217/// exact, case-sensitive registered names (CIP-230), the same resolution
218/// the generic path's own built-in lookup below uses. This replaces the
219/// historical ad-hoc divert schemes (a registry scan plus a
220/// `starts_with` prefix plus `try_from` for the ontology divert, a
221/// lowercase literal match for the vector pair, a lowercase substring
222/// match for fulltext): no parallel name-matching scheme remains in the
223/// dispatch path.
224enum CallDivert {
225    /// One of the four `db.ontology.*` procedures, already classified.
226    Ontology(OntologyProc),
227    /// One of the two `db.index.vector.query*` procedures, with the entity
228    /// kind its name selects.
229    Vector(VectorEntity),
230    /// One of the two `db.index.fulltext.query*` procedures;
231    /// `relationship` distinguishes `queryRelationships` from `queryNodes`.
232    FulltextQuery { relationship: bool },
233}
234
235/// The diverted-call classification as a predicate, for the producer-table
236/// completeness pin (test-only: no production path asks without also needing
237/// the variant).
238#[cfg(test)]
239pub(crate) fn is_diverted_call(name: &str) -> bool {
240    divert_call(name).is_some()
241}
242
243/// The one classification step: decide [`CallDivert`] for one `CALL` name,
244/// once, before the generic machinery.
245fn divert_call(name: &str) -> Option<CallDivert> {
246    if let Ok(proc) = OntologyProc::try_from(name) {
247        return Some(CallDivert::Ontology(proc));
248    }
249    // The registry lookup doubles as the classifier: only exact registered
250    // names divert, case-sensitively (CIP-230), exactly like the generic
251    // path's built-in resolution below.
252    match crate::procedure_registry::builtin_procedure_signature(name)?.name {
253        "db.index.vector.queryNodes" => Some(CallDivert::Vector(VectorEntity::Nodes)),
254        "db.index.vector.queryRelationships" => {
255            Some(CallDivert::Vector(VectorEntity::Relationships))
256        }
257        "db.index.fulltext.queryNodes" => Some(CallDivert::FulltextQuery {
258            relationship: false,
259        }),
260        "db.index.fulltext.queryRelationships" => {
261            Some(CallDivert::FulltextQuery { relationship: true })
262        }
263        _ => None,
264    }
265}
266
267/// The runtime `CALL` contract for the diverted `db.ontology.*`
268/// procedures — the SAME checks the generic path applies below, from the
269/// ONE registry signature: the passing-mode backstop
270/// (`check_implicit_passing_mode`), then the explicit arity
271/// (`check_explicit_arity`). Applied at the divert site in `exec_call`
272/// so the diverted executor enforces exactly the contract the generic
273/// path enforces, visibly, at the same place.
274pub(super) fn check_ontology_call_contract(call: &CallSpec<'_>) -> Result<()> {
275    // The four names are statically registered and the classification
276    // accepts exactly those four (pinned by test), so this lookup cannot
277    // miss; the fail-closed arm replaces the divert's historical
278    // `ProcedureNotFound` error should the table and the classification
279    // ever drift apart.
280    let signature = crate::procedure_registry::builtin_procedure_signature(call.name)
281        .ok_or_else(|| Error::procedure_not_found(call.name))?;
282    // All-default parameters are callable paren-less (LABS-389): the
283    // guard keys on required args, not declared ones.
284    check_implicit_passing_mode(
285        call.explicit,
286        signature.required_args(),
287        call.yield_items.has_yield(),
288    )?;
289    if call.explicit {
290        check_explicit_arity(
291            call.name,
292            signature.required_args(),
293            signature.args.len(),
294            call.args.len(),
295        )?;
296    }
297    Ok(())
298}
299
300pub(crate) fn exec_call(
301    ctx: ExecCtx<'_>,
302    rows: Vec<Row>,
303    call: CallSpec<'_>,
304) -> Result<(Vec<Row>, bool)> {
305    // ONE classification step decides divert-or-generic once. The
306    // `db.ontology.*` divert runs the same runtime contract (passing
307    // mode, arity — `check_ontology_call_contract`) the generic path runs
308    // below, at this same site, before handing the call to its executor;
309    // the vector executor takes the classified entity kind (node vs
310    // relationship) with it. Everything else falls to the generic
311    // registry machinery below.
312    // The unit fact is the registry's: every diverted name is a registered
313    // signature, so the call path reports `is_void()` rather than re-deriving
314    // it per arm.
315    let yields_unit = crate::exec::procedure_rows::executable_signature(call.name)
316        .is_some_and(ProcSignature::is_void);
317    match divert_call(call.name) {
318        Some(CallDivert::Ontology(proc)) => {
319            check_ontology_call_contract(&call)?;
320            exec_ontology_call(ctx, rows, call, proc).map(|rows| (rows, yields_unit))
321        }
322        Some(CallDivert::Vector(entity)) => {
323            exec_vector_query_call(ctx, rows, entity, call).map(|rows| (rows, yields_unit))
324        }
325        Some(CallDivert::FulltextQuery { relationship }) => {
326            exec_fulltext_query_call(ctx, rows, relationship, call).map(|rows| (rows, yields_unit))
327        }
328        None => exec_registry_call(ctx, rows, call),
329    }
330}
331
332/// Which rows one resolved call answers: the rows it already has (a
333/// registered procedure's stored rows or a no-argument built-in's
334/// once-produced rows), or a producing signature whose rows are a function of
335/// each row's bound arguments.
336enum CallRows<'a> {
337    Rows(Cow<'a, [BTreeMap<String, Value>]>),
338    PerRow(&'static ProcSignature),
339}
340
341/// One `CALL`'s resolved shape, from the one resolution: the metadata its
342/// arguments bind against, its minimum arity, whether it yields columns, and
343/// where its rows come from. The call path reads this and never re-matches
344/// the target.
345struct ResolvedCall<'a> {
346    metadata: Cow<'a, Procedure>,
347    required_args: usize,
348    yields_unit: bool,
349    rows: CallRows<'a>,
350}
351
352/// The generic registry path a non-diverted call takes: one resolution into a
353/// [`CallTarget`], the passing-mode and arity contract, per-row argument
354/// binding and type check, row matching, composition, and the void-procedure
355/// unit row. One unit, so the classifier above stays a classifier.
356fn exec_registry_call(
357    ctx: ExecCtx<'_>,
358    rows: Vec<Row>,
359    call: CallSpec<'_>,
360) -> Result<(Vec<Row>, bool)> {
361    let ExecCtx {
362        graph, principal, ..
363    } = ctx;
364    let CallSpec {
365        name,
366        args,
367        explicit,
368        yield_items,
369        optional,
370        where_clause,
371    } = call;
372    // One resolution decides registered-vs-builtin and carries everything
373    // the call needs: metadata, arity, the unit fact and the row source. A
374    // void call produces no rows at all, so nothing is produced to be
375    // discarded.
376    let registered = graph.procedure(name);
377    let resolved = match &registered {
378        Some(procedure) => ResolvedCall {
379            yields_unit: procedure.yield_names.is_empty() && procedure.rows.is_empty(),
380            metadata: Cow::Borrowed(procedure),
381            required_args: procedure.arg_names.len(),
382            rows: CallRows::Rows(Cow::Borrowed(procedure.rows.as_slice())),
383        },
384        None => {
385            let signature =
386                executable_signature(name).ok_or_else(|| Error::procedure_not_found(name))?;
387            let rows = if signature.is_void() {
388                CallRows::Rows(Cow::Borrowed(&[]))
389            } else if signature.args.is_empty() {
390                CallRows::Rows(Cow::Owned(builtin_procedure_rows(
391                    graph,
392                    signature,
393                    principal,
394                    &BTreeMap::new(),
395                )?))
396            } else {
397                CallRows::PerRow(signature)
398            };
399            ResolvedCall {
400                yields_unit: signature.is_void(),
401                metadata: Cow::Owned(procedure_metadata(signature)),
402                required_args: signature.required_args(),
403                rows,
404            }
405        }
406    };
407    let ResolvedCall {
408        metadata,
409        required_args,
410        yields_unit,
411        rows: row_source,
412    } = resolved;
413    // Same rule on the unit-call path (LABS-389): required_args already
414    // folds the builtin/registered split, so the guard reads it instead
415    // of any-args.
416    check_implicit_passing_mode(explicit, required_args, yield_items.has_yield())?;
417    if explicit {
418        check_explicit_arity(name, required_args, metadata.arg_names.len(), args.len())?;
419    }
420    if yields_unit && void_optional_unit_row(rows.is_empty(), optional) {
421        return Ok((vec![Row::new()], true));
422    }
423    let binding = CallBinding {
424        name,
425        source: if explicit {
426            CallArgsSource::Explicit(args)
427        } else {
428            CallArgsSource::Implicit
429        },
430        metadata: &metadata,
431        required_args,
432        ctx,
433    };
434    let mut out = Vec::new();
435    // One binding pass over the driving rows: a void call binds and
436    // type-checks each row's arguments too, it just produces nothing.
437    for row in &rows {
438        let call_args = binding.bind_row(row)?;
439        if yields_unit {
440            continue;
441        }
442        // Rows come from the resolved target: a registered procedure's are
443        // fixed at registration, a no-argument built-in's were produced once
444        // above, and any other built-in's are a function of this row's bound
445        // arguments (a null `db.schema.visualization` options map selects
446        // nothing at all; a `db.stats.retrieve` section names the section it
447        // serves).
448        let proc_rows: Cow<'_, [BTreeMap<String, Value>]> = match &row_source {
449            CallRows::Rows(rows) => Cow::Borrowed(rows.as_ref()),
450            CallRows::PerRow(signature) => Cow::Owned(builtin_procedure_rows(
451                graph, signature, principal, &call_args,
452            )?),
453        };
454        let matched: Vec<_> = proc_rows
455            .iter()
456            .filter(|pr| {
457                metadata
458                    .arg_names
459                    .iter()
460                    .all(|n| match (pr.get(n), call_args.get(n)) {
461                        (Some(a), Some(b)) => call_args_match(a, b),
462                        (None, _) => true,
463                        _ => false,
464                    })
465            })
466            .collect();
467        if matched.is_empty() && metadata.yield_names.is_empty() {
468            out.push(row.clone());
469            continue;
470        }
471        let default_yields: Vec<&str> = metadata.yield_names.iter().map(String::as_str).collect();
472        out.extend(compose_rows(
473            ctx,
474            vec![row.clone()],
475            &default_yields,
476            yield_items,
477            optional,
478            where_clause,
479            // The matched rows are BORROWED, not cloned: compose_rows
480            // clones only the yielded cells it inserts, so a wide
481            // procedure row costs one cell per yielded column — never a
482            // full-row deep clone per input row.
483            |_| Ok(matched.iter().map(|pr| Cow::Borrowed(*pr)).collect()),
484        )?);
485    }
486    Ok((if yields_unit { rows } else { out }, yields_unit))
487}
488
489/// The bound-argument source of one resolved CALL: explicit positional
490/// expressions, or the implicit parameter/row-column names.
491enum CallArgsSource<'a> {
492    Explicit(&'a [Expr]),
493    Implicit,
494}
495
496/// One resolved CALL's binding context: the facts every per-row bind needs,
497/// carried once instead of as nine positional parameters.
498struct CallBinding<'a> {
499    name: &'a str,
500    source: CallArgsSource<'a>,
501    metadata: &'a Procedure,
502    required_args: usize,
503    ctx: ExecCtx<'a>,
504}
505
506impl CallBinding<'_> {
507    /// Bind one driving row's arguments and type-check them against the
508    /// resolved metadata — the one binding policy the row loop and the
509    /// resolved call share, so a void procedure's arguments are validated
510    /// exactly like a row-answering one's.
511    fn bind_row(&self, row: &Row) -> Result<BTreeMap<String, Value>> {
512        // One declared type per declared argument: `procedure_metadata` and
513        // registration build the two lists together, so a shorter type list
514        // is an engine bug, not a per-argument absence.
515        if self.metadata.arg_types.len() != self.metadata.arg_names.len() {
516            return Err(Error::internal(format!(
517                "procedure '{}' declares {} arguments but {} types",
518                self.name,
519                self.metadata.arg_names.len(),
520                self.metadata.arg_types.len()
521            )));
522        }
523        let explicit = matches!(self.source, CallArgsSource::Explicit(_));
524        let args = match self.source {
525            CallArgsSource::Explicit(args) => args,
526            CallArgsSource::Implicit => &[],
527        };
528        if !explicit {
529            // Only parameters without a default are mandatory; defaulted
530            // built-in parameters (e.g. `db.awaitIndexes`'s
531            // `timeOutSeconds`) may be omitted.
532            let missing_required = self
533                .metadata
534                .arg_names
535                .iter()
536                .take(self.required_args)
537                .any(|n| !self.ctx.params.contains_key(n) && !row.contains_key(n));
538            if missing_required {
539                return Err(Error::syntax(format!(
540                    "MissingParameter: implicit args for {}",
541                    self.name
542                )));
543            }
544        }
545        let mut call_args = BTreeMap::new();
546        for (index, (n, ty)) in self
547            .metadata
548            .arg_names
549            .iter()
550            .zip(self.metadata.arg_types.iter())
551            .enumerate()
552        {
553            let Some(value) = call_arg_value(&self.ctx, row, args, explicit, index, n)? else {
554                // A defaulted implicit argument may legitimately be absent.
555                continue;
556            };
557            if !value_matches_proc_type(&value, ty) {
558                return Err(Error::syntax(format!(
559                    "InvalidArgumentType: {} argument `{n}` expects {ty}",
560                    self.name
561                )));
562            }
563            call_args.insert(n.clone(), value);
564        }
565        Ok(call_args)
566    }
567}
568
569/// Resolve one declared CALL argument: its explicit positional expression
570/// evaluated against the driving row, or the implicit parameter/row-column
571/// value. The one per-argument resolver the generic binder and the
572/// `db.ontology.*` readers share, so the policy is spelled once.
573pub(crate) fn call_arg_value(
574    ctx: &ExecCtx<'_>,
575    row: &Row,
576    args: &[Expr],
577    explicit: bool,
578    index: usize,
579    arg_name: &str,
580) -> Result<Option<Value>> {
581    if explicit {
582        args.get(index)
583            .map(|expr| eval(ctx.graph, row, expr, ctx.params, ctx.cypher_version))
584            .transpose()
585    } else {
586        Ok(ctx
587            .params
588            .get(arg_name)
589            .cloned()
590            .or_else(|| row.get(arg_name).cloned()))
591    }
592}
593
594/// The one fulltext scan for both `db.index.fulltext.query*` procedures:
595/// `relationship` selects the entity kind (relationship indexes match on
596/// relationship types, node indexes on labels) and the yielded column name.
597pub(crate) fn exec_fulltext_query_call(
598    ctx: ExecCtx<'_>,
599    rows: Vec<Row>,
600    relationship: bool,
601    call: CallSpec<'_>,
602) -> Result<Vec<Row>> {
603    let CallSpec {
604        name,
605        args,
606        yield_items,
607        optional,
608        where_clause,
609        ..
610    } = call;
611    let ExecCtx {
612        graph,
613        params,
614        cypher_version,
615        ..
616    } = ctx;
617    if args.len() != 2 {
618        return Err(Error::syntax(format!(
619            "InvalidNumberOfArguments: {name} expected 2, got {}",
620            args.len()
621        )));
622    }
623    // The entity column is the divert's classification; the score column
624    // is shared by both entity variants, so the table is one choice plus
625    // one literal.
626    let entity_column = if relationship { "relationship" } else { "node" };
627    let score_key = "score";
628    let columns = [entity_column, score_key];
629    compose_rows(
630        ctx,
631        rows,
632        &columns,
633        yield_items,
634        optional,
635        where_clause,
636        |input| {
637            let index_name = eval(graph, input, &args[0], params, cypher_version)?
638                .as_string()
639                .ok_or_else(|| Error::invalid_argument_type("indexName must be STRING"))?
640                .to_string();
641            let query = eval(graph, input, &args[1], params, cypher_version)?
642                .as_string()
643                .ok_or_else(|| Error::invalid_argument_type("query must be STRING"))?
644                .to_string();
645            // The shared SEARCH index resolution (the vector procedure's
646            // one spelling): a missing or non-fulltext index is that
647            // helper's typed error. Only the entity-kind disagreement is
648            // this procedure's own — `queryNodes` on a relationship index
649            // (or the reverse) has no scan to run.
650            let (detail, _options) =
651                resolve_search_index(graph, &index_name, crate::redo::IndexKindSpec::Fulltext)?;
652            if detail.relationship != relationship {
653                return Err(Error::execution(
654                    "WrongIndexType: fulltext index entity type mismatch",
655                ));
656            }
657            // The one CIP-225 scan: the Lucene-style query parser (terms
658            // OR'd, `AND`/`OR`/`NOT`, `property:term` field filters) and the
659            // live-fitted BM25 score, ranked best-first, no window.
660            let kind = EntityKind::from_relationship_flag(detail.relationship);
661            let produced =
662                fulltext::search_all(graph, &detail, &query, fulltext::Analyzer::Standard)
663                    .into_iter()
664                    .map(|(id, score)| {
665                        Cow::Owned(BTreeMap::from([
666                            (
667                                entity_column.to_string(),
668                                materialize_candidate(graph, kind, id),
669                            ),
670                            (score_key.to_string(), Value::Float(score)),
671                        ]))
672                    })
673                    .collect();
674            Ok(produced)
675        },
676    )
677}
678
679fn exec_vector_query_call(
680    ctx: ExecCtx<'_>,
681    rows: Vec<Row>,
682    entity: VectorEntity,
683    call: CallSpec<'_>,
684) -> Result<Vec<Row>> {
685    let relationship = entity.relationship();
686    let CallSpec {
687        name,
688        args,
689        yield_items,
690        optional,
691        where_clause,
692        ..
693    } = call;
694    let ExecCtx {
695        graph,
696        params,
697        cypher_version,
698        ..
699    } = ctx;
700    if args.len() != 3 {
701        return Err(Error::syntax(format!(
702            "InvalidNumberOfArguments: {name} expected 3, got {}",
703            args.len()
704        )));
705    }
706    // The divert already classified the entity kind (`relationship` is
707    // `queryRelationships` vs `queryNodes`); no name re-matching here.
708    let entity_column = if relationship { "relationship" } else { "node" };
709    compose_rows(
710        ctx,
711        rows,
712        &[entity_column, "score"],
713        yield_items,
714        optional,
715        where_clause,
716        |input| {
717            let index_name = eval(graph, input, &args[0], params, cypher_version)?
718                .as_string()
719                .ok_or_else(|| Error::invalid_argument_type("indexName must be STRING"))?
720                .to_string();
721            let limit = match eval(graph, input, &args[1], params, cypher_version)? {
722                Value::Int(value) if (1..=i32::MAX as i64).contains(&value) => value as usize,
723                _ => return Err(Error::ty(
724                    "InvalidArgumentValue: numberOfNearestNeighbours must be a positive INTEGER",
725                )),
726            };
727            let query = eval(graph, input, &args[2], params, cypher_version)?;
728            let Some(query) = vector_operand(&query)? else {
729                return Ok(Vec::new());
730            };
731            let (index_kind, candidates) = vector_index_candidates(
732                ctx,
733                &index_name,
734                &query,
735                0,
736                limit,
737                VectorSearchFilter {
738                    filters: &[],
739                    input,
740                },
741            )?;
742            if index_kind.is_relationship() != relationship {
743                return Err(Error::execution(
744                    "WrongIndexType: vector index entity type mismatch",
745                ));
746            }
747            let mut produced = Vec::new();
748            for (entity, score) in candidates {
749                // Both entity spellings map to the candidate (the
750                // historical cell match keyed `"node" | "relationship"`),
751                // so an explicit YIELD of either sees it.
752                produced.push(BTreeMap::from([
753                    ("node".to_string(), entity.clone()),
754                    ("relationship".to_string(), entity.clone()),
755                    ("score".to_string(), Value::Float(score)),
756                ]));
757            }
758            Ok(produced.into_iter().map(Cow::Owned).collect())
759        },
760    )
761}
762
763#[cfg(test)]
764mod type_vocabulary_tests {
765    use super::value_matches_proc_type;
766    use relate_core::Value;
767
768    /// ADR-0463 round 6: the list spelling is exactly `LIST` or `LIST<…>`;
769    /// a bare prefix match would silently accept `LISTS`/`LISTING` as any
770    /// list, re-opening the fail-closed vocabulary.
771    #[test]
772    fn list_type_accepts_only_list_or_list_generic() {
773        let list = Value::List(Vec::new().into());
774        assert!(value_matches_proc_type(&list, "LIST"));
775        assert!(value_matches_proc_type(&list, "LIST<FLOAT>"));
776        assert!(value_matches_proc_type(&list, "list<string>"));
777        assert!(!value_matches_proc_type(&list, "LISTS"));
778        assert!(!value_matches_proc_type(&list, "LISTING"));
779        assert!(!value_matches_proc_type(&Value::Int(1), "LISTS"));
780    }
781}
782
783#[cfg(test)]
784mod row_provenance_tests {
785    use crate::exec::test_support::{exec_autocommit, exec_cypher};
786    use crate::graph::Graph;
787    use relate_core::Value;
788
789    /// A no-argument built-in's rows are produced once for the call and
790    /// answered by every driving row — two driving rows times two labels,
791    /// never one production that only the first row sees.
792    #[test]
793    fn a_no_argument_builtin_answers_its_rows_for_every_driving_row() {
794        let graph = Graph::default();
795        exec_autocommit(&graph, "CREATE (:User), (:Admin)").expect("the fixture's CREATE succeeds");
796
797        let result = exec_cypher(
798            &graph,
799            "UNWIND [1, 2] AS i CALL db.labels() YIELD label \
800             RETURN i, label ORDER BY i, label",
801        );
802        let string = |value: &str| Value::String(value.into());
803        assert_eq!(
804            result.rows,
805            vec![
806                vec![Value::Int(1), string("Admin")],
807                vec![Value::Int(1), string("User")],
808                vec![Value::Int(2), string("Admin")],
809                vec![Value::Int(2), string("User")],
810            ]
811        );
812    }
813
814    /// A built-in whose producer reads its arguments produces them under
815    /// every driving row's own binding: `db.stats.retrieve` is served the
816    /// section each row carries, never an empty argument map.
817    #[test]
818    fn an_argument_taking_builtin_produces_rows_from_each_rows_bindings() {
819        let graph = Graph::default();
820
821        let result = exec_cypher(
822            &graph,
823            "UNWIND [1, 2] AS i WITH i, 'GRAPH COUNTS' AS wanted \
824             CALL db.stats.retrieve(wanted) YIELD section RETURN i, section",
825        );
826        assert_eq!(
827            result.rows,
828            vec![
829                vec![Value::Int(1), Value::String("GRAPH COUNTS".into())],
830                vec![Value::Int(2), Value::String("GRAPH COUNTS".into())],
831            ]
832        );
833    }
834}