relate-executor 1.3.0

In-memory graph and Cypher physical executor
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
//! Canonical built-in procedure signature registry: the single table of
//! argument/return-column names and types for every procedure the engine
//! executes or lists.
//!
//! Five consumers share this table so they cannot drift apart (e.g. the
//! vector `query` argument typed `ANY` in one place and `LIST<FLOAT>` in
//! another):
//!
//! - `exec::procedure_rows::builtin_procedure_rows` — the executor's `CALL`
//!   dispatch (arg names/types, yield columns, arity, and the rows);
//! - `relate::Database`'s compile-time `validate_calls` (same shapes);
//! - `relate`'s namespace write classification (`writes`, ADR-0116 §4);
//! - `show_catalog::procedure_catalog_rows` — the `SHOW PROCEDURES` catalog
//!   (CIP-84/CIP-113/CIP-157 display, which additionally reads the
//!   description/mode/deprecation fields);
//! - `procedure_gate::procedure_preview_feature` — the preview-feature
//!   mapping of the `db.ontology.*` family (ADR-0378).

use relate_core::Value;

use crate::catalog_meta::{DeprecatedBy, ProcArgMeta};

/// Which row producer a row-declaring executable signature carries: the
/// registry owns the fact, so a signature that declares return columns but
/// names no producer cannot be written without the table saying so, and the
/// producer table cannot drift into a second name-keyed list.
///
/// The variants are listed in the same order as their arms in the `produce`
/// dispatch (`exec::procedure_rows`); keeping the two in step is a
/// readability convention, not an enforced invariant.
///
/// Crate-internal: no reader outside this crate names a producer, matching
/// `args`/`returns`.
#[derive(Clone, Copy, Debug)]
pub(crate) enum RowProducer {
    TxGetMetaData,
    DbmsComponents,
    DbPing,
    DbLabels,
    DbRelationshipTypes,
    DbPropertyKeys,
    DbInfo,
    DbmsInfo,
    DbmsShowCurrentUser,
    DbmsConfig,
    DbmsLicenseAgreementDetails,
    DbmsListCapabilities,
    FulltextAnalyzers,
    DbStatsRetrieve,
    SchemaNodeTypeProperties,
    SchemaRelTypeProperties,
    SchemaVisualization,
}

/// Static signature and catalog metadata of a built-in procedure.
pub struct ProcSignature {
    pub name: &'static str,
    pub description: &'static str,
    pub mode: &'static str,
    pub works_on_system: bool,
    pub admin: bool,
    /// Formal parameters. Required parameters come first; a parameter with
    /// a `default` may be omitted by the caller (CIP-113's
    /// `name = default :: type` rendering). Crate-internal (the parameter
    /// type is); a cross-crate caller reads [`Self::parameters`].
    pub(crate) args: &'static [ProcArgMeta],
    /// Return columns (`YIELD` names/types). Crate-internal; a cross-crate
    /// caller reads [`Self::return_columns`].
    pub(crate) returns: &'static [ProcArgMeta],
    /// The replacement when the procedure is deprecated (CIP-157's
    /// `deprecatedBy`); `None` means not deprecated. One fact, so a bool and
    /// its replacement cannot disagree.
    pub deprecated_by: Option<DeprecatedBy>,
    /// True when `CALL` can actually execute it (as opposed to a
    /// catalog-only entry pinned by CIP-84/CIP-113/CIP-157 scenarios that no
    /// scenario calls).
    pub executable: bool,
    /// True when `SHOW PROCEDURES` lists it.
    pub listed: bool,
    /// The row producer a row-declaring executable signature carries; `None`
    /// for a void signature, a catalog-only entry and a diverted procedure
    /// (whose `CALL` path is a dedicated executor — see `divert_call`). One
    /// fact with the return columns, so a row-declaring signature cannot
    /// answer without a producer.
    pub(crate) rows: Option<RowProducer>,
    /// True when a `CALL` mutates the graph or catalog (ADR-0116 §4) — the
    /// write classification `relate`'s namespace rules read, so there is
    /// one table (`mode` does not encode this: DBMS-mode entries such as
    /// `dbms.components` and `tx.setMetaData` are not graph/catalog writes).
    pub writes: bool,
    /// True when the procedure's commit is a store-level commit of its own
    /// (ADR-0120 §3) — the `db.ontology.set` / `db.ontology.drop` store ops,
    /// which push a store-level redo and require the implicit-only /
    /// no-mixed-writes gates; the in-overlay `db.ontology.apply` write is
    /// not one. The store-op classification reads this table the same way
    /// the write classification reads `writes`.
    pub store_level: bool,
}

