Skip to main content

relate_executor/
procedure_registry.rs

1//! Canonical built-in procedure signature registry: the single table of
2//! argument/return-column names and types for every procedure the engine
3//! executes or lists.
4//!
5//! Five consumers share this table so they cannot drift apart (e.g. the
6//! vector `query` argument typed `ANY` in one place and `LIST<FLOAT>` in
7//! another):
8//!
9//! - `exec::procedure_rows::builtin_procedure_rows` — the executor's `CALL`
10//!   dispatch (arg names/types, yield columns, arity, and the rows);
11//! - `relate::Database`'s compile-time `validate_calls` (same shapes);
12//! - `relate`'s namespace write classification (`writes`, ADR-0116 §4);
13//! - `show_catalog::procedure_catalog_rows` — the `SHOW PROCEDURES` catalog
14//!   (CIP-84/CIP-113/CIP-157 display, which additionally reads the
15//!   description/mode/deprecation fields);
16//! - `procedure_gate::procedure_preview_feature` — the preview-feature
17//!   mapping of the `db.ontology.*` family (ADR-0378).
18
19use relate_core::Value;
20
21use crate::catalog_meta::{DeprecatedBy, ProcArgMeta};
22
23/// Which row producer a row-declaring executable signature carries: the
24/// registry owns the fact, so a signature that declares return columns but
25/// names no producer cannot be written without the table saying so, and the
26/// producer table cannot drift into a second name-keyed list.
27///
28/// The variants are listed in the same order as their arms in the `produce`
29/// dispatch (`exec::procedure_rows`); keeping the two in step is a
30/// readability convention, not an enforced invariant.
31///
32/// Crate-internal: no reader outside this crate names a producer, matching
33/// `args`/`returns`.
34#[derive(Clone, Copy, Debug)]
35pub(crate) enum RowProducer {
36    TxGetMetaData,
37    DbmsComponents,
38    DbPing,
39    DbLabels,
40    DbRelationshipTypes,
41    DbPropertyKeys,
42    DbInfo,
43    DbmsInfo,
44    DbmsShowCurrentUser,
45    DbmsConfig,
46    DbmsLicenseAgreementDetails,
47    DbmsListCapabilities,
48    FulltextAnalyzers,
49    DbStatsRetrieve,
50    SchemaNodeTypeProperties,
51    SchemaRelTypeProperties,
52    SchemaVisualization,
53}
54
55/// Static signature and catalog metadata of a built-in procedure.
56pub struct ProcSignature {
57    pub name: &'static str,
58    pub description: &'static str,
59    pub mode: &'static str,
60    pub works_on_system: bool,
61    pub admin: bool,
62    /// Formal parameters. Required parameters come first; a parameter with
63    /// a `default` may be omitted by the caller (CIP-113's
64    /// `name = default :: type` rendering). Crate-internal (the parameter
65    /// type is); a cross-crate caller reads [`Self::parameters`].
66    pub(crate) args: &'static [ProcArgMeta],
67    /// Return columns (`YIELD` names/types). Crate-internal; a cross-crate
68    /// caller reads [`Self::return_columns`].
69    pub(crate) returns: &'static [ProcArgMeta],
70    /// The replacement when the procedure is deprecated (CIP-157's
71    /// `deprecatedBy`); `None` means not deprecated. One fact, so a bool and
72    /// its replacement cannot disagree.
73    pub deprecated_by: Option<DeprecatedBy>,
74    /// True when `CALL` can actually execute it (as opposed to a
75    /// catalog-only entry pinned by CIP-84/CIP-113/CIP-157 scenarios that no
76    /// scenario calls).
77    pub executable: bool,
78    /// True when `SHOW PROCEDURES` lists it.
79    pub listed: bool,
80    /// The row producer a row-declaring executable signature carries; `None`
81    /// for a void signature, a catalog-only entry, a diverted procedure
82    /// (whose `CALL` path is a dedicated executor — see `divert_call`) and
83    /// a compat callable (ADR-0699: the query front-end rewrites its `CALL`
84    /// into a Cypher body before lowering — `relate_front`'s
85    /// `compat_callables` table owns the membership, and the dispatch
86    /// declines it by name). One fact with the return columns: a
87    /// row-declaring signature answers through exactly one of the three —
88    /// a producer arm here, a diverted call path, or the front-end
89    /// rewrite that lowers it away before the executor ever sees it.
90    pub(crate) rows: Option<RowProducer>,
91    /// True when a `CALL` mutates the graph or catalog (ADR-0116 §4) — the
92    /// write classification `relate`'s namespace rules read, so there is
93    /// one table (`mode` does not encode this: DBMS-mode entries such as
94    /// `dbms.components` and `tx.setMetaData` are not graph/catalog writes).
95    pub writes: bool,
96    /// True when the procedure's commit is a store-level commit of its own
97    /// (ADR-0120 §3) — the `db.ontology.set` / `db.ontology.drop` store ops,
98    /// which push a store-level redo and require the implicit-only /
99    /// no-mixed-writes gates; the in-overlay `db.ontology.apply` write is
100    /// not one. The store-op classification reads this table the same way
101    /// the write classification reads `writes`.
102    pub store_level: bool,
103}
104
105impl ProcSignature {
106    /// The common entry: a listed, executable read procedure with no
107    /// description, catalog flags or deprecation. The builders below name
108    /// only what a row changes from it, so the table states each entry's
109    /// deviations instead of restating ten fields per row.
110    pub(crate) const fn read(name: &'static str) -> Self {
111        Self {
112            name,
113            description: "",
114            mode: "READ",
115            works_on_system: false,
116            admin: false,
117            args: &[],
118            returns: &[],
119            deprecated_by: None,
120            executable: true,
121            listed: true,
122            writes: false,
123            store_level: false,
124            rows: None,
125        }
126    }
127
128    /// A listed procedure whose mode is `"DBMS"`. The system-database
129    /// capability is a separate fact — the corpus lists `tx.setMetaData` as
130    /// DBMS-mode but not system-database-capable (ADR-0497 §6) — so each
131    /// entry states [`Self::works_on_system`] itself.
132    pub(crate) const fn dbms(name: &'static str) -> Self {
133        let mut sig = Self::read(name);
134        sig.mode = "DBMS";
135        sig
136    }
137
138    /// A listed procedure whose mode is `"WRITE"`. The `writes` flag is a
139    /// separate fact: a catalog-only entry carries the mode without being
140    /// callable, so it can mutate nothing.
141    pub(crate) const fn write(name: &'static str) -> Self {
142        let mut sig = Self::read(name);
143        sig.mode = "WRITE";
144        sig
145    }
146
147    /// A listed procedure whose mode is `"SCHEMA"`. The [`Self::writes`]
148    /// flag is a separate fact, as on [`Self::write`]: a schema-mode
149    /// procedure that mutates the store still routes its statements to the
150    /// write path through `writes`, while the mode itself is only the
151    /// catalog rendering.
152    pub(crate) const fn schema(name: &'static str) -> Self {
153        let mut sig = Self::read(name);
154        sig.mode = "SCHEMA";
155        sig
156    }
157
158    /// The row producer this signature's rows come from.
159    pub(crate) const fn rows(mut self, rows: RowProducer) -> Self {
160        self.rows = Some(rows);
161        self
162    }
163
164    /// The procedure works on the system database.
165    pub(crate) const fn works_on_system(mut self) -> Self {
166        self.works_on_system = true;
167        self
168    }
169
170    /// A description for the catalog row.
171    pub(crate) const fn described(mut self, description: &'static str) -> Self {
172        self.description = description;
173        self
174    }
175
176    /// The procedure requires admin privileges.
177    pub(crate) const fn admin(mut self) -> Self {
178        self.admin = true;
179        self
180    }
181
182    /// A `CALL` mutates the graph or catalog (ADR-0116 §4).
183    pub(crate) const fn writes(mut self) -> Self {
184        self.writes = true;
185        self
186    }
187
188    /// The procedure's commit is a store-level commit of its own (ADR-0120 §3).
189    pub(crate) const fn store_level(mut self) -> Self {
190        self.store_level = true;
191        self
192    }
193
194    /// The procedure's formal parameters.
195    pub(crate) const fn args(mut self, args: &'static [ProcArgMeta]) -> Self {
196        self.args = args;
197        self
198    }
199
200    /// The procedure's return columns.
201    pub(crate) const fn returns(mut self, returns: &'static [ProcArgMeta]) -> Self {
202        self.returns = returns;
203        self
204    }
205
206    /// The replacement when the procedure is deprecated (CIP-157).
207    pub(crate) const fn deprecated_by(mut self, by: DeprecatedBy) -> Self {
208        self.deprecated_by = Some(by);
209        self
210    }
211
212    /// Whether `CALL` can actually execute it.
213    pub(crate) const fn executable(mut self, executable: bool) -> Self {
214        self.executable = executable;
215        self
216    }
217
218    /// Whether `SHOW PROCEDURES` lists it.
219    pub(crate) const fn listed(mut self, listed: bool) -> Self {
220        self.listed = listed;
221        self
222    }
223}
224
225impl ProcSignature {
226    /// Number of leading parameters without a default — the minimum arity a
227    /// `CALL` may pass. (`args` lists required parameters first.)
228    pub fn required_args(&self) -> usize {
229        self.args.iter().take_while(|a| a.default.is_none()).count()
230    }
231
232    /// The formal parameters as `(name, declared type)` pairs, required
233    /// parameters first — a caller outside this crate's view of `args`
234    /// (`ProcArgMeta` is crate-internal). The compile-time `CALL`
235    /// validation reads this.
236    pub fn parameters(&self) -> impl Iterator<Item = (&'static str, &'static str)> + '_ {
237        self.args.iter().map(|arg| (arg.name, arg.type_str))
238    }
239
240    /// The `YIELD` column names, in signature order — a caller outside this
241    /// crate's view of `returns`.
242    pub fn return_columns(&self) -> impl Iterator<Item = &'static str> + '_ {
243        self.returns.iter().map(|ret| ret.name)
244    }
245
246    /// Whether the procedure produces no rows — a unit procedure such as
247    /// `tx.setMetaData`, `db.createLabel` or `db.awaitIndexes` declares no
248    /// return columns. The one void fact: the clause engine's terminal-call
249    /// check and the row-producer dispatch both read it instead of each
250    /// re-deriving it from `returns`.
251    pub(crate) fn is_void(&self) -> bool {
252        self.returns.is_empty()
253    }
254}
255
256mod signatures;
257
258pub use signatures::BUILTIN_PROCEDURE_SIGNATURES;
259
260/// Looks up a built-in procedure signature by name, case-sensitively.
261/// Casing sensitivity: built-in *function* names are
262/// case-insensitive, but built-in *procedure* names are case-sensitive --
263/// `CALL DB.LABELS()` is an UnknownProcedure error, only the exact declared
264/// casing (`CALL db.labels()`) resolves. The validator must agree.
265pub fn builtin_procedure_signature(name: &str) -> Option<&'static ProcSignature> {
266    BUILTIN_PROCEDURE_SIGNATURES
267        .iter()
268        .find(|sig| sig.name == name)
269}
270
271/// Whether the procedure behind `name` declares no return columns — the one
272/// void-procedure fact, so the `CALL` contract validator and the
273/// redundant-`OPTIONAL` notification detector cannot drift.
274///
275/// `registered` is the caller's own lookup of a user-registered procedure,
276/// which shadows the built-in: it answers from its `yield_names`, the
277/// built-in from the one signature table. A name that is neither is not a
278/// procedure, and is not void.
279pub fn is_void_procedure(registered: Option<&crate::graph::Procedure>, name: &str) -> bool {
280    if let Some(procedure) = registered {
281        return procedure.yield_names.is_empty();
282    }
283    builtin_procedure_signature(name).is_some_and(ProcSignature::is_void)
284}
285
286/// Whether a value satisfies a procedure argument type string (`STRING`,
287/// `INTEGER`, `LIST<FLOAT>`, …). `ANY`, an empty type, a nullable `?`
288/// suffix, and a null value match everything; the accepted type vocabulary
289/// is explicit and fails closed, so an unknown (typo'd or unmodelled) type
290/// name matches nothing. The precise element-type check of a list happens
291/// in the procedure body itself. The canonical home is here, beside the
292/// type strings this registry declares — the facade's compile-time
293/// `validate_calls` and the executor's per-row binder read the one
294/// spelling, so the two cannot drift.
295pub fn value_matches_proc_type(v: &Value, ty: &str) -> bool {
296    matches_normalized_type(v, &normalize_proc_type(ty))
297}
298
299/// One signature's declared type string in the vocabulary's own form —
300/// trimmed, `?`-stripped, uppercased. The binder normalizes its binding's
301/// declared types once at construction, so the per-row check never pays
302/// this again.
303pub(crate) fn normalize_proc_type(ty: &str) -> String {
304    ty.trim().trim_end_matches('?').trim().to_ascii_uppercase()
305}
306
307/// The vocabulary match over an already-normalized type string (a
308/// signature may declare several admissible types — `BOOLEAN|MAP`, the
309/// Cypher 25 and legacy forms of one argument — each alternative already
310/// normalized with the whole).
311pub(crate) fn matches_normalized_type(v: &Value, ty: &str) -> bool {
312    if v.is_null() || ty.is_empty() || ty == "ANY" {
313        return true;
314    }
315    if ty.contains('|') {
316        // Each alternative trims on its own: a union spelled with spaces
317        // (`STRING | INTEGER`) normalizes as a whole, so the split arms
318        // can carry leading or trailing blanks.
319        return ty
320            .split('|')
321            .any(|alternative| matches_normalized_type(v, alternative.trim()));
322    }
323    // The accepted type vocabulary is explicit and fails closed: an unknown
324    // (typo'd or unmodelled) name does not silently disable checking.
325    // Generic lists (`LIST<FLOAT>`, `LIST<NODE>`, …) share the list check.
326    if ty == "LIST" || ty.starts_with("LIST<") {
327        return matches!(v, Value::List(_));
328    }
329    match ty {
330        "STRING" => matches!(v, Value::String(_)),
331        "INTEGER" | "INT" => matches!(v, Value::Int(_)),
332        "FLOAT" => matches!(v, Value::Float(_) | Value::Int(_)),
333        "NUMBER" => matches!(v, Value::Int(_) | Value::Float(_)),
334        "BOOLEAN" | "BOOL" => matches!(v, Value::Bool(_)),
335        "MAP" => matches!(v, Value::Map(_)),
336        "NODE" => matches!(v, Value::Node(_)),
337        "RELATIONSHIP" | "REL" => matches!(v, Value::Relationship(_)),
338        "PATH" => matches!(v, Value::Path(_)),
339        "BYTES" => matches!(v, Value::Bytes(_)),
340        "DATE" | "DATETIME" | "LOCAL DATETIME" | "LOCALDATETIME" | "TIME" | "LOCAL TIME"
341        | "LOCALTIME" | "DURATION" => matches!(v, Value::Temporal(_)),
342        "POINT" => matches!(v, Value::Point(_)),
343        "UUID" => matches!(v, Value::Uuid(_)),
344        "VECTOR" => matches!(v, Value::Vector { .. }),
345        _ => false,
346    }
347}
348
349/// Whether `name` names one of the `db.ontology.*` procedures (ADR-0121 as
350/// amended by ADR-0227). Derived from the one table so the facade's
351/// compile-time gates (no-mixed-writes, transaction-mixing, target
352/// namespace) and the executor's `CALL` dispatch cannot drift apart.
353pub fn is_ontology_procedure(name: &str) -> bool {
354    builtin_procedure_signature(name)
355        .is_some_and(|signature| signature.name.starts_with("db.ontology."))
356}
357
358/// Whether `name` names a `db.ontology.*` write procedure (`set`, `drop`,
359/// `apply` — ADR-0121 as amended by ADR-0227): registered with the
360/// prefix AND flagged `writes`, both read from the one table.
361pub fn is_ontology_write_procedure(name: &str) -> bool {
362    builtin_procedure_signature(name)
363        .is_some_and(|signature| signature.writes && signature.name.starts_with("db.ontology."))
364}
365
366/// Whether `name` names a store-level ontology op (`db.ontology.set` /
367/// `db.ontology.drop`, ADR-0120 §3) as opposed to the in-overlay `apply`
368/// write or the `get` read. Derived from the one table the way
369/// [`is_ontology_write_procedure`] is: the procedure's signature is flagged
370/// [`ProcSignature::store_level`].
371pub fn is_ontology_store_op(name: &str) -> bool {
372    builtin_procedure_signature(name).is_some_and(|signature| signature.store_level)
373}
374
375/// Whether `CALL name` **could** write — the namespace gate's question: a
376/// store-registered procedure or a built-in flagged `writes` in the
377/// canonical signature registry (ADR-0116 §4). The gate must never admit a
378/// callable to a read view, so registration alone counts.
379///
380/// Its consumer is the facade's namespace write gate (`relate::gate`,
381/// which injects this as the `is_write_procedure` closure the planner's
382/// `is_write` and `plan` take — the planner cannot depend on this registry).
383/// The ADR-0402 effect asks the narrower question, `call_writes_store`.
384pub fn call_is_write(graph: &crate::graph::Graph, name: &str) -> bool {
385    graph.has_procedure(name)
386        || builtin_procedure_signature(name).is_some_and(|signature| signature.writes)
387}
388
389/// Whether `CALL name` writes the store — the ADR-0402 effect question. Only
390/// a writes-flagged built-in does; a store-registered procedure
391/// ([`crate::graph::Procedure`]) is a static row table and cannot mutate the
392/// store, so calling it is no write attempt. [`mutates_store`] applies it
393/// clause by clause, so [`plan_mutates_store`] is the one exported form.
394pub(crate) fn call_writes_store(name: &str) -> bool {
395    builtin_procedure_signature(name).is_some_and(|signature| signature.writes)
396}
397
398/// The replacement when `name` resolves to a deprecated built-in procedure,
399/// `None` otherwise; the procedure-side twin of
400/// [`crate::function_registry::builtin_function_deprecation`] and the one
401/// lookup the query-notification detector reads. The registry's
402/// `deprecated_by` field is the whole deprecation fact — `None` means not
403/// deprecated — so the lookup is a field read, never a bridge between two
404/// flags.
405pub fn builtin_procedure_deprecation(name: &str) -> Option<DeprecatedBy> {
406    builtin_procedure_signature(name)?.deprecated_by
407}
408
409#[cfg(test)]
410mod tests {
411    use super::*;
412
413    /// The lookup reads the one registry: a deprecated entry yields its
414    /// replacement (display text and syntactic form), a current entry and an
415    /// unknown name yield `None`.
416    #[test]
417    fn procedure_deprecation_lookup_reads_the_registry() {
418        assert_eq!(
419            builtin_procedure_deprecation("db.index.vector.queryNodes"),
420            Some(DeprecatedBy::clause("SEARCH"))
421        );
422        assert_eq!(builtin_procedure_deprecation("db.labels"), None);
423        assert_eq!(builtin_procedure_deprecation("no.such.procedure"), None);
424    }
425
426    /// ADR-0463 round 6: the list spelling is exactly `LIST` or `LIST<…>`;
427    /// a bare prefix match would silently accept `LISTS`/`LISTING` as any
428    /// list, re-opening the fail-closed vocabulary.
429    #[test]
430    fn list_type_accepts_only_list_or_list_generic() {
431        let list = Value::List(Vec::new().into());
432        assert!(value_matches_proc_type(&list, "LIST"));
433        assert!(value_matches_proc_type(&list, "LIST<FLOAT>"));
434        assert!(value_matches_proc_type(&list, "list<string>"));
435        assert!(!value_matches_proc_type(&list, "LISTS"));
436        assert!(!value_matches_proc_type(&list, "LISTING"));
437        assert!(!value_matches_proc_type(&Value::Int(1), "LISTS"));
438    }
439
440    #[test]
441    fn every_listed_procedure_has_a_signature() {
442        // The catalog placeholder path is gone: every `SHOW PROCEDURES`
443        // entry renders from this one table.
444        let listed = BUILTIN_PROCEDURE_SIGNATURES
445            .iter()
446            .filter(|s| s.listed)
447            .count();
448        assert!(listed >= 27, "expected the full listed set, got {listed}");
449    }
450
451    #[test]
452    fn vector_query_argument_is_list_of_float() {
453        for name in [
454            "db.index.vector.queryNodes",
455            "db.index.vector.queryRelationships",
456        ] {
457            let sig = builtin_procedure_signature(name).unwrap();
458            assert!(sig.executable);
459            assert_eq!(sig.args[2].name, "query");
460            assert_eq!(sig.args[2].type_str, "LIST<FLOAT>");
461        }
462    }
463
464    /// The description marker every compat-callables signature row and
465    /// front-table entry carries — the shared text the drift guard pins
466    /// both ways: table entries must have matching rows (the forward
467    /// walk), and a row carrying the marker without a table entry is an
468    /// engine-side compat row the front no longer rewrites.
469    const COMPAT_MARKER: &str = "Compatibility (ADR-0699)";
470
471    /// ADR-0699 drift guard, both directions: every compat-callables
472    /// table entry (`relate_front::compat_callables`) carries a matching
473    /// signature row here — executable, listed, no shadowing producer,
474    /// same parameters (names, types, default values), same yield
475    /// columns, same description — and every row carrying the
476    /// compatibility marker belongs to a table entry. Engine
477    /// classification (`writes`, `executable`, `listed`) lives in this
478    /// table alone; membership and bodies in the front table — this test
479    /// is the pin between them.
480    #[test]
481    fn compat_rows_match_the_front_callables_table() {
482        for entry in relate_front::compat_callables::COMPAT_CALLABLES {
483            // Procedure-kind entries pin against this table's rows;
484            // Function-kind entries (independent namespaces, ADR-0382)
485            // pin the inverse — no procedure row may carry their name
486            // until a function-signature home exists for them.
487            if entry.kind == relate_parser::LocalCallableKind::Function {
488                assert!(
489                    builtin_procedure_signature(entry.name).is_none(),
490                    "compat callable {} is Function-kind but has a procedure signature row; \
491                     it needs a function-signature home, not this table's",
492                    entry.name
493                );
494                continue;
495            }
496            let signature = builtin_procedure_signature(entry.name)
497                .unwrap_or_else(|| panic!("compat callable {} has no signature row", entry.name));
498            assert!(signature.executable, "{}", entry.name);
499            assert!(signature.listed, "{}", entry.name);
500            assert!(signature.rows.is_none(), "{}", entry.name);
501            // The full per-position parameter shape — name, type, and the
502            // default's VALUE — compared on both sides, so neither table
503            // can drift a parameter (or a default's text) without the
504            // other failing here.
505            let expected: Vec<(&str, &str, Option<&str>)> = entry
506                .params
507                .iter()
508                .map(|param| (param.name, param.ty, param.default))
509                .collect();
510            let declared: Vec<(&str, &str, Option<&str>)> = signature
511                .args
512                .iter()
513                .map(|arg| (arg.name, arg.type_str, arg.default))
514                .collect();
515            assert_eq!(declared, expected, "{}", entry.name);
516            let returns: Vec<&str> = signature.return_columns().collect();
517            assert_eq!(returns, entry.returns, "{}", entry.name);
518            assert_eq!(signature.description, entry.description, "{}", entry.name);
519        }
520        // The converse: an engine row carrying the compatibility marker
521        // whose name the front table no longer rewrites is an orphaned
522        // compat row — executable, listed, advertising a Cypher body
523        // nothing performs.
524        for signature in BUILTIN_PROCEDURE_SIGNATURES {
525            if signature.description.contains(COMPAT_MARKER) {
526                assert!(
527                    relate_front::compat_callables::is_compat_callable(signature.name),
528                    "{} carries the compatibility marker but is not a compat-callables \
529                     table entry",
530                    signature.name
531                );
532            }
533        }
534    }
535
536    #[test]
537    fn lookup_is_case_sensitive() {
538        // CIP-230: built-in procedure names are case-sensitive (unlike
539        // function names) -- only the exact declared casing resolves, so
540        // `CALL DB.LABELS()`/`CALL Db.Labels()` are UnknownProcedure errors.
541        assert!(builtin_procedure_signature("db.labels").is_some());
542        assert!(builtin_procedure_signature("DB.LABELS").is_none());
543        assert!(builtin_procedure_signature("Db.Labels").is_none());
544        assert!(builtin_procedure_signature("no.such.procedure").is_none());
545    }
546
547    #[test]
548    fn required_args_stop_at_first_defaulted_parameter() {
549        let await_indexes = builtin_procedure_signature("db.awaitIndexes").unwrap();
550        assert_eq!(await_indexes.args.len(), 1);
551        assert_eq!(await_indexes.required_args(), 0);
552        let labels = builtin_procedure_signature("db.labels").unwrap();
553        assert_eq!(labels.required_args(), 0);
554        let create_label = builtin_procedure_signature("db.createLabel").unwrap();
555        assert_eq!(create_label.required_args(), 1);
556    }
557
558    /// ADR-0121/ADR-0227: the four ontology procedures — no database
559    /// argument, `get` with the `"yaml"` default on `format`.
560    #[test]
561    fn is_ontology_procedure_matches_exactly_the_four() {
562        for name in [
563            "db.ontology.set",
564            "db.ontology.get",
565            "db.ontology.drop",
566            "db.ontology.apply",
567        ] {
568            assert!(is_ontology_procedure(name), "{name}");
569        }
570        for name in [
571            "db.labels",
572            "db.ontology",
573            "DB.ONTOLOGY.SET",
574            "db.ontology.getx",
575        ] {
576            assert!(!is_ontology_procedure(name), "{name}");
577        }
578    }
579
580    /// The write/store-op predicates derive from the one table: `get` is
581    /// not a write, `apply` is a write but not a store op.
582    #[test]
583    fn ontology_write_and_store_op_predicates_split_the_four() {
584        assert!(is_ontology_write_procedure("db.ontology.set"));
585        assert!(is_ontology_write_procedure("db.ontology.drop"));
586        assert!(is_ontology_write_procedure("db.ontology.apply"));
587        assert!(!is_ontology_write_procedure("db.ontology.get"));
588        assert!(!is_ontology_write_procedure("db.labels"));
589
590        assert!(is_ontology_store_op("db.ontology.set"));
591        assert!(is_ontology_store_op("db.ontology.drop"));
592        assert!(!is_ontology_store_op("db.ontology.apply"));
593        assert!(!is_ontology_store_op("db.ontology.get"));
594        assert!(!is_ontology_store_op("db.createLabel"));
595    }
596
597    #[test]
598    fn ontology_procedures_follow_the_revised_contract() {
599        let set = builtin_procedure_signature("db.ontology.set").unwrap();
600        assert!(set.executable && set.listed && set.writes && set.store_level);
601        assert_eq!(set.mode, "SCHEMA");
602        assert_eq!(
603            set.args
604                .iter()
605                .map(|a| (a.name, a.type_str))
606                .collect::<Vec<_>>(),
607            [("ontology", "STRING")]
608        );
609        assert!(set.returns.is_empty());
610
611        let get = builtin_procedure_signature("db.ontology.get").unwrap();
612        assert!(get.executable && get.listed && !get.writes && !get.store_level);
613        assert_eq!(get.mode, "READ");
614        assert_eq!(get.args.len(), 1);
615        assert_eq!(get.args[0].name, "format");
616        assert_eq!(get.args[0].default, Some("\"yaml\""));
617        assert_eq!(get.required_args(), 0);
618        assert_eq!(
619            get.returns
620                .iter()
621                .map(|r| (r.name, r.type_str))
622                .collect::<Vec<_>>(),
623            [("ontology", "STRING")]
624        );
625
626        let drop = builtin_procedure_signature("db.ontology.drop").unwrap();
627        assert!(drop.executable && drop.listed && drop.writes && drop.store_level);
628        assert_eq!(drop.mode, "SCHEMA");
629        assert!(drop.args.is_empty() && drop.returns.is_empty());
630
631        // The one row-producing write of the family (ADR-0667): `apply`
632        // writes and answers its delta row, so it is neither void nor a
633        // store op.
634        let apply = builtin_procedure_signature("db.ontology.apply").unwrap();
635        assert!(apply.executable && apply.listed && apply.writes && !apply.store_level);
636        assert_eq!(apply.mode, "SCHEMA");
637        assert!(apply.args.is_empty());
638        assert_eq!(
639            apply
640                .returns
641                .iter()
642                .map(|r| (r.name, r.type_str))
643                .collect::<Vec<_>>(),
644            [
645                ("ontology", "STRING"),
646                ("constraintsCreated", "INTEGER"),
647                ("constraintsDropped", "INTEGER"),
648                ("skipped", "LIST<STRING>"),
649            ]
650        );
651    }
652
653    #[test]
654    fn writes_flag_marks_exactly_the_graph_or_catalog_mutating_builtins() {
655        // ADR-0116 §4: this set is the single source of truth for the
656        // write-procedure classification the `system_ontologies` read-only
657        // check reads — a name added to or dropped from the table must flip
658        // here, not in a second list.
659        let writes: Vec<&str> = BUILTIN_PROCEDURE_SIGNATURES
660            .iter()
661            .filter(|s| s.writes)
662            .map(|s| s.name)
663            .collect();
664        assert_eq!(
665            writes,
666            [
667                "apoc.create.addLabels",
668                "apoc.merge.relationship",
669                "db.create.setNodeVectorProperty",
670                "db.create.setRelationshipVectorProperty",
671                "db.createLabel",
672                "db.ontology.apply",
673                "db.ontology.drop",
674                "db.ontology.set"
675            ]
676        );
677    }
678
679    /// The corpus's `SHOW PROCEDURES` inventory, row by row (ADR-0497 §6):
680    /// every listed row carries the metadata the catalog renders, and the two
681    /// procedures the corpus has no row for are gone — `SHOW INDEXES` and
682    /// `SHOW CONSTRAINTS` are those surfaces.
683    #[test]
684    fn listed_rows_carry_catalog_metadata_and_the_removed_procedures_are_absent() {
685        for signature in BUILTIN_PROCEDURE_SIGNATURES
686            .iter()
687            .filter(|signature| signature.listed)
688        {
689            assert!(
690                !signature.description.is_empty(),
691                "{} is listed without a description",
692                signature.name
693            );
694            assert!(
695                !signature.mode.is_empty(),
696                "{} is listed without a mode",
697                signature.name
698            );
699        }
700        for removed in ["db.indexes", "db.constraints"] {
701            assert!(
702                builtin_procedure_signature(removed).is_none(),
703                "{removed} must leave the registry"
704            );
705        }
706    }
707
708    /// The policy's `add` rows are all registered with the mode the policy
709    /// states: `db.stats.retrieve` is the one executable addition, the other
710    /// five are listed-only inventory rows.
711    ///
712    /// The server-only families the policy originally added — cluster, routing,
713    /// fleet management, CDC, sessions/connections/locks/pools/JMX/security/
714    /// scheduler, usage statistics, server config, and the vector-property
715    /// setters — are gone: Relate is a single-process embedded engine, so those
716    /// rows advertised capabilities it cannot have (ADR-0557).
717    #[test]
718    fn added_procedures_are_registered_with_the_policys_mode() {
719        let adds = [
720            "db.clearQueryCaches",
721            "db.createProperty",
722            "db.createRelationshipType",
723            "db.listLocks",
724            "db.prepareForReplanning",
725        ];
726        for name in adds {
727            let signature =
728                builtin_procedure_signature(name).unwrap_or_else(|| panic!("{name} missing"));
729            assert!(signature.listed, "{name} must be listed");
730            assert!(!signature.executable, "{name} is catalog-only");
731            assert!(!signature.description.is_empty(), "{name}");
732        }
733        let retrieve = builtin_procedure_signature("db.stats.retrieve").expect("registered");
734        assert!(retrieve.listed && retrieve.executable);
735        assert_eq!(retrieve.mode, "READ");
736        assert_eq!(
737            retrieve
738                .returns
739                .iter()
740                .map(|ret| (ret.name, ret.type_str))
741                .collect::<Vec<_>>(),
742            [("section", "STRING"), ("data", "MAP")]
743        );
744    }
745
746    /// ADR-0143: the Browser/Desktop-compat `dbms.*` procedures stay callable
747    /// with the exact pinned return columns; ADR-0497 §6 makes every one of
748    /// them but `dbms.clientConfig` and `dbms.licenseAgreementDetails` a
749    /// listed `SHOW PROCEDURES` row, because the corpus inventories them.
750    #[test]
751    fn adr0143_procedures_keep_their_pinned_columns_and_corpus_listing() {
752        let show_current_user =
753            builtin_procedure_signature("dbms.showCurrentUser").expect("registered");
754        assert!(show_current_user.executable);
755        assert!(show_current_user.listed);
756        assert!(show_current_user.args.is_empty());
757        assert_eq!(
758            show_current_user
759                .returns
760                .iter()
761                .map(|r| (r.name, r.type_str))
762                .collect::<Vec<_>>(),
763            [
764                ("username", "STRING"),
765                ("roles", "LIST<STRING>"),
766                ("flags", "LIST<STRING>")
767            ]
768        );
769
770        // dbms.clientConfig and dbms.listConfig deliberately share one
771        // return-column list: same names, same types, same order, no args.
772        let client_config = builtin_procedure_signature("dbms.clientConfig").expect("registered");
773        let list_config = builtin_procedure_signature("dbms.listConfig").expect("registered");
774        assert!(client_config.executable && !client_config.listed);
775        assert!(list_config.executable && list_config.listed);
776        assert!(client_config.args.is_empty() && list_config.args.is_empty());
777        assert!(std::ptr::eq(client_config.returns, list_config.returns));
778        assert_eq!(
779            client_config
780                .returns
781                .iter()
782                .map(|r| (r.name, r.type_str))
783                .collect::<Vec<_>>(),
784            [
785                ("name", "STRING"),
786                ("description", "STRING"),
787                ("value", "STRING"),
788                ("dynamic", "BOOLEAN"),
789                ("defaultValue", "STRING"),
790                ("startupValue", "STRING"),
791                ("explicitlySet", "BOOLEAN"),
792                ("validValues", "STRING")
793            ]
794        );
795
796        let license =
797            builtin_procedure_signature("dbms.licenseAgreementDetails").expect("registered");
798        assert!(license.executable);
799        assert!(!license.listed);
800        assert!(license.args.is_empty());
801        assert_eq!(
802            license
803                .returns
804                .iter()
805                .map(|r| (r.name, r.type_str))
806                .collect::<Vec<_>>(),
807            [
808                ("status", "STRING"),
809                ("daysLeftOnTrial", "INTEGER"),
810                ("totalTrialDays", "INTEGER")
811            ]
812        );
813    }
814}