relate-executor 1.5.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
//! Rows for the `dbms.*` compatibility family plus `db.info`
//! (ADR-0142, ADR-0143): one row per identity, component or
//! configuration fact a Neo4j client tool reads at connect, plus
//! `dbms.listCapabilities` (ADR-0561) with ADR-0741's preview-gated
//! ontology row. The family's shape is one constant row or a small
//! constant table; the graph-derived producers read only the statement's
//! namespace, the store's preview set, and (the capability rows) its
//! pattern-engine switch.

use std::collections::BTreeMap;

use relate_core::Value;

use crate::exec::catalog::principal_cell;
use crate::overlay::ExecGraph;

/// Relate engine version, single-sourced from the workspace version
/// (`version.workspace = true`), reported by `dbms.components` row 3
/// (`Relate`) (ADR-0142).
const RELATE_VERSION: &str = env!("CARGO_PKG_VERSION");

/// Version reported by the `dbms.components` row 1 (`Neo4j Kernel`)
/// (ADR-0152): a deliberately-bumped **policy constant**, not derived from
/// the workspace version. It tracks the Neo4j calver month the Browser
/// compat surface was verified against and carries the `-relate`
/// product suffix (Aura's `5.27-aura` convention) so it stays
/// distinguishable from any real Neo4j release. Bump it deliberately, with
/// a re-check of the browser.neo4j.io bundle gates โ€” the sdk minimum-version
/// gate (`>= 4.4.0`, coerced loose semver) reads only this row's
/// `versions[0]` and throws on anything lower, blocking the Database
/// information sidebar (LABS-150). Must always be non-empty.
const NEO4J_KERNEL_VERSION: &str = "2026.10-relate";

/// Row for `db.info`: the database the statement targets is the graph's
/// namespace (ADR-0116 ยง7).
pub(super) fn db_info_rows(graph: &ExecGraph<'_>) -> Vec<BTreeMap<String, Value>> {
    let namespace = graph.namespace().as_str();
    vec![BTreeMap::from([
        ("id".into(), Value::String(namespace.into())),
        ("name".into(), Value::String(namespace.into())),
        ("creationDate".into(), Value::Null),
    ])]
}

/// Row for `dbms.info` (ADR-0142: Desktop-compat procedure,
/// `updateDBMSInfo`). The procedure arm only sees the graph, not the
/// session's current database, and Relate is a single embedded
/// database โ€” so `name` is the constant `'system'` (the always-present
/// namespace, ADR-0116) standing in for "the current database name".
/// `creationDate` is a documented placeholder: the engine tracks no
/// creation time.
pub(super) fn dbms_info_rows() -> Vec<BTreeMap<String, Value>> {
    vec![BTreeMap::from([
        ("id".into(), Value::String("relate".into())),
        ("name".into(), Value::String("system".into())),
        (
            "creationDate".into(),
            Value::String("1970-01-01T00:00:00Z".into()),
        ),
    ])]
}

/// Row for `dbms.showCurrentUser` (ADR-0143: Browser/Desktop-compat
/// procedure, LABS-148). Session context beyond the principal is not
/// plumbed, so the other columns are fixed documented placeholders.
/// ADR-0273: `username` is the connection's authenticated principal when
/// the surface set one (Bolt after a validated HELLO), else the documented
/// placeholder `'relate'`; `roles: ['admin']` conveys the engine's
/// actual authorization model (there is none) and `flags: []` is honest
/// (Relate has no user flags).
pub(super) fn dbms_show_current_user_rows(principal: Option<&str>) -> Vec<BTreeMap<String, Value>> {
    vec![BTreeMap::from([
        ("username".into(), principal_cell(principal, "relate")),
        (
            "roles".into(),
            Value::List(vec![Value::String("admin".into())].into()),
        ),
        ("flags".into(), Value::List(Vec::new().into())),
    ])]
}

/// Row for `dbms.licenseAgreementDetails` (ADR-0143): honest constant โ€”
/// Relate is Apache-2.0 (ADR-0055): no license agreement to accept and
/// no trial, so `status: 'yes'` with null off-trial counters.
pub(super) fn dbms_license_agreement_rows() -> Vec<BTreeMap<String, Value>> {
    vec![BTreeMap::from([
        ("status".into(), Value::String("yes".into())),
        ("daysLeftOnTrial".into(), Value::Null),
        ("totalTrialDays".into(), Value::Null),
    ])]
}