impl ProcSignature {
    /// The common entry: a listed, executable read procedure with no
    /// description, catalog flags or deprecation. The builders below name
    /// only what a row changes from it, so the table states each entry's
    /// deviations instead of restating ten fields per row.
    pub(crate) const fn read(name: &'static str) -> Self {
        Self {
            name,
            description: "",
            mode: "READ",
            works_on_system: false,
            admin: false,
            args: &[],
            returns: &[],
            deprecated_by: None,
            executable: true,
            listed: true,
            writes: false,
            store_level: false,
            rows: None,
        }
    }

    /// A listed procedure whose mode is `"DBMS"`. The system-database
    /// capability is a separate fact — the corpus lists `tx.setMetaData` as
    /// DBMS-mode but not system-database-capable (ADR-0497 §6) — so each
    /// entry states [`Self::works_on_system`] itself.
    pub(crate) const fn dbms(name: &'static str) -> Self {
        let mut sig = Self::read(name);
        sig.mode = "DBMS";
        sig
    }

    /// A listed procedure whose mode is `"WRITE"`. The `writes` flag is a
    /// separate fact: a catalog-only entry carries the mode without being
    /// callable, so it can mutate nothing.
    pub(crate) const fn write(name: &'static str) -> Self {
        let mut sig = Self::read(name);
        sig.mode = "WRITE";
        sig
    }

    /// A listed procedure whose mode is `"SCHEMA"`. The [`Self::writes`]
    /// flag is a separate fact, as on [`Self::write`]: a schema-mode
    /// procedure that mutates the store still routes its statements to the
    /// write path through `writes`, while the mode itself is only the
    /// catalog rendering.
    pub(crate) const fn schema(name: &'static str) -> Self {
        let mut sig = Self::read(name);
        sig.mode = "SCHEMA";
        sig
    }

    /// The row producer this signature's rows come from.
    pub(crate) const fn rows(mut self, rows: RowProducer) -> Self {
        self.rows = Some(rows);
        self
    }

    /// The procedure works on the system database.
    pub(crate) const fn works_on_system(mut self) -> Self {
        self.works_on_system = true;
        self
    }

    /// A description for the catalog row.
    pub(crate) const fn described(mut self, description: &'static str) -> Self {
        self.description = description;
        self
    }

    /// The procedure requires admin privileges.
    pub(crate) const fn admin(mut self) -> Self {
        self.admin = true;
        self
    }

    /// A `CALL` mutates the graph or catalog (ADR-0116 §4).
    pub(crate) const fn writes(mut self) -> Self {
        self.writes = true;
        self
    }

    /// The procedure's commit is a store-level commit of its own (ADR-0120 §3).
    pub(crate) const fn store_level(mut self) -> Self {
        self.store_level = true;
        self
    }

    /// The procedure's formal parameters.
    pub(crate) const fn args(mut self, args: &'static [ProcArgMeta]) -> Self {
        self.args = args;
        self
    }

    /// The procedure's return columns.
    pub(crate) const fn returns(mut self, returns: &'static [ProcArgMeta]) -> Self {
        self.returns = returns;
        self
    }

    /// The replacement when the procedure is deprecated (CIP-157).
    pub(crate) const fn deprecated_by(mut self, by: DeprecatedBy) -> Self {
        self.deprecated_by = Some(by);
        self
    }

    /// Whether `CALL` can actually execute it.
    pub(crate) const fn executable(mut self, executable: bool) -> Self {
        self.executable = executable;
        self
    }

    /// Whether `SHOW PROCEDURES` lists it.
    pub(crate) const fn listed(mut self, listed: bool) -> Self {
        self.listed = listed;
        self
    }
}

impl ProcSignature {
    /// Number of leading parameters without a default — the minimum arity a
    /// `CALL` may pass. (`args` lists required parameters first.)
    pub fn required_args(&self) -> usize {
        self.args.iter().take_while(|a| a.default.is_none()).count()
    }

