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
//! Built-in procedure row producers: the graph-dependent rows behind
//! `builtin_procedure_rows` (`dbms.components`, `dbms.clientConfig`,
//! `db.schema.*`, …). Argument names/types and yield columns come from the
//! single canonical signature registry (`crate::procedure_registry`); only
//! the rows are produced here. The generic `CALL` machinery and the
//! fulltext/vector query executors live in `exec::procedures`.

use std::collections::{BTreeMap, BTreeSet};

use relate_core::{Error, Result, Value};

use crate::graph::Procedure;
use crate::overlay::ExecGraph;
use crate::procedure_registry::ProcSignature;

mod dbms;
mod graph_counts;
mod schema;
mod stats;
#[cfg(test)]
mod test_helpers;

use schema::{schema_node_type_rows, schema_rel_type_rows, schema_visualization_rows};

/// The executable signature of a built-in name, `None` when the registry does
/// not list it as callable (a catalog-only `SHOW PROCEDURES` row). `CALL`
/// resolves a name to it once and reads it for the call's metadata and its
/// void-terminal fact, so no other path re-spells "executable".
pub(crate) fn executable_signature(name: &str) -> Option<&'static ProcSignature> {
    crate::procedure_registry::builtin_procedure_signature(name)
        .filter(|signature| signature.executable)
}

/// The metadata a signature declares — argument names/types and YIELD columns
/// from the canonical registry — as the row-less `Procedure` a `CALL` binds
/// its arguments against; the rows are [`builtin_procedure_rows`]'s business.
pub(crate) fn procedure_metadata(signature: &ProcSignature) -> Procedure {
    Procedure {
        name: signature.name.into(),
        arg_names: signature
            .args
            .iter()
            .map(|arg| arg.name.to_string())
            .collect(),
        arg_types: signature
            .args
            .iter()
            .map(|arg| arg.type_str.to_string())
            .collect(),
        yield_names: signature
            .returns
            .iter()
            .map(|ret| ret.name.to_string())
            .collect(),
        rows: Vec::new(),
    }
}

/// ADR-0699: the one authored backstop error for a compat callable whose
/// `CALL` bypassed the front-end rewrite — read by the call resolution
/// (ahead of its void classification) and this module's row-producer
/// dispatch, so the message cannot drift between the two sites. It lives
/// here, in the lower of the two CALL modules: `exec::procedures`
/// already imports this module's producers, so the constructor must not
/// reach up from it.
pub(crate) fn compat_rewrite_bypassed(name: &str) -> Error {
    Error::internal(format!(
        "compat procedure '{name}' is re-implemented as a Cypher body and is \
         rewritten by the query front-end; a call reaching the executor means \
         the front-end injection was bypassed"
    ))
}

/// The rows of a built-in procedure under one `CALL`'s bound arguments.
/// `signature` is the canonical registry entry the call resolved its name
/// to: argument names/types, yield columns and the void fact all come from
/// it — only the rows are produced here, and they are a function of `graph`
/// and, where the procedure's contract says so, of `args`
/// (`db.schema.visualization` with a null `options` map selects nothing;
/// `db.stats.retrieve` serves the section it is asked for).
/// `principal` is the connection's authenticated principal (ADR-0273): only
/// `dbms.showCurrentUser` reads it; `None` (a surface with no notion of
/// identity, or `--auth none`) yields the documented placeholder.
/// The row producer's own contract errors (a `db.stats.retrieve` section the
/// engine cannot serve) come back as the `Err` arm.
pub(crate) fn builtin_procedure_rows(
    graph: &ExecGraph<'_>,
    signature: &'static ProcSignature,
    principal: Option<&str>,
    args: &BTreeMap<String, Value>,
) -> Result<Vec<BTreeMap<String, Value>>> {
    // A compat callable (ADR-0699) never reaches this dispatch: the
    // front-end rewrites its CALL into a Cypher body before lowering —
    // membership is the front table's one fact, read here by name. A row
    // arriving here means the injection was bypassed, and this guard
    // answers it with an authored error rather than falling through to
    // the no-producer table error below (a void compat call never gets
    // this far: the resolver classifies it `CallResolution::Void` first).
    if relate_front::compat_callables::is_compat_callable(signature.name) {
        return Err(compat_rewrite_bypassed(signature.name));
    }
    // A void procedure — the signature declares no return columns
    // (`tx.setMetaData`, `db.createLabel`, `db.awaitIndexes`) — is a unit
    // operation with no rows.
    if signature.is_void() {
        return Ok(Vec::new());
    }
    // The registry row owns which producer answers it, so a row-declaring
    // signature without one is a table error rather than a silent zero-row
    // answer, and the producer table cannot drift into a second name-keyed
    // list.
    let producer = signature.rows.ok_or_else(|| {
        Error::internal(format!(
            "builtin procedure '{}' declares return columns but has no row producer",
            signature.name
        ))
    })?;
    producer.produce(graph, principal, args)
}