/// Rows for `dbms.components` (ADR-0142, ADR-0152): three rows, order
/// load-bearing โ€”
/// row 1 is `Neo4j Kernel` because Neo4j Desktop finds the version row *by
/// name* while the public web Browser reads only the first record's
/// `versions[0]`; row 2 feeds Desktop's `cypherVersions`; row 3 keeps
/// Relate's identification row. Row 1 reports the ADR-0152 policy
/// constant `NEO4J_KERNEL_VERSION`; row 3 reports the honest workspace
/// version. Every row reports edition `community`
/// (Relate has no enterprise tier). Row 2's `["5", "25"]` mirrors
/// Neo4j's own listing shape (a compat row, ADR-0142 โ€” the engine
/// implements 25 only, the fact the `cypher.version` capability row
/// reports from the parser's pin), so it is not derived from the
/// dialect constant.
pub(super) fn dbms_components_rows() -> Vec<BTreeMap<String, Value>> {
    const COMPONENTS: &[(&str, &[&str])] = &[
        ("Neo4j Kernel", &[NEO4J_KERNEL_VERSION]),
        ("Cypher", &["5", "25"]),
        ("Relate", &[RELATE_VERSION]),
    ];
    COMPONENTS
        .iter()
        .map(|(name, versions)| {
            BTreeMap::from([
                ("name".into(), Value::String((*name).into())),
                (
                    "versions".into(),
                    Value::List(
                        versions
                            .iter()
                            .map(|version| Value::String((*version).into()))
                            .collect::<Vec<_>>()
                            .into(),
                    ),
                ),
                ("edition".into(), Value::String("community".into())),
            ])
        })
        .collect()
}

/// Rows for `dbms.clientConfig`/`dbms.listConfig` (ADR-0143): one row per
/// Neo4j 5.x+ default clientConfig allowlist key, in the Browser's lookup
/// order. On every row `dynamic: false`, `defaultValue`/`startupValue`
/// equal `value`, `explicitlySet: false`, `validValues: ''`. All rows are
/// documented placeholders except `server.metrics.prefix` and
/// `client.allow_telemetry`, which are honest (Relate exposes no
/// Neo4j-style metrics namespace, and engine telemetry is opt-in).
pub(super) fn dbms_config_rows() -> Vec<BTreeMap<String, Value>> {
    const CONFIG: &[(&str, &str, &str)] = &[
        (
            "browser.allow_outgoing_connections",
            "true",
            "Whether the Browser may open outgoing connections to other servers.",
        ),
        (
            "browser.credential_timeout",
            "0",
            "Seconds before the Browser discards retained credentials (0 = never).",
        ),
        (
            "browser.post_connect_cmd",
            "",
            "Command the Browser runs after connecting.",
        ),
        (
            "browser.remote_content_hostname_whitelist",
            "*",
            "Hostnames the Browser may load remote content from.",
        ),
        (
            "browser.retain_connection_credentials",
            "false",
            "Whether the Browser retains connection credentials.",
        ),
        (
            "browser.retain_editor_history",
            "true",
            "Whether the Browser retains editor history.",
        ),
        (
            "client.allow_telemetry",
            "false",
            "Whether client telemetry collection is allowed.",
        ),
        (
            "dbms.security.auth_enabled",
            "true",
            "Whether the server requires authentication.",
        ),
        (
            "server.metrics.prefix",
            "relate",
            "Prefix for reported metrics names.",
        ),
    ];
    CONFIG
        .iter()
        .map(|(name, value, description)| {
            BTreeMap::from([
                ("name".into(), Value::String((*name).into())),
                ("description".into(), Value::String((*description).into())),
                ("value".into(), Value::String((*value).into())),
                ("dynamic".into(), Value::Bool(false)),
                ("defaultValue".into(), Value::String((*value).into())),
                ("startupValue".into(), Value::String((*value).into())),
                ("explicitlySet".into(), Value::Bool(false)),
                ("validValues".into(), Value::String("".into())),
            ])
        })
        .collect()
}