    /// The formal parameters as `(name, declared type)` pairs, required
    /// parameters first — a caller outside this crate's view of `args`
    /// (`ProcArgMeta` is crate-internal). The compile-time `CALL`
    /// validation reads this.
    pub fn parameters(&self) -> impl Iterator<Item = (&'static str, &'static str)> + '_ {
        self.args.iter().map(|arg| (arg.name, arg.type_str))
    }

    /// The `YIELD` column names, in signature order — a caller outside this
    /// crate's view of `returns`.
    pub fn return_columns(&self) -> impl Iterator<Item = &'static str> + '_ {
        self.returns.iter().map(|ret| ret.name)
    }

    /// Whether the procedure produces no rows — a unit procedure such as
    /// `tx.setMetaData`, `db.createLabel` or `db.awaitIndexes` declares no
    /// return columns. The one void fact: the clause engine's terminal-call
    /// check and the row-producer dispatch both read it instead of each
    /// re-deriving it from `returns`.
    pub(crate) fn is_void(&self) -> bool {
        self.returns.is_empty()
    }
}

mod signatures;

pub use signatures::BUILTIN_PROCEDURE_SIGNATURES;

/// Looks up a built-in procedure signature by name, case-sensitively.
/// Casing sensitivity: built-in *function* names are
/// case-insensitive, but built-in *procedure* names are case-sensitive --
/// `CALL DB.LABELS()` is an UnknownProcedure error, only the exact declared
/// casing (`CALL db.labels()`) resolves. The validator must agree.
pub fn builtin_procedure_signature(name: &str) -> Option<&'static ProcSignature> {
    BUILTIN_PROCEDURE_SIGNATURES
        .iter()
        .find(|sig| sig.name == name)
}

/// Whether the procedure behind `name` declares no return columns — the one
/// void-procedure fact, so the `CALL` contract validator and the
/// redundant-`OPTIONAL` notification detector cannot drift.
///
/// `registered` is the caller's own lookup of a user-registered procedure,
/// which shadows the built-in: it answers from its `yield_names`, the
/// built-in from the one signature table. A name that is neither is not a
/// procedure, and is not void.
pub fn is_void_procedure(registered: Option<&crate::graph::Procedure>, name: &str) -> bool {
    if let Some(procedure) = registered {
        return procedure.yield_names.is_empty();
    }
    builtin_procedure_signature(name).is_some_and(ProcSignature::is_void)
}

/// Whether a value satisfies a procedure argument type string (`STRING`,
/// `INTEGER`, `LIST<FLOAT>`, …). `ANY`, an empty type, a nullable `?`
/// suffix, and a null value match everything; the accepted type vocabulary
/// is explicit and fails closed, so an unknown (typo'd or unmodelled) type
/// name matches nothing. The precise element-type check of a list happens
/// in the procedure body itself. The canonical home is here, beside the
/// type strings this registry declares — the facade's compile-time
/// `validate_calls` and the executor's per-row binder read the one
/// spelling, so the two cannot drift.
pub fn value_matches_proc_type(v: &Value, ty: &str) -> bool {
    matches_normalized_type(v, &normalize_proc_type(ty))
}

/// One signature's declared type string in the vocabulary's own form —
/// trimmed, `?`-stripped, uppercased. The binder normalizes its binding's
/// declared types once at construction, so the per-row check never pays
/// this again.
pub(crate) fn normalize_proc_type(ty: &str) -> String {
    ty.trim().trim_end_matches('?').trim().to_ascii_uppercase()
}