impl crate::procedure_registry::RowProducer {
    /// Produce this row's rows under one `CALL`'s bound arguments.
    fn produce(
        self,
        graph: &ExecGraph<'_>,
        principal: Option<&str>,
        args: &BTreeMap<String, Value>,
    ) -> Result<Vec<BTreeMap<String, Value>>> {
        // Every producer but `db.stats.retrieve` is infallible; that one arm
        // ends in `?` (its own section contract), so the match yields the rows
        // and the single trailing `Ok` wraps them. A per-arm `Ok` would hide
        // which arm is the fallible one.
        let rows = match self {
            Self::TxGetMetaData => tx_get_metadata_rows(),
            Self::DbmsComponents => dbms::dbms_components_rows(),
            Self::DbPing => ping_rows(),
            Self::DbLabels => label_rows(graph),
            Self::DbRelationshipTypes => relationship_type_rows(graph),
            Self::DbPropertyKeys => property_key_rows(graph),
            Self::DbInfo => dbms::db_info_rows(graph),
            Self::DbmsInfo => dbms::dbms_info_rows(),
            Self::DbmsShowCurrentUser => dbms::dbms_show_current_user_rows(principal),
            Self::DbmsConfig => dbms::dbms_config_rows(),
            Self::DbmsLicenseAgreementDetails => dbms::dbms_license_agreement_rows(),
            Self::DbmsListCapabilities => dbms::dbms_list_capabilities_rows(graph),
            Self::FulltextAnalyzers => fulltext_analyzer_rows(),
            Self::DbStatsRetrieve => stats::stats_retrieve_rows(
                graph,
                args.get("section")
                    .expect("db.stats.retrieve binds its required section before its rows")
                    .as_string(),
            )?,
            Self::SchemaNodeTypeProperties => schema_node_type_rows(graph),
            Self::SchemaRelTypeProperties => schema_rel_type_rows(graph),
            Self::SchemaVisualization => schema_visualization_rows(graph, args.get("options")),
        };
        Ok(rows)
    }
}

/// Row for `tx.getMetaData` (CIP-230): the fixed `source: 'cip230'`
/// metadata map.
fn tx_get_metadata_rows() -> Vec<BTreeMap<String, Value>> {
    vec![BTreeMap::from([(
        "metadata".into(),
        Value::Map(BTreeMap::from([("source".into(), Value::String("cip230".into()))]).into()),
    )])]
}

/// Shared producer for the single-column distinct-string procedures
/// (`db.labels`, `db.relationshipTypes`, `db.propertyKeys`): a `BTreeSet`
/// dedupes and sorts in one pass, then each value maps to a one-column row.
fn distinct_string_rows(
    values: impl IntoIterator<Item = String>,
    column: &str,
) -> Vec<BTreeMap<String, Value>> {
    values
        .into_iter()
        .collect::<BTreeSet<_>>()
        .into_iter()
        .map(|value| BTreeMap::from([(column.into(), Value::String(value.into()))]))
        .collect()
}

/// Row for `db.ping` (Neo4j Browser's connectivity probe): reaching this
/// code means the database answered, so the row is a constant `true`.
fn ping_rows() -> Vec<BTreeMap<String, Value>> {
    vec![BTreeMap::from([("success".into(), Value::Bool(true))])]
}

/// Rows for `db.index.fulltext.listAvailableAnalyzers`: one per analyzer the
/// engine admits, from the one analyzer table.
///
/// The catalogue's item type stays unnameable outside `fulltext`: it is
/// deliberately absent from that module's `pub(crate) use` list, so this
/// producer reads each entry by inference through `analyzer_catalog()`
/// instead of naming the type — a second export would be a second path to
/// the same fact (the one-public-path rule).
fn fulltext_analyzer_rows() -> Vec<BTreeMap<String, Value>> {
    crate::exec::fulltext::analyzer_catalog()
        .map(|entry| {
            BTreeMap::from([
                ("analyzer".to_string(), Value::String(entry.name.into())),
                (
                    "description".to_string(),
                    Value::String(entry.description.into()),
                ),
                (
                    "stopwords".to_string(),
                    crate::exec::catalog::string_list(
                        entry.stopwords.iter().map(|word| word.to_string()),
                    ),
                ),
            ])
        })
        .collect()
}

/// Rows for `db.labels`: every distinct stored node label, sorted. Read
/// from the maintained per-label counts when the view sees exactly the
/// latest committed state; any other view walks the nodes.
fn label_rows(graph: &ExecGraph<'_>) -> Vec<BTreeMap<String, Value>> {
    if let Some(names) = graph
        .base()
        .windowed_label_names(|| graph.sees_exact_base_stats())
    {
        return distinct_string_rows(names, "label");
    }
    let labels = graph
        .all_node_ids()
        .into_iter()
        .flat_map(|id| graph.node_labels(id).unwrap_or_default());
    distinct_string_rows(labels, "label")
}