/// Rows for `dbms.listCapabilities` (ADR-0561): what this engine can do.
///
/// The always-on name vocabulary is vendor-owned -- Neo4j's rows describe
/// its Graph Engine and its JDBC drivers -- so those are Relate's own
/// facts, each one something the engine can state truthfully rather than
/// a row mirrored from a server it is not. The one mirrored name,
/// `ontology.supported.version`, is Neo4j's own capability entry
/// (ADR-0741): it versions the shared external spec the `db.ontology.*`
/// family already tracks, so ontology tooling reads the same fact from
/// either engine -- and it lists only under the `ontology` opt-in, keeping
/// discovery in step with the gated surface (ADR-0378's
/// invisible-while-off rule).
pub(super) fn dbms_list_capabilities_rows(graph: &ExecGraph<'_>) -> Vec<BTreeMap<String, Value>> {
    fn row(name: &str, description: &str, value: Value) -> BTreeMap<String, Value> {
        BTreeMap::from([
            ("name".to_string(), Value::String(name.into())),
            ("description".to_string(), Value::String(description.into())),
            ("value".to_string(), value),
        ])
    }
    let mut rows = vec![
        row(
            "cypher.version",
            "The Cypher dialect version this engine implements.",
            // The parser's one dialect pin โ€” the same constant the ALTER
            // DATABASE default-language check reads โ€” so a dialect bump
            // moves this row with it. The tests keep the literal `25` as
            // the independent pin.
            Value::String(
                relate_parser::error::SUPPORTED_CYPHER_VERSION
                    .to_string()
                    .into(),
            ),
        ),
        row(
            "fulltext.index",
            "Whether fulltext indexes and their query procedures are available.",
            Value::Bool(true),
        ),
        row(
            "vector.index",
            "Whether vector indexes and their query procedures are available.",
            Value::Bool(true),
        ),
        row(
            "pattern.engine",
            "The pattern-matching engine in force for this database.",
            Value::String(graph.base().pattern_engine().as_str().into()),
        ),
    ];
    // The gated rows render from the one gate table (ADR-0741): a
    // row-content gate, not a call gate โ€” the procedure stays callable
    // with the opt-in off and its always-on rows are unchanged; a gated
    // row is simply absent, like every other surface of its feature.
    // The value is the one pin `db.ontology.set` validates against, so
    // the listing cannot drift from the gate.
    for capability in crate::procedure_gate::GATED_CAPABILITIES {
        if graph.preview().enabled(capability.feature) {
            rows.push(row(
                capability.name,
                capability.description,
                Value::String(capability.value.into()),
            ));
        }
    }
    rows
}

#[cfg(test)]
mod tests {
    use super::super::test_helpers::{capability_names, rows, rows_with_principal, string};
    use super::*;
    use crate::graph::Graph;
    use relate_core::PreviewFeatures;

    /// `dbms.listCapabilities` reports this engine's own facts, not rows
    /// mirrored from a server it is not (ADR-0561). The pattern-engine row
    /// reads the store's configured switch, so a diagnostic store reports
    /// what it is actually running. A default graph carries the closed
    /// preview gate, so this also pins the always-on row set: no
    /// `ontology.supported.version` without the opt-in (ADR-0741; the
    /// opt-in side is the test below).
    #[test]
    fn dbms_list_capabilities_reports_the_engines_own_facts() {
        let rows = rows(&Graph::default(), "dbms.listCapabilities");
        assert_eq!(
            capability_names(&rows),
            [
                "cypher.version",
                "fulltext.index",
                "vector.index",
                "pattern.engine"
            ]
        );
        assert_eq!(rows[0]["value"], Value::String("25".into()));
        assert_eq!(rows[1]["value"], Value::Bool(true));
        assert_eq!(rows[2]["value"], Value::Bool(true));
        assert_eq!(rows[3]["value"], Value::String("auto".into()));
        for row in &rows {
            assert!(!row["description"]
                .as_string()
                .expect("every capability row carries a description")
                .is_empty());
        }
    }