/// The vocabulary match over an already-normalized type string (a
/// signature may declare several admissible types — `BOOLEAN|MAP`, the
/// Cypher 25 and legacy forms of one argument — each alternative already
/// normalized with the whole).
pub(crate) fn matches_normalized_type(v: &Value, ty: &str) -> bool {
    if v.is_null() || ty.is_empty() || ty == "ANY" {
        return true;
    }
    if ty.contains('|') {
        // Each alternative trims on its own: a union spelled with spaces
        // (`STRING | INTEGER`) normalizes as a whole, so the split arms
        // can carry leading or trailing blanks.
        return ty
            .split('|')
            .any(|alternative| matches_normalized_type(v, alternative.trim()));
    }
    // The accepted type vocabulary is explicit and fails closed: an unknown
    // (typo'd or unmodelled) name does not silently disable checking.
    // Generic lists (`LIST<FLOAT>`, `LIST<NODE>`, …) share the list check.
    if ty == "LIST" || ty.starts_with("LIST<") {
        return matches!(v, Value::List(_));
    }
    match ty {
        "STRING" => matches!(v, Value::String(_)),
        "INTEGER" | "INT" => matches!(v, Value::Int(_)),
        "FLOAT" => matches!(v, Value::Float(_) | Value::Int(_)),
        "NUMBER" => matches!(v, Value::Int(_) | Value::Float(_)),
        "BOOLEAN" | "BOOL" => matches!(v, Value::Bool(_)),
        "MAP" => matches!(v, Value::Map(_)),
        "NODE" => matches!(v, Value::Node(_)),
        "RELATIONSHIP" | "REL" => matches!(v, Value::Relationship(_)),
        "PATH" => matches!(v, Value::Path(_)),
        "BYTES" => matches!(v, Value::Bytes(_)),
        "DATE" | "DATETIME" | "LOCAL DATETIME" | "LOCALDATETIME" | "TIME" | "LOCAL TIME"
        | "LOCALTIME" | "DURATION" => matches!(v, Value::Temporal(_)),
        "POINT" => matches!(v, Value::Point(_)),
        "UUID" => matches!(v, Value::Uuid(_)),
        "VECTOR" => matches!(v, Value::Vector { .. }),
        _ => false,
    }
}

/// Whether `name` names one of the `db.ontology.*` procedures (ADR-0121 as
/// amended by ADR-0227). Derived from the one table so the facade's
/// compile-time gates (no-mixed-writes, transaction-mixing, target
/// namespace) and the executor's `CALL` dispatch cannot drift apart.
pub fn is_ontology_procedure(name: &str) -> bool {
    builtin_procedure_signature(name)
        .is_some_and(|signature| signature.name.starts_with("db.ontology."))
}

/// Whether `name` names a `db.ontology.*` write procedure (`set`, `drop`,
/// `apply` — ADR-0121 as amended by ADR-0227): registered with the
/// prefix AND flagged `writes`, both read from the one table.
pub fn is_ontology_write_procedure(name: &str) -> bool {
    builtin_procedure_signature(name)
        .is_some_and(|signature| signature.writes && signature.name.starts_with("db.ontology."))
}

/// Whether `name` names a store-level ontology op (`db.ontology.set` /
/// `db.ontology.drop`, ADR-0120 §3) as opposed to the in-overlay `apply`
/// write or the `get` read. Derived from the one table the way
/// [`is_ontology_write_procedure`] is: the procedure's signature is flagged
/// [`ProcSignature::store_level`].
pub fn is_ontology_store_op(name: &str) -> bool {
    builtin_procedure_signature(name).is_some_and(|signature| signature.store_level)
}

/// Whether `CALL name` **could** write — the namespace gate's question: a
/// store-registered procedure or a built-in flagged `writes` in the
/// canonical signature registry (ADR-0116 §4). The gate must never admit a
/// callable to a read view, so registration alone counts.
///
/// Its consumer is the facade's namespace write gate (`relate::gate`,
/// which injects this as the `is_write_procedure` closure the planner's
/// `is_write` and `plan` take — the planner cannot depend on this registry).
/// The ADR-0402 effect asks the narrower question, `call_writes_store`.
pub fn call_is_write(graph: &crate::graph::Graph, name: &str) -> bool {
    graph.has_procedure(name)
        || builtin_procedure_signature(name).is_some_and(|signature| signature.writes)
}

/// Whether `CALL name` writes the store — the ADR-0402 effect question. Only
/// a writes-flagged built-in does; a store-registered procedure
/// ([`crate::graph::Procedure`]) is a static row table and cannot mutate the
/// store, so calling it is no write attempt.
pub(crate) fn call_writes_store(name: &str) -> bool {
    builtin_procedure_signature(name).is_some_and(|signature| signature.writes)
}