/// Rows for `db.relationshipTypes`: every distinct stored relationship
/// type, sorted. Read from the maintained per-type counts under the same
/// exactness window as [`label_rows`]; any other view walks the
/// relationships.
fn relationship_type_rows(graph: &ExecGraph<'_>) -> Vec<BTreeMap<String, Value>> {
    if let Some(names) = graph
        .base()
        .windowed_rel_type_names(|| graph.sees_exact_base_stats())
    {
        return distinct_string_rows(names, "relationshipType");
    }
    let types = graph
        .all_rel_ids()
        .into_iter()
        .filter_map(|id| graph.rel_type(id));
    distinct_string_rows(types, "relationshipType")
}

/// Rows for `db.propertyKeys`: every distinct property key on stored nodes
/// or relationships, sorted.
fn property_key_rows(graph: &ExecGraph<'_>) -> Vec<BTreeMap<String, Value>> {
    let node_keys = graph
        .all_node_ids()
        .into_iter()
        .flat_map(|id| graph.node_prop_keys(id));
    let rel_keys = graph
        .all_rel_ids()
        .into_iter()
        .flat_map(|id| graph.rel_prop_keys(id));
    distinct_string_rows(node_keys.chain(rel_keys), "propertyKey")
}

#[cfg(test)]
mod tests {
    use super::test_helpers::{rows, string};
    use super::*;
    use crate::graph::Graph;
    /// A void call still binds and type-checks its arguments per driving
    /// row: a wrong-typed argument is `InvalidArgumentType`, never silently
    /// accepted by the unit fast path.
    #[test]
    fn a_void_call_type_checks_its_arguments() {
        let graph = Graph::default();
        for query in [
            "CALL db.awaitIndexes('not-an-int')",
            "CALL tx.setMetaData(1)",
        ] {
            let error = crate::exec::test_support::error_of(
                crate::exec::test_support::try_exec_cypher(&graph, query),
            );
            assert!(error.contains("InvalidArgumentType"), "{query}: {error}");
        }
    }

    /// A NULL section passes the CALL type check (null is admitted for a
    /// required STRING), so the producer must reject it with a typed error —
    /// never a panic, which would unwind the query worker.
    #[test]
    fn a_null_stats_section_is_a_typed_rejection() {
        let graph = Graph::default();
        let error = crate::exec::test_support::error_of(
            crate::exec::test_support::try_exec_cypher(&graph, "CALL db.stats.retrieve(null)"),
        );
        assert!(
            error.contains("InvalidArgumentValue: db.stats.retrieve") && error.contains("NULL"),
            "{error}"
        );
    }

    /// ADR-0497 §6: the two procedures the corpus has no row for are gone —
    /// a call is the ordinary unknown-procedure error, and `SHOW INDEXES` /
    /// `SHOW CONSTRAINTS` are the surfaces.
    #[test]
    fn removed_catalog_procedures_are_unknown() {
        let graph = Graph::default();
        for name in ["db.indexes", "db.constraints"] {
            let error = crate::exec::test_support::error_of(
                crate::exec::test_support::try_exec_cypher(&graph, &format!("CALL {name}()")),
            );
            assert!(error.contains("ProcedureNotFound: "), "{name}: {error}");
        }
    }

    /// The metadata boundary: resolving a call reads the canonical signature
    /// and runs no row producer, so no producer ever sees a synthetic empty
    /// argument binding. The same name still answers its rows through
    /// `builtin_procedure_rows`, under a call's own arguments.
    #[test]
    fn metadata_comes_from_the_signature_without_running_a_producer() {
        fn metadata(name: &str) -> Procedure {
            procedure_metadata(executable_signature(name).expect("a registered builtin"))
        }

        let graph = Graph::default();
        crate::exec::test_support::exec_autocommit(&graph, "CREATE (:User {name: 'a'})")
            .expect("the fixture's CREATE succeeds");

        // `db.labels` answers a row for this graph; its metadata never does.
        let labels = metadata("db.labels");
        assert_eq!(labels.yield_names, ["label"]);
        assert!(labels.rows.is_empty());
        assert_eq!(rows(&graph, "db.labels").len(), 1);

        // `db.stats.retrieve`'s required argument and its yields come from
        // the signature; nothing is produced without the call's section.
        let retrieve = metadata("db.stats.retrieve");
        assert_eq!(retrieve.arg_names, ["section"]);
        assert_eq!(retrieve.arg_types, ["STRING"]);
        assert_eq!(retrieve.yield_names, ["section", "data"]);
        assert!(retrieve.rows.is_empty());

        // A void procedure declares no yields, so it has no row producer.
        let await_indexes = metadata("db.awaitIndexes");
        assert!(await_indexes.yield_names.is_empty() && await_indexes.rows.is_empty());

        // A catalog-only row is listed but not callable: the registry carries
        // it, `executable_signature` refuses it. Both halves are asserted,
        // because `None` alone cannot tell a catalog-only row from a name the
        // registry does not carry at all.
        let catalog_only =
            crate::procedure_registry::builtin_procedure_signature("db.clearQueryCaches")
                .expect("the catalog-only row is registered");
        assert!(catalog_only.listed && !catalog_only.executable);
        assert!(executable_signature("db.clearQueryCaches").is_none());
    }