    /// The mirrored ontology row lists only under the opt-in (ADR-0741):
    /// a graph with the `ontology` feature enabled appends
    /// `ontology.supported.version` โ€” fifth, after the four always-on
    /// rows โ€” and its value is the spec pin the `db.ontology.set`
    /// validation reads. The literal here pins the pin: it changes only
    /// with a spec bump (ADR-0487's successor), never on its own.
    #[test]
    fn the_ontology_capability_row_lists_only_under_the_opt_in() {
        let mut enabled = Graph::default();
        enabled.configure_preview(relate_core::PreviewSources {
            env: PreviewFeatures::parse("ontology").unwrap(),
            ..relate_core::PreviewSources::default()
        });
        let rows = rows(&enabled, "dbms.listCapabilities");
        assert_eq!(
            capability_names(&rows),
            [
                "cypher.version",
                "fulltext.index",
                "vector.index",
                "pattern.engine",
                "ontology.supported.version",
            ]
        );
        assert_eq!(rows[4]["value"], Value::String("1.1.0".into()));
        assert!(!rows[4]["description"]
            .as_string()
            .expect("the ontology row carries a description")
            .is_empty());
    }

    #[test]
    fn dbms_components_returns_kernel_cypher_relate_rows_with_edition() {
        // ADR-0142: three rows, order load-bearing โ€” Neo4j Desktop finds the
        // version row by name (`Neo4j Kernel`), the public web Browser reads
        // only the first record's `versions[0]`, so row 1 is both first and
        // named `Neo4j Kernel`.
        let graph = Graph::default();
        let rows = rows(&graph, "dbms.components");

        assert_eq!(rows.len(), 3);
        assert_eq!(rows[0]["name"], string("Neo4j Kernel"));
        assert_eq!(
            rows[0]["versions"],
            Value::List(vec![string(NEO4J_KERNEL_VERSION)].into())
        );
        assert_eq!(rows[0]["edition"], string("community"));
        assert_eq!(rows[1]["name"], string("Cypher"));
        assert_eq!(
            rows[1]["versions"],
            Value::List(vec![string("5"), string("25")].into())
        );
        assert_eq!(rows[1]["edition"], string("community"));
        assert_eq!(rows[2]["name"], string("Relate"));
        assert_eq!(
            rows[2]["versions"],
            Value::List(vec![string(RELATE_VERSION)].into())
        );
        assert_eq!(rows[2]["edition"], string("community"));
    }

    #[test]
    fn db_info_reports_the_graphs_namespace() {
        // Default graph is the `neo4j` namespace.
        let graph = Graph::default();
        let neo4j_rows = rows(&graph, "db.info");
        assert_eq!(neo4j_rows.len(), 1);
        assert_eq!(neo4j_rows[0]["id"], string("neo4j"));
        assert_eq!(neo4j_rows[0]["name"], string("neo4j"));

        // A graph tagged with the system_ontologies namespace reports it
        // (ADR-0116 ยง7; the facade's ADR-0229 gate now rejects every
        // statement routed there before it can reach this, but the
        // graph-level identity rule is unchanged).
        let mut ontologies = Graph::default();
        ontologies.set_namespace(relate_core::Namespace::SystemOntologies);
        let ontologies_rows = rows(&ontologies, "db.info");
        assert_eq!(ontologies_rows.len(), 1);
        assert_eq!(ontologies_rows[0]["id"], string("system_ontologies"));
        assert_eq!(ontologies_rows[0]["name"], string("system_ontologies"));
    }

