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 crate::catalog_meta::{DeprecatedBy, ProcArgMeta};
20
21/// Which row producer a row-declaring executable signature carries: the
22/// registry owns the fact, so a signature that declares return columns but
23/// names no producer cannot be written without the table saying so, and the
24/// producer table cannot drift into a second name-keyed list.
25///
26/// Crate-internal: no reader outside this crate names a producer, matching
27/// `args`/`returns`.
28#[derive(Clone, Copy, Debug)]
29pub(crate) enum RowProducer {
30    TxGetMetaData,
31    DbmsComponents,
32    DbPing,
33    DbLabels,
34    DbRelationshipTypes,
35    DbPropertyKeys,
36    DbInfo,
37    DbmsInfo,
38    DbmsShowCurrentUser,
39    DbmsConfig,
40    DbmsLicenseAgreementDetails,
41    DbmsListCapabilities,
42    DbStatsRetrieve,
43    SchemaNodeTypeProperties,
44    SchemaRelTypeProperties,
45    SchemaVisualization,
46}
47
48/// Static signature and catalog metadata of a built-in procedure.
49pub struct ProcSignature {
50    pub name: &'static str,
51    pub description: &'static str,
52    pub mode: &'static str,
53    pub works_on_system: bool,
54    pub admin: bool,
55    /// Formal parameters. Required parameters come first; a parameter with
56    /// a `default` may be omitted by the caller (CIP-113's
57    /// `name = default :: type` rendering). Crate-internal (the parameter
58    /// type is); a cross-crate caller reads [`Self::parameters`].
59    pub(crate) args: &'static [ProcArgMeta],
60    /// Return columns (`YIELD` names/types). Crate-internal; a cross-crate
61    /// caller reads [`Self::return_columns`].
62    pub(crate) returns: &'static [ProcArgMeta],
63    /// The replacement when the procedure is deprecated (CIP-157's
64    /// `deprecatedBy`); `None` means not deprecated. One fact, so a bool and
65    /// its replacement cannot disagree.
66    pub deprecated_by: Option<DeprecatedBy>,
67    /// True when `CALL` can actually execute it (as opposed to a
68    /// catalog-only entry pinned by CIP-84/CIP-113/CIP-157 scenarios that no
69    /// scenario calls).
70    pub executable: bool,
71    /// True when `SHOW PROCEDURES` lists it.
72    pub listed: bool,
73    /// The row producer a row-declaring executable signature carries; `None`
74    /// for a void signature, a catalog-only entry and a diverted procedure
75    /// (whose `CALL` path is a dedicated executor — see `divert_call`). One
76    /// fact with the return columns, so a row-declaring signature cannot
77    /// answer without a producer.
78    pub(crate) rows: Option<RowProducer>,
79    /// True when a `CALL` mutates the graph or catalog (ADR-0116 §4) — the
80    /// write classification `relate`'s namespace rules read, so there is
81    /// one table (`mode` does not encode this: DBMS-mode entries such as
82    /// `dbms.components` and `tx.setMetaData` are not graph/catalog writes).
83    pub writes: bool,
84    /// True when the procedure's commit is a store-level commit of its own
85    /// (ADR-0120 §3) — the `db.ontology.set` / `db.ontology.drop` store ops,
86    /// which push a store-level redo and require the implicit-only /
87    /// no-mixed-writes gates; the in-overlay `db.ontology.apply` write is
88    /// not one. The store-op classification reads this table the same way
89    /// the write classification reads `writes`.
90    pub store_level: bool,
91}
92
93impl ProcSignature {
94    /// The common entry: a listed, executable read procedure with no
95    /// description, catalog flags or deprecation. The builders below name
96    /// only what a row changes from it, so the table states each entry's
97    /// deviations instead of restating ten fields per row.
98    pub(crate) const fn read(name: &'static str) -> Self {
99        Self {
100            name,
101            description: "",
102            mode: "READ",
103            works_on_system: false,
104            admin: false,
105            args: &[],
106            returns: &[],
107            deprecated_by: None,
108            executable: true,
109            listed: true,
110            writes: false,
111            store_level: false,
112            rows: None,
113        }
114    }
115
116    /// A listed procedure whose mode is `"DBMS"`. The system-database
117    /// capability is a separate fact — the corpus lists `tx.setMetaData` as
118    /// DBMS-mode but not system-database-capable (ADR-0497 §6) — so each
119    /// entry states [`Self::works_on_system`] itself.
120    pub(crate) const fn dbms(name: &'static str) -> Self {
121        let mut sig = Self::read(name);
122        sig.mode = "DBMS";
123        sig
124    }
125
126    /// A listed procedure whose mode is `"WRITE"`. The `writes` flag is a
127    /// separate fact: a catalog-only entry carries the mode without being
128    /// callable, so it can mutate nothing.
129    pub(crate) const fn write(name: &'static str) -> Self {
130        let mut sig = Self::read(name);
131        sig.mode = "WRITE";
132        sig
133    }
134
135    /// The row producer this signature's rows come from.
136    pub(crate) const fn rows(mut self, rows: RowProducer) -> Self {
137        self.rows = Some(rows);
138        self
139    }
140
141    /// The procedure works on the system database.
142    pub(crate) const fn works_on_system(mut self) -> Self {
143        self.works_on_system = true;
144        self
145    }
146
147    /// A description for the catalog row.
148    pub(crate) const fn described(mut self, description: &'static str) -> Self {
149        self.description = description;
150        self
151    }
152
153    /// The procedure requires admin privileges.
154    pub(crate) const fn admin(mut self) -> Self {
155        self.admin = true;
156        self
157    }
158
159    /// A `CALL` mutates the graph or catalog (ADR-0116 §4).
160    pub(crate) const fn writes(mut self) -> Self {
161        self.writes = true;
162        self
163    }
164
165    /// The procedure's commit is a store-level commit of its own (ADR-0120 §3).
166    pub(crate) const fn store_level(mut self) -> Self {
167        self.store_level = true;
168        self
169    }
170
171    /// The procedure's formal parameters.
172    pub(crate) const fn args(mut self, args: &'static [ProcArgMeta]) -> Self {
173        self.args = args;
174        self
175    }
176
177    /// The procedure's return columns.
178    pub(crate) const fn returns(mut self, returns: &'static [ProcArgMeta]) -> Self {
179        self.returns = returns;
180        self
181    }
182
183    /// The replacement when the procedure is deprecated (CIP-157).
184    pub(crate) const fn deprecated_by(mut self, by: DeprecatedBy) -> Self {
185        self.deprecated_by = Some(by);
186        self
187    }
188
189    /// Whether `CALL` can actually execute it.
190    pub(crate) const fn executable(mut self, executable: bool) -> Self {
191        self.executable = executable;
192        self
193    }
194
195    /// Whether `SHOW PROCEDURES` lists it.
196    pub(crate) const fn listed(mut self, listed: bool) -> Self {
197        self.listed = listed;
198        self
199    }
200}
201
202impl ProcSignature {
203    /// Number of leading parameters without a default — the minimum arity a
204    /// `CALL` may pass. (`args` lists required parameters first.)
205    pub fn required_args(&self) -> usize {
206        self.args.iter().take_while(|a| a.default.is_none()).count()
207    }
208
209    /// The formal parameters as `(name, declared type)` pairs, required
210    /// parameters first — a caller outside this crate's view of `args`
211    /// (`ProcArgMeta` is crate-internal). The compile-time `CALL`
212    /// validation reads this.
213    pub fn parameters(&self) -> impl Iterator<Item = (&'static str, &'static str)> + '_ {
214        self.args.iter().map(|arg| (arg.name, arg.type_str))
215    }
216
217    /// The `YIELD` column names, in signature order — a caller outside this
218    /// crate's view of `returns`.
219    pub fn return_columns(&self) -> impl Iterator<Item = &'static str> + '_ {
220        self.returns.iter().map(|ret| ret.name)
221    }
222
223    /// Whether the procedure produces no rows — a unit procedure such as
224    /// `tx.setMetaData`, `db.createLabel` or `db.awaitIndexes` declares no
225    /// return columns. The one void fact: the clause engine's terminal-call
226    /// check and the row-producer dispatch both read it instead of each
227    /// re-deriving it from `returns`.
228    pub(crate) fn is_void(&self) -> bool {
229        self.returns.is_empty()
230    }
231}
232
233mod signatures;
234
235pub use signatures::BUILTIN_PROCEDURE_SIGNATURES;
236
237/// Looks up a built-in procedure signature by name, case-sensitively.
238/// CIP-230 ("Casing sensitivity"): built-in *function* names are
239/// case-insensitive, but built-in *procedure* names are case-sensitive --
240/// `CALL DB.LABELS()` is an UnknownProcedure error, only the exact declared
241/// casing (`CALL db.labels()`) resolves. The validator must agree.
242pub fn builtin_procedure_signature(name: &str) -> Option<&'static ProcSignature> {
243    BUILTIN_PROCEDURE_SIGNATURES
244        .iter()
245        .find(|sig| sig.name == name)
246}
247
248/// Whether `name` names one of the `db.ontology.*` procedures (ADR-0121 as
249/// amended by ADR-0227). Derived from the one table so the facade's
250/// compile-time gates (implicit-only, no-mixed-writes, target namespace)
251/// and the executor's `CALL` dispatch cannot drift apart.
252pub fn is_ontology_procedure(name: &str) -> bool {
253    builtin_procedure_signature(name)
254        .is_some_and(|signature| signature.name.starts_with("db.ontology."))
255}
256
257/// Whether `name` names a `db.ontology.*` write procedure (`set`, `drop`,
258/// `apply` — ADR-0121 as amended by ADR-0227): registered with the
259/// prefix AND flagged `writes`, both read from the one table.
260pub fn is_ontology_write_procedure(name: &str) -> bool {
261    builtin_procedure_signature(name)
262        .is_some_and(|signature| signature.writes && signature.name.starts_with("db.ontology."))
263}
264
265/// Whether `name` names a store-level ontology op (`db.ontology.set` /
266/// `db.ontology.drop`, ADR-0120 §3) as opposed to the in-overlay `apply`
267/// write or the `get` read. Derived from the one table the way
268/// [`is_ontology_write_procedure`] is: the procedure's signature is flagged
269/// [`ProcSignature::store_level`].
270pub fn is_ontology_store_op(name: &str) -> bool {
271    builtin_procedure_signature(name).is_some_and(|signature| signature.store_level)
272}
273
274/// Whether `CALL name` **could** write — the namespace gate's question: a
275/// store-registered procedure or a built-in flagged `writes` in the
276/// canonical signature registry (ADR-0116 §4). The gate must never admit a
277/// callable to a read view, so registration alone counts.
278///
279/// Its consumer is the facade's namespace write gate (`relate::gate`,
280/// which injects this as the `is_write_procedure` closure the planner's
281/// `is_write` and `plan` take — the planner cannot depend on this registry).
282/// The ADR-0402 effect asks the narrower question, `call_writes_store`.
283pub fn call_is_write(graph: &crate::graph::Graph, name: &str) -> bool {
284    graph.has_procedure(name)
285        || builtin_procedure_signature(name).is_some_and(|signature| signature.writes)
286}
287
288/// Whether `CALL name` writes the store — the ADR-0402 effect question. Only
289/// a writes-flagged built-in does; a store-registered procedure
290/// ([`crate::graph::Procedure`]) is a static row table and cannot mutate the
291/// store, so calling it is no write attempt.
292pub(crate) fn call_writes_store(name: &str) -> bool {
293    builtin_procedure_signature(name).is_some_and(|signature| signature.writes)
294}
295
296/// The replacement when `name` resolves to a deprecated built-in procedure,
297/// `None` otherwise; the procedure-side twin of
298/// [`crate::function_registry::builtin_function_deprecation`] and the one
299/// lookup the query-notification detector reads. The registry's
300/// `deprecated_by` field is the whole deprecation fact — `None` means not
301/// deprecated — so the lookup is a field read, never a bridge between two
302/// flags.
303pub fn builtin_procedure_deprecation(name: &str) -> Option<DeprecatedBy> {
304    builtin_procedure_signature(name)?.deprecated_by
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310
311    /// The lookup reads the one registry: a deprecated entry yields its
312    /// replacement (display text and syntactic form), a current entry and an
313    /// unknown name yield `None`.
314    #[test]
315    fn procedure_deprecation_lookup_reads_the_registry() {
316        assert_eq!(
317            builtin_procedure_deprecation("db.index.vector.queryNodes"),
318            Some(DeprecatedBy::clause("SEARCH"))
319        );
320        assert_eq!(builtin_procedure_deprecation("db.labels"), None);
321        assert_eq!(builtin_procedure_deprecation("no.such.procedure"), None);
322    }
323
324    #[test]
325    fn every_listed_procedure_has_a_signature() {
326        // The catalog placeholder path is gone: every `SHOW PROCEDURES`
327        // entry renders from this one table.
328        let listed = BUILTIN_PROCEDURE_SIGNATURES
329            .iter()
330            .filter(|s| s.listed)
331            .count();
332        assert!(listed >= 27, "expected the full listed set, got {listed}");
333    }
334
335    #[test]
336    fn vector_query_argument_is_list_of_float() {
337        for name in [
338            "db.index.vector.queryNodes",
339            "db.index.vector.queryRelationships",
340        ] {
341            let sig = builtin_procedure_signature(name).unwrap();
342            assert!(sig.executable);
343            assert_eq!(sig.args[2].name, "query");
344            assert_eq!(sig.args[2].type_str, "LIST<FLOAT>");
345        }
346    }
347
348    #[test]
349    fn lookup_is_case_sensitive() {
350        // CIP-230: built-in procedure names are case-sensitive (unlike
351        // function names) -- only the exact declared casing resolves, so
352        // `CALL DB.LABELS()`/`CALL Db.Labels()` are UnknownProcedure errors.
353        assert!(builtin_procedure_signature("db.labels").is_some());
354        assert!(builtin_procedure_signature("DB.LABELS").is_none());
355        assert!(builtin_procedure_signature("Db.Labels").is_none());
356        assert!(builtin_procedure_signature("no.such.procedure").is_none());
357    }
358
359    #[test]
360    fn required_args_stop_at_first_defaulted_parameter() {
361        let await_indexes = builtin_procedure_signature("db.awaitIndexes").unwrap();
362        assert_eq!(await_indexes.args.len(), 1);
363        assert_eq!(await_indexes.required_args(), 0);
364        let labels = builtin_procedure_signature("db.labels").unwrap();
365        assert_eq!(labels.required_args(), 0);
366        let create_label = builtin_procedure_signature("db.createLabel").unwrap();
367        assert_eq!(create_label.required_args(), 1);
368    }
369
370    /// ADR-0121/ADR-0227 (CIP-287): the four ontology procedures — no
371    /// database argument, `get` with the `"yaml"` default on `format`.
372    #[test]
373    fn is_ontology_procedure_matches_exactly_the_four() {
374        for name in [
375            "db.ontology.set",
376            "db.ontology.get",
377            "db.ontology.drop",
378            "db.ontology.apply",
379        ] {
380            assert!(is_ontology_procedure(name), "{name}");
381        }
382        for name in [
383            "db.labels",
384            "db.ontology",
385            "DB.ONTOLOGY.SET",
386            "db.ontology.getx",
387        ] {
388            assert!(!is_ontology_procedure(name), "{name}");
389        }
390    }
391
392    /// The write/store-op predicates derive from the one table: `get` is
393    /// not a write, `apply` is a write but not a store op.
394    #[test]
395    fn ontology_write_and_store_op_predicates_split_the_four() {
396        assert!(is_ontology_write_procedure("db.ontology.set"));
397        assert!(is_ontology_write_procedure("db.ontology.drop"));
398        assert!(is_ontology_write_procedure("db.ontology.apply"));
399        assert!(!is_ontology_write_procedure("db.ontology.get"));
400        assert!(!is_ontology_write_procedure("db.labels"));
401
402        assert!(is_ontology_store_op("db.ontology.set"));
403        assert!(is_ontology_store_op("db.ontology.drop"));
404        assert!(!is_ontology_store_op("db.ontology.apply"));
405        assert!(!is_ontology_store_op("db.ontology.get"));
406        assert!(!is_ontology_store_op("db.createLabel"));
407    }
408
409    #[test]
410    fn ontology_procedures_follow_cip287() {
411        let set = builtin_procedure_signature("db.ontology.set").unwrap();
412        assert!(set.executable && set.listed && set.writes);
413        assert_eq!(set.mode, "WRITE");
414        assert_eq!(
415            set.args
416                .iter()
417                .map(|a| (a.name, a.type_str))
418                .collect::<Vec<_>>(),
419            [("ontology", "STRING")]
420        );
421        assert!(set.returns.is_empty());
422
423        let get = builtin_procedure_signature("db.ontology.get").unwrap();
424        assert!(get.executable && get.listed && !get.writes);
425        assert_eq!(get.mode, "READ");
426        assert_eq!(get.args.len(), 1);
427        assert_eq!(get.args[0].name, "format");
428        assert_eq!(get.args[0].default, Some("\"yaml\""));
429        assert_eq!(get.required_args(), 0);
430        assert_eq!(
431            get.returns
432                .iter()
433                .map(|r| (r.name, r.type_str))
434                .collect::<Vec<_>>(),
435            [("ontology", "STRING")]
436        );
437
438        for (name, mode) in [
439            ("db.ontology.drop", "WRITE"),
440            ("db.ontology.apply", "WRITE"),
441        ] {
442            let sig = builtin_procedure_signature(name).unwrap();
443            assert!(sig.executable && sig.listed && sig.writes, "{name}");
444            assert_eq!(sig.mode, mode, "{name}");
445            assert!(sig.args.is_empty() && sig.returns.is_empty(), "{name}");
446        }
447    }
448
449    #[test]
450    fn writes_flag_marks_exactly_the_graph_or_catalog_mutating_builtins() {
451        // ADR-0116 §4: this set is the single source of truth for the
452        // write-procedure classification the `system_ontologies` read-only
453        // check reads — a name added to or dropped from the table must flip
454        // here, not in a second list.
455        let writes: Vec<&str> = BUILTIN_PROCEDURE_SIGNATURES
456            .iter()
457            .filter(|s| s.writes)
458            .map(|s| s.name)
459            .collect();
460        assert_eq!(
461            writes,
462            [
463                "db.createLabel",
464                "db.ontology.apply",
465                "db.ontology.drop",
466                "db.ontology.set"
467            ]
468        );
469    }
470
471    /// The corpus's `SHOW PROCEDURES` inventory, row by row (ADR-0497 §6):
472    /// every listed row carries the metadata the catalog renders, and the two
473    /// procedures the corpus has no row for are gone — `SHOW INDEXES` and
474    /// `SHOW CONSTRAINTS` are those surfaces.
475    #[test]
476    fn listed_rows_carry_catalog_metadata_and_the_removed_procedures_are_absent() {
477        for signature in BUILTIN_PROCEDURE_SIGNATURES
478            .iter()
479            .filter(|signature| signature.listed)
480        {
481            assert!(
482                !signature.description.is_empty(),
483                "{} is listed without a description",
484                signature.name
485            );
486            assert!(
487                !signature.mode.is_empty(),
488                "{} is listed without a mode",
489                signature.name
490            );
491        }
492        for removed in ["db.indexes", "db.constraints"] {
493            assert!(
494                builtin_procedure_signature(removed).is_none(),
495                "{removed} must leave the registry"
496            );
497        }
498    }
499
500    /// The policy's `add` rows are all registered with the mode the policy
501    /// states: `db.stats.retrieve` is the one executable addition, the other
502    /// five are listed-only inventory rows.
503    ///
504    /// The server-only families the policy originally added — cluster, routing,
505    /// fleet management, CDC, sessions/connections/locks/pools/JMX/security/
506    /// scheduler, usage statistics, server config, and the vector-property
507    /// setters — are gone: Relate is a single-process embedded engine, so those
508    /// rows advertised capabilities it cannot have (ADR-0557).
509    #[test]
510    fn added_procedures_are_registered_with_the_policys_mode() {
511        let adds = [
512            "db.clearQueryCaches",
513            "db.createProperty",
514            "db.createRelationshipType",
515            "db.listLocks",
516            "db.prepareForReplanning",
517        ];
518        for name in adds {
519            let signature =
520                builtin_procedure_signature(name).unwrap_or_else(|| panic!("{name} missing"));
521            assert!(signature.listed, "{name} must be listed");
522            assert!(!signature.executable, "{name} is catalog-only");
523            assert!(!signature.description.is_empty(), "{name}");
524        }
525        let retrieve = builtin_procedure_signature("db.stats.retrieve").expect("registered");
526        assert!(retrieve.listed && retrieve.executable);
527        assert_eq!(retrieve.mode, "READ");
528        assert_eq!(
529            retrieve
530                .returns
531                .iter()
532                .map(|ret| (ret.name, ret.type_str))
533                .collect::<Vec<_>>(),
534            [("section", "STRING"), ("data", "MAP")]
535        );
536    }
537
538    /// ADR-0143: the Browser/Desktop-compat `dbms.*` procedures stay callable
539    /// with the exact pinned return columns; ADR-0497 §6 makes every one of
540    /// them but `dbms.clientConfig` and `dbms.licenseAgreementDetails` a
541    /// listed `SHOW PROCEDURES` row, because the corpus inventories them.
542    #[test]
543    fn adr0143_procedures_keep_their_pinned_columns_and_corpus_listing() {
544        let show_current_user =
545            builtin_procedure_signature("dbms.showCurrentUser").expect("registered");
546        assert!(show_current_user.executable);
547        assert!(show_current_user.listed);
548        assert!(show_current_user.args.is_empty());
549        assert_eq!(
550            show_current_user
551                .returns
552                .iter()
553                .map(|r| (r.name, r.type_str))
554                .collect::<Vec<_>>(),
555            [
556                ("username", "STRING"),
557                ("roles", "LIST<STRING>"),
558                ("flags", "LIST<STRING>")
559            ]
560        );
561
562        // dbms.clientConfig and dbms.listConfig deliberately share one
563        // return-column list: same names, same types, same order, no args.
564        let client_config = builtin_procedure_signature("dbms.clientConfig").expect("registered");
565        let list_config = builtin_procedure_signature("dbms.listConfig").expect("registered");
566        assert!(client_config.executable && !client_config.listed);
567        assert!(list_config.executable && list_config.listed);
568        assert!(client_config.args.is_empty() && list_config.args.is_empty());
569        assert!(std::ptr::eq(client_config.returns, list_config.returns));
570        assert_eq!(
571            client_config
572                .returns
573                .iter()
574                .map(|r| (r.name, r.type_str))
575                .collect::<Vec<_>>(),
576            [
577                ("name", "STRING"),
578                ("description", "STRING"),
579                ("value", "STRING"),
580                ("dynamic", "BOOLEAN"),
581                ("defaultValue", "STRING"),
582                ("startupValue", "STRING"),
583                ("explicitlySet", "BOOLEAN"),
584                ("validValues", "STRING")
585            ]
586        );
587
588        let license =
589            builtin_procedure_signature("dbms.licenseAgreementDetails").expect("registered");
590        assert!(license.executable);
591        assert!(!license.listed);
592        assert!(license.args.is_empty());
593        assert_eq!(
594            license
595                .returns
596                .iter()
597                .map(|r| (r.name, r.type_str))
598                .collect::<Vec<_>>(),
599            [
600                ("status", "STRING"),
601                ("daysLeftOnTrial", "INTEGER"),
602                ("totalTrialDays", "INTEGER")
603            ]
604        );
605    }
606}