    /// A row-declaring signature without a producer arm is table/producer
    /// drift, never a zero-row answer. The vector and fulltext query
    /// procedures are the registry's remaining row-declaring entries without
    /// an arm here — `exec_call` diverts them to their own executors — so a
    /// direct call pins the guard.
    #[test]
    fn a_diverted_row_declaring_signature_is_an_internal_error_on_the_generic_path() {
        let graph = Graph::default();
        let view = ExecGraph::read(&graph);
        let signature = executable_signature("db.index.vector.queryNodes")
            .expect("db.index.vector.queryNodes is registered");
        let error = builtin_procedure_rows(&view, signature, None, &BTreeMap::new())
            .expect_err("a diverted procedure has no generic row producer");
        let message = error.to_string();
        assert!(
            message.contains("dedicated executor") || message.contains("no row producer"),
            "{message}"
        );
    }

    /// A terminal void call is a unit statement (CIP-159): the clause engine
    /// reads the void fact from the signature — never by producing the rows
    /// and discarding them — so the terminal `db.awaitIndexes()` result
    /// carries no rows, while a row-declaring terminal call keeps its row.
    #[test]
    fn a_terminal_void_builtin_call_answers_no_rows() {
        let graph = Graph::default();
        let void = crate::exec::test_support::exec_cypher(&graph, "CALL db.awaitIndexes()");
        assert!(void.rows.is_empty());

        let rows_afield = crate::exec::test_support::exec_cypher(&graph, "CALL db.ping()");
        assert_eq!(rows_afield.rows.len(), 1);
    }
    #[test]
    fn db_ping_reports_success() {
        // The connectivity probe answers one constant row; the signature
        // declares the BOOLEAN `success` output.
        let rows = rows(&Graph::default(), "db.ping");
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0]["success"], Value::Bool(true));
        let signature = crate::procedure_registry::builtin_procedure_signature("db.ping")
            .expect("db.ping is registered");
        assert_eq!(signature.returns[0].name, "success");
        assert_eq!(signature.returns[0].type_str, "BOOLEAN");
        assert!(signature.works_on_system);
    }

    /// `db.index.fulltext.listAvailableAnalyzers` answers one row per
    /// admitted analyzer from the one analyzer table: the corpus pins the
    /// swedish description verbatim, and `stopwords` reports what this
    /// engine's analyzer actually filters.
    #[test]
    fn fulltext_list_available_analyzers_answers_the_analyzer_table() {
        let graph = Graph::default();
        let signature = crate::procedure_registry::builtin_procedure_signature(
            "db.index.fulltext.listAvailableAnalyzers",
        )
        .expect("registered");
        assert!(signature.executable && signature.works_on_system);

        let rows = rows(&graph, "db.index.fulltext.listAvailableAnalyzers");
        assert_eq!(rows.len(), 45);
        let swedish = rows
            .iter()
            .find(|row| row["analyzer"] == string("swedish"))
            .expect("swedish is listed");
        assert_eq!(
            swedish["description"],
            string("Swedish analyzer with stemming and stop word filtering.")
        );
        let english = rows
            .iter()
            .find(|row| row["analyzer"] == string("english"))
            .expect("english is listed");
        assert!(matches!(
            &english["stopwords"],
            Value::List(words) if !words.is_empty()
        ));
        // Every other analyzer shares the standard tokenizer, which filters
        // no stop words; the engine applies none, so the row states none.
        let french = rows
            .iter()
            .find(|row| row["analyzer"] == string("french"))
            .expect("french is listed");
        assert_eq!(french["stopwords"], Value::List(Vec::new().into()));

        // The `CALL` path reaches the producer through `YIELD`.
        let result = crate::exec::test_support::exec_cypher(
            &graph,
            "CALL db.index.fulltext.listAvailableAnalyzers() YIELD analyzer \
             WHERE analyzer = 'swedish' RETURN analyzer",
        );
        assert_eq!(result.rows, vec![vec![string("swedish")]]);
    }
}