    #[test]
    fn dbms_info_returns_the_desktop_compat_row() {
        // ADR-0142: one row; `name` is the constant `system` (the procedure
        // arm cannot see the session's current database) and `creationDate`
        // is a documented placeholder.
        let graph = Graph::default();
        let rows = rows(&graph, "dbms.info");

        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0]["id"], string("relate"));
        assert_eq!(rows[0]["name"], string("system"));
        assert_eq!(rows[0]["creationDate"], string("1970-01-01T00:00:00Z"));
    }

    /// The family's one pinned-column table: the registry's executable
    /// `dbms.*` signatures' `YIELD` columns, read through the registry's
    /// one accessor โ€” one assert covers the family's membership both
    /// ways and every column list, so a new family procedure, or a
    /// changed column set on any of them, fails here. Column types, arg
    /// shapes and corpus listing stay pinned per procedure by the
    /// registry's own ADR-0143 contract tests, which is why they are
    /// not restated here; the actual side's filter is the one place the
    /// family's prefix and executability are stated.
    #[test]
    fn dbms_family_signatures_declare_their_outputs() {
        // `dbms.clientConfig` and `dbms.listConfig` deliberately share
        // one return-column list (the registry pins them to one shared
        // static), so the table spells it once.
        const CONFIG: &[&str] = &[
            "name",
            "description",
            "value",
            "dynamic",
            "defaultValue",
            "startupValue",
            "explicitlySet",
            "validValues",
        ];
        let expected: std::collections::BTreeMap<&str, Vec<&str>> = [
            ("dbms.clientConfig", CONFIG),
            ("dbms.components", &["name", "versions", "edition"]),
            ("dbms.info", &["id", "name", "creationDate"]),
            (
                "dbms.licenseAgreementDetails",
                &["status", "daysLeftOnTrial", "totalTrialDays"],
            ),
            ("dbms.listCapabilities", &["name", "description", "value"]),
            ("dbms.listConfig", CONFIG),
            ("dbms.showCurrentUser", &["username", "roles", "flags"]),
        ]
        .into_iter()
        .map(|(name, columns)| (name, columns.to_vec()))
        .collect();
        let actual: std::collections::BTreeMap<&str, Vec<&str>> =
            crate::procedure_registry::BUILTIN_PROCEDURE_SIGNATURES
                .iter()
                .filter(|signature| signature.executable && signature.name.starts_with("dbms."))
                .map(|signature| (signature.name, signature.return_columns().collect()))
                .collect();
        assert_eq!(actual, expected);
    }

    #[test]
    fn dbms_show_current_user_returns_the_placeholder_row_without_a_principal() {
        // ADR-0143/0273: with no connection principal (every non-Bolt
        // surface, and Bolt under `--auth none`), one fixed
        // documented-placeholder row.
        let graph = Graph::default();
        let rows = rows(&graph, "dbms.showCurrentUser");

        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0]["username"], string("relate"));
        assert_eq!(rows[0]["roles"], Value::List(vec![string("admin")].into()));
        assert_eq!(rows[0]["flags"], Value::List(Vec::new().into()));
    }

    #[test]
    fn dbms_show_current_user_reports_the_connection_principal() {
        // ADR-0273: a set principal becomes `username`; roles/flags keep the
        // ADR-0143 values.
        let graph = Graph::default();
        let rows = rows_with_principal(&graph, "dbms.showCurrentUser", Some("alice"));

        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0]["username"], string("alice"));
        assert_eq!(rows[0]["roles"], Value::List(vec![string("admin")].into()));
        assert_eq!(rows[0]["flags"], Value::List(Vec::new().into()));
    }

    #[test]
    fn dbms_config_rows_match_the_adr0143_allowlist() {
        // ADR-0143: nine rows, one per Neo4j 5.x+ allowlist key; identical
        // for dbms.clientConfig and dbms.listConfig.
        let graph = Graph::default();
        let client_rows = rows(&graph, "dbms.clientConfig");
        let list_rows = rows(&graph, "dbms.listConfig");
        assert_eq!(client_rows, list_rows);
        assert_eq!(client_rows.len(), 9);

        let expected: &[(&str, &str)] = &[
            ("browser.allow_outgoing_connections", "true"),
            ("browser.credential_timeout", "0"),
            ("browser.post_connect_cmd", ""),
            ("browser.remote_content_hostname_whitelist", "*"),
            ("browser.retain_connection_credentials", "false"),
            ("browser.retain_editor_history", "true"),
            ("client.allow_telemetry", "false"),
            ("dbms.security.auth_enabled", "true"),
            ("server.metrics.prefix", "relate"),
        ];
        for (row, (name, value)) in client_rows.iter().zip(expected) {
            assert_eq!(row["name"], string(name));
            assert_eq!(row["value"], string(value));
            assert_eq!(row["dynamic"], Value::Bool(false));
            assert_eq!(row["defaultValue"], string(value));
            assert_eq!(row["startupValue"], string(value));
            assert_eq!(row["explicitlySet"], Value::Bool(false));
            assert_eq!(row["validValues"], string(""));
            // Every row carries a non-empty fixed description string.
            assert!(matches!(&row["description"], Value::String(d) if !d.is_empty()));
        }
    }

    #[test]
    fn dbms_license_agreement_details_returns_the_honest_row() {
        // ADR-0143: honest constant โ€” Apache-2.0 (ADR-0055), no agreement
        // to accept and no trial.
        let graph = Graph::default();
        let rows = rows(&graph, "dbms.licenseAgreementDetails");

        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0]["status"], string("yes"));
        assert_eq!(rows[0]["daysLeftOnTrial"], Value::Null);
        assert_eq!(rows[0]["totalTrialDays"], Value::Null);
    }
}