/// The replacement when `name` resolves to a deprecated built-in procedure,
/// `None` otherwise; the procedure-side twin of
/// [`crate::function_registry::builtin_function_deprecation`] and the one
/// lookup the query-notification detector reads. The registry's
/// `deprecated_by` field is the whole deprecation fact — `None` means not
/// deprecated — so the lookup is a field read, never a bridge between two
/// flags.
pub fn builtin_procedure_deprecation(name: &str) -> Option<DeprecatedBy> {
    builtin_procedure_signature(name)?.deprecated_by
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The lookup reads the one registry: a deprecated entry yields its
    /// replacement (display text and syntactic form), a current entry and an
    /// unknown name yield `None`.
    #[test]
    fn procedure_deprecation_lookup_reads_the_registry() {
        assert_eq!(
            builtin_procedure_deprecation("db.index.vector.queryNodes"),
            Some(DeprecatedBy::clause("SEARCH"))
        );
        assert_eq!(builtin_procedure_deprecation("db.labels"), None);
        assert_eq!(builtin_procedure_deprecation("no.such.procedure"), None);
    }

    /// ADR-0463 round 6: the list spelling is exactly `LIST` or `LIST<…>`;
    /// a bare prefix match would silently accept `LISTS`/`LISTING` as any
    /// list, re-opening the fail-closed vocabulary.
    #[test]
    fn list_type_accepts_only_list_or_list_generic() {
        let list = Value::List(Vec::new().into());
        assert!(value_matches_proc_type(&list, "LIST"));
        assert!(value_matches_proc_type(&list, "LIST<FLOAT>"));
        assert!(value_matches_proc_type(&list, "list<string>"));
        assert!(!value_matches_proc_type(&list, "LISTS"));
        assert!(!value_matches_proc_type(&list, "LISTING"));
        assert!(!value_matches_proc_type(&Value::Int(1), "LISTS"));
    }

    #[test]
    fn every_listed_procedure_has_a_signature() {
        // The catalog placeholder path is gone: every `SHOW PROCEDURES`
        // entry renders from this one table.
        let listed = BUILTIN_PROCEDURE_SIGNATURES
            .iter()
            .filter(|s| s.listed)
            .count();
        assert!(listed >= 27, "expected the full listed set, got {listed}");
    }

    #[test]
    fn vector_query_argument_is_list_of_float() {
        for name in [
            "db.index.vector.queryNodes",
            "db.index.vector.queryRelationships",
        ] {
            let sig = builtin_procedure_signature(name).unwrap();
            assert!(sig.executable);
            assert_eq!(sig.args[2].name, "query");
            assert_eq!(sig.args[2].type_str, "LIST<FLOAT>");
        }
    }

    #[test]
    fn lookup_is_case_sensitive() {
        // CIP-230: built-in procedure names are case-sensitive (unlike
        // function names) -- only the exact declared casing resolves, so
        // `CALL DB.LABELS()`/`CALL Db.Labels()` are UnknownProcedure errors.
        assert!(builtin_procedure_signature("db.labels").is_some());
        assert!(builtin_procedure_signature("DB.LABELS").is_none());
        assert!(builtin_procedure_signature("Db.Labels").is_none());
        assert!(builtin_procedure_signature("no.such.procedure").is_none());
    }

    #[test]
    fn required_args_stop_at_first_defaulted_parameter() {
        let await_indexes = builtin_procedure_signature("db.awaitIndexes").unwrap();
        assert_eq!(await_indexes.args.len(), 1);
        assert_eq!(await_indexes.required_args(), 0);
        let labels = builtin_procedure_signature("db.labels").unwrap();
        assert_eq!(labels.required_args(), 0);
        let create_label = builtin_procedure_signature("db.createLabel").unwrap();
        assert_eq!(create_label.required_args(), 1);
    }

    /// ADR-0121/ADR-0227: the four ontology procedures — no database
    /// argument, `get` with the `"yaml"` default on `format`.
    #[test]
    fn is_ontology_procedure_matches_exactly_the_four() {
        for name in [
            "db.ontology.set",
            "db.ontology.get",
            "db.ontology.drop",
            "db.ontology.apply",
        ] {
            assert!(is_ontology_procedure(name), "{name}");
        }
        for name in [
            "db.labels",
            "db.ontology",
            "DB.ONTOLOGY.SET",
            "db.ontology.getx",
        ] {
            assert!(!is_ontology_procedure(name), "{name}");
        }
    }

    /// The write/store-op predicates derive from the one table: `get` is
    /// not a write, `apply` is a write but not a store op.
    #[test]
    fn ontology_write_and_store_op_predicates_split_the_four() {
        assert!(is_ontology_write_procedure("db.ontology.set"));
        assert!(is_ontology_write_procedure("db.ontology.drop"));
        assert!(is_ontology_write_procedure("db.ontology.apply"));
        assert!(!is_ontology_write_procedure("db.ontology.get"));
        assert!(!is_ontology_write_procedure("db.labels"));

        assert!(is_ontology_store_op("db.ontology.set"));
        assert!(is_ontology_store_op("db.ontology.drop"));
        assert!(!is_ontology_store_op("db.ontology.apply"));
        assert!(!is_ontology_store_op("db.ontology.get"));
        assert!(!is_ontology_store_op("db.createLabel"));
    }

    #[test]
    fn ontology_procedures_follow_the_revised_contract() {
        let set = builtin_procedure_signature("db.ontology.set").unwrap();
        assert!(set.executable && set.listed && set.writes && set.store_level);
        assert_eq!(set.mode, "SCHEMA");
        assert_eq!(
            set.args
                .iter()
                .map(|a| (a.name, a.type_str))
                .collect::<Vec<_>>(),
            [("ontology", "STRING")]
        );
        assert!(set.returns.is_empty());

        let get = builtin_procedure_signature("db.ontology.get").unwrap();
        assert!(get.executable && get.listed && !get.writes && !get.store_level);
        assert_eq!(get.mode, "READ");
        assert_eq!(get.args.len(), 1);
        assert_eq!(get.args[0].name, "format");
        assert_eq!(get.args[0].default, Some("\"yaml\""));
        assert_eq!(get.required_args(), 0);
        assert_eq!(
            get.returns
                .iter()
                .map(|r| (r.name, r.type_str))
                .collect::<Vec<_>>(),
            [("ontology", "STRING")]
        );

        let drop = builtin_procedure_signature("db.ontology.drop").unwrap();
        assert!(drop.executable && drop.listed && drop.writes && drop.store_level);
        assert_eq!(drop.mode, "SCHEMA");
        assert!(drop.args.is_empty() && drop.returns.is_empty());

        // The one row-producing write of the family (ADR-0667): `apply`
        // writes and answers its delta row, so it is neither void nor a
        // store op.
        let apply = builtin_procedure_signature("db.ontology.apply").unwrap();
        assert!(apply.executable && apply.listed && apply.writes && !apply.store_level);
        assert_eq!(apply.mode, "SCHEMA");
        assert!(apply.args.is_empty());
        assert_eq!(
            apply
                .returns
                .iter()
                .map(|r| (r.name, r.type_str))
                .collect::<Vec<_>>(),
            [
                ("ontology", "STRING"),
                ("constraintsCreated", "INTEGER"),
                ("constraintsDropped", "INTEGER"),
                ("skipped", "LIST<STRING>"),
            ]
        );
    }

    #[test]
    fn writes_flag_marks_exactly_the_graph_or_catalog_mutating_builtins() {
        // ADR-0116 §4: this set is the single source of truth for the
        // write-procedure classification the `system_ontologies` read-only
        // check reads — a name added to or dropped from the table must flip
        // here, not in a second list.
        let writes: Vec<&str> = BUILTIN_PROCEDURE_SIGNATURES
            .iter()
            .filter(|s| s.writes)
            .map(|s| s.name)
            .collect();
        assert_eq!(
            writes,
            [
                "db.createLabel",
                "db.ontology.apply",
                "db.ontology.drop",
                "db.ontology.set"
            ]
        );
    }

    /// The corpus's `SHOW PROCEDURES` inventory, row by row (ADR-0497 §6):
    /// every listed row carries the metadata the catalog renders, and the two
    /// procedures the corpus has no row for are gone — `SHOW INDEXES` and
    /// `SHOW CONSTRAINTS` are those surfaces.
    #[test]
    fn listed_rows_carry_catalog_metadata_and_the_removed_procedures_are_absent() {
        for signature in BUILTIN_PROCEDURE_SIGNATURES
            .iter()
            .filter(|signature| signature.listed)
        {
            assert!(
                !signature.description.is_empty(),
                "{} is listed without a description",
                signature.name
            );
            assert!(
                !signature.mode.is_empty(),
                "{} is listed without a mode",
                signature.name
            );
        }
        for removed in ["db.indexes", "db.constraints"] {
            assert!(
                builtin_procedure_signature(removed).is_none(),
                "{removed} must leave the registry"
            );
        }
    }

    /// The policy's `add` rows are all registered with the mode the policy
    /// states: `db.stats.retrieve` is the one executable addition, the other
    /// five are listed-only inventory rows.
    ///
    /// The server-only families the policy originally added — cluster, routing,
    /// fleet management, CDC, sessions/connections/locks/pools/JMX/security/
    /// scheduler, usage statistics, server config, and the vector-property
    /// setters — are gone: Relate is a single-process embedded engine, so those
    /// rows advertised capabilities it cannot have (ADR-0557).
    #[test]
    fn added_procedures_are_registered_with_the_policys_mode() {
        let adds = [
            "db.clearQueryCaches",
            "db.createProperty",
            "db.createRelationshipType",
            "db.listLocks",
            "db.prepareForReplanning",
        ];
        for name in adds {
            let signature =
                builtin_procedure_signature(name).unwrap_or_else(|| panic!("{name} missing"));
            assert!(signature.listed, "{name} must be listed");
            assert!(!signature.executable, "{name} is catalog-only");
            assert!(!signature.description.is_empty(), "{name}");
        }
        let retrieve = builtin_procedure_signature("db.stats.retrieve").expect("registered");
        assert!(retrieve.listed && retrieve.executable);
        assert_eq!(retrieve.mode, "READ");
        assert_eq!(
            retrieve
                .returns
                .iter()
                .map(|ret| (ret.name, ret.type_str))
                .collect::<Vec<_>>(),
            [("section", "STRING"), ("data", "MAP")]
        );
    }

    /// ADR-0143: the Browser/Desktop-compat `dbms.*` procedures stay callable
    /// with the exact pinned return columns; ADR-0497 §6 makes every one of
    /// them but `dbms.clientConfig` and `dbms.licenseAgreementDetails` a
    /// listed `SHOW PROCEDURES` row, because the corpus inventories them.
    #[test]
    fn adr0143_procedures_keep_their_pinned_columns_and_corpus_listing() {
        let show_current_user =
            builtin_procedure_signature("dbms.showCurrentUser").expect("registered");
        assert!(show_current_user.executable);
        assert!(show_current_user.listed);
        assert!(show_current_user.args.is_empty());
        assert_eq!(
            show_current_user
                .returns
                .iter()
                .map(|r| (r.name, r.type_str))
                .collect::<Vec<_>>(),
            [
                ("username", "STRING"),
                ("roles", "LIST<STRING>"),
                ("flags", "LIST<STRING>")
            ]
        );

        // dbms.clientConfig and dbms.listConfig deliberately share one
        // return-column list: same names, same types, same order, no args.
        let client_config = builtin_procedure_signature("dbms.clientConfig").expect("registered");
        let list_config = builtin_procedure_signature("dbms.listConfig").expect("registered");
        assert!(client_config.executable && !client_config.listed);
        assert!(list_config.executable && list_config.listed);
        assert!(client_config.args.is_empty() && list_config.args.is_empty());
        assert!(std::ptr::eq(client_config.returns, list_config.returns));
        assert_eq!(
            client_config
                .returns
                .iter()
                .map(|r| (r.name, r.type_str))
                .collect::<Vec<_>>(),
            [
                ("name", "STRING"),
                ("description", "STRING"),
                ("value", "STRING"),
                ("dynamic", "BOOLEAN"),
                ("defaultValue", "STRING"),
                ("startupValue", "STRING"),
                ("explicitlySet", "BOOLEAN"),
                ("validValues", "STRING")
            ]
        );

        let license =
            builtin_procedure_signature("dbms.licenseAgreementDetails").expect("registered");
        assert!(license.executable);
        assert!(!license.listed);
        assert!(license.args.is_empty());
        assert_eq!(
            license
                .returns
                .iter()
                .map(|r| (r.name, r.type_str))
                .collect::<Vec<_>>(),
            [
                ("status", "STRING"),
                ("daysLeftOnTrial", "INTEGER"),
                ("totalTrialDays", "INTEGER")
            ]
        );
    }
}