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