Skip to main content

relate_core/
preview.rs

1//! Preview-feature gating for the Cypher dialect (ADR-0371).
2//!
3//! A preview feature is a Cypher language feature accepted into a CIP but
4//! not yet part of the pinned dialect floor (the openCypher TCK pin).
5//! `RELATE_PREVIEW` is the global opt-in: a comma-separated list of
6//! kebab-case feature names, read once at `Database::open`. Unset or empty
7//! means no preview features; an unknown name fails open with a loud usage
8//! error naming the known names — never a silent ignore.
9//!
10//! Only syntax-extending features gate: a purely additive function name
11//! never needs the opt-in, so it never lands in this registry. Three
12//! gate classes are recorded exceptions. (a) ADR-0378, widened by
13//! ADR-0593: a built-in surface whose contract tracks a non-final
14//! external spec — the `ontology` row gates the `db.ontology.*`
15//! procedure family and, through the namespace registry's one
16//! fixed-namespace → feature mapping, the `system_ontologies`
17//! namespace's visibility. (b) ADR-0497: a
18//! *name admission* gate — a function name an approved CIP adds that no
19//! reference release ships, or one the corpus records as unreachable
20//! (`coll-zip`, `coll-has`, `gql-stddev-aliases`). A name
21//! gate hides a name; it never widens grammar, and its disabled form is the
22//! registry's ordinary unknown-function rejection rather than the authored
23//! error below: a name that must not exist cannot be named in an error
24//! without advertising it. (c) ADR-0593: a fixed namespace's visibility —
25//! the name-gate rule in namespace form, so a hidden database is
26//! indistinguishable from an unknown one at every resolution site: listed
27//! by no catalog, rejected by the site's own unknown-database path, never
28//! the authored error. None of the exceptions is general — additive
29//! function names and surfaces on our own pinned contract still never
30//! gate. Each gated feature checks the gate where it would otherwise be
31//! parsed or dispatched; while disabled a syntax or procedure-family check
32//! fails with [`preview_feature_disabled`]'s authored error.
33//!
34//! The registry macro is the single source: variant, doc, and name are
35//! declared once, and the macro emits every derivation — the enum, the
36//! exhaustive `kebab_name`/`from_kebab_name` matches (coverage is a
37//! compile guarantee), and [`PREVIEW_FEATURE_TABLE`], the registry view
38//! the fail-closed known-names list renders from. A later feature PR adds
39//! its row here and gates its syntax; nothing else names the feature.
40
41use crate::error_kinds::TckErrorClass;
42
43use crate::Error;
44
45/// The `ParseOptions` field a parse-site feature switches on, one variant per
46/// option. The front applies each through one total `match`.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
48pub enum ParseOption {
49    ObfuscatedLiterals,
50    MixedLabelSyntax,
51    CypherAnnotations,
52    PathConstruction,
53}
54
55/// The front's AST detector a detected feature is checked by, one variant per
56/// distinct detector. The front dispatches through one total `match`.
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
58pub enum DetectorKind {
59    HybridSearch,
60    LocalCallables,
61    Float16,
62    PathConstruction,
63    Chronological,
64    /// The graph-type family: the one graph-type walk reports membership.
65    GraphTypeMembership,
66}
67
68/// Where in the pipeline a preview feature's gate is checked, for the
69/// sites whose consumers a test can read. A feature gated somewhere else
70/// (statement validation, run-time evaluation, the executor's graph-type
71/// layer) declares no site.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73pub enum GateSite {
74    /// The lexer or parser decides it, through this parse option.
75    ParseOption(ParseOption),
76    /// The front's AST detector loop rejects the feature's syntax.
77    AstDetector(DetectorKind),
78    /// A function name is admitted or hidden by the function registry.
79    NameAdmission,
80    /// Procedure dispatch gates a built-in procedure family.
81    ProcedureDispatch,
82    /// The namespace registry hides a fixed namespace.
83    Namespace,
84}
85
86/// The one registry: each preview feature's variant, doc comment,
87/// kebab-case `RELATE_PREVIEW` name, and gate sites are declared from this single
88/// list, so a variant cannot exist without its name and vice versa — a
89/// forgotten row is a compile error, not a runtime `expect`. Every other
90/// spelling of a feature name derives from [`PREVIEW_FEATURE_TABLE`].
91macro_rules! preview_feature_registry {
92    ($(($variant:ident, $doc:literal, $name:literal, [$($site:expr),* $(,)?])),* $(,)?) => {
93        /// A gated preview Cypher feature. The table order is the
94        /// registry order; rows are never renumbered, only appended.
95        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
96        pub enum PreviewFeature {
97            $(
98                #[doc = $doc]
99                $variant,
100            )*
101        }
102
103        /// The one registry: each preview feature with its kebab-case
104        /// `RELATE_PREVIEW` name. The table order is the registry
105        /// order; rows are never renumbered, only appended.
106        pub const PREVIEW_FEATURE_TABLE: &[(PreviewFeature, &str)] =
107            &[$((PreviewFeature::$variant, $name)),*];
108
109        /// Every registered feature, registry order — the enumeration
110        /// callers iterate instead of re-spelling the vocabulary.
111        pub const PREVIEW_FEATURES: &[PreviewFeature] = &[$(PreviewFeature::$variant),*];
112
113        /// The registry width bound: the bitset's `u32` holds every
114        /// registered feature — a 33rd row is a compile error, not a
115        /// runtime wrap.
116        const _: () = assert!([$(stringify!($variant)),*].len() <= 32);
117
118        impl PreviewFeature {
119            /// The feature's kebab-case `RELATE_PREVIEW` name. The
120            /// exhaustive match is the compile guarantee the registry
121            /// exists for — coverage cannot drift from the table.
122            pub fn kebab_name(self) -> &'static str {
123                match self {
124                    $(PreviewFeature::$variant => $name,)*
125                }
126            }
127
128            /// The pipeline sites that check this feature's gate.
129            pub fn gate_sites(self) -> &'static [GateSite] {
130                match self {
131                    $(PreviewFeature::$variant => &[$($site),*],)*
132                }
133            }
134
135            /// The feature for a kebab-case `RELATE_PREVIEW` name.
136            /// `None` when `name` is not a registered feature.
137            pub fn from_kebab_name(name: &str) -> Option<Self> {
138                match name {
139                    $($name => Some(PreviewFeature::$variant),)*
140                    _ => None,
141                }
142            }
143        }
144    };
145}
146
147preview_feature_registry! {
148    (HybridSearch, "CIP-278 hybrid search `COMBINE` (reserved; lands later).", "hybrid-search", [GateSite::AstDetector(DetectorKind::HybridSearch)]),
149    (LocalCallables, "CIP-231 local callables: DEFINE PROCEDURE/FUNCTION, ADR-0382.", "local-callables", [GateSite::AstDetector(DetectorKind::LocalCallables)]),
150    (GraphTypeOptProps, "CIP-283 graph-type optional properties (`prop :: ANY` in element types).", "graph-type-opt-props", [GateSite::AstDetector(DetectorKind::GraphTypeMembership)]),
151    (GraphTypeDefaultValues, "CIP-262 graph-type property default values (`DEFAULT ON COMMIT <value expression>`).", "graph-type-default-values", [GateSite::AstDetector(DetectorKind::GraphTypeMembership)]),
152    (GraphTypeImpliedLabels, "CIP-266 graph-type implied labels that identify node element types (inheritance).", "graph-type-implied-labels", [GateSite::AstDetector(DetectorKind::GraphTypeMembership)]),
153    (
154        Ontology,
155        "The ontology feature's whole dialect surface: the `db.ontology.*` procedures \
156         (ADR-0378: the first non-syntax extension of ADR-0371's scope policy — the \
157         family's contract tracks the non-final Ontology Graph Spec and CIP-287) and, \
158         through the namespace registry's mapping, the `system_ontologies` namespace's \
159         visibility (ADR-0593 — the namespace exists to host this feature's stored \
160         document, so its listing advertises the same non-final surface the procedures \
161         do). Row, mapping and gates are removed once the spec and CIP-287 are final.",
162        "ontology",
163        [GateSite::ProcedureDispatch, GateSite::Namespace]
164    ),
165    (
166        ObfuscatedLiterals,
167        "The Neo4j obfuscated literal `******`: parsed to a dummy `false` \
168         for semantic analysis, never executed. Gates at the lexer, the one point the two \
169         behaviors differ: enabled it lexes as a literal, disabled the stream is the ordinary \
170         `*` tokens and the parser's own syntax error -- Neo4j's disabled form is a syntax \
171         error, not ADR-0371's authored preview error, so the gate never reaches the front \
172         detector loop (the registry names no detector site for it).",
173        "obfuscated-literals",
174        [GateSite::ParseOption(ParseOption::ObfuscatedLiterals)]
175    ),
176    (
177        MixedLabelSyntax,
178        "Neo4j's mixed-label-syntax extra semantic feature: legacy \
179         colon-conjunction, GQL label-expression symbols and the `IS` introducer may mix \
180         across the label expressions of one clause (gates at parse, threaded to the parser \
181         as `ParseOptions`; mixing inside ONE label expression stays rejected).",
182        "mixed-label-syntax",
183        [GateSite::ParseOption(ParseOption::MixedLabelSyntax)]
184    ),
185    (
186        Float16CoordinateTypes,
187        "The FLOAT16/BFLOAT16 vector coordinate types (CIP-280, ADR-0464), mirroring \
188         Neo4j's own configuration toggle: the types in a \
189         `VECTOR<…>` type expression and the `vector(<list>, <dim>, <type>)` constructor. \
190         Detected on the parsed AST; the disabled form is ADR-0371's authored error.",
191        "float16-coordinate-types",
192        [GateSite::AstDetector(DetectorKind::Float16)]
193    ),
194    (
195        ChronologicalComparisons,
196        "Cypher 25's four chronological comparison operators \
197         (`a IS [NOT] BEFORE | AFTER | SAME INSTANT | SAME REPRESENTATION b`), mirroring \
198         Neo4j's own toggle. Detected on the \
199         parsed AST; the disabled form is ADR-0371's authored error.",
200        "chronological-comparisons",
201        [GateSite::AstDetector(DetectorKind::Chronological)]
202    ),
203    (
204        CollectionZip,
205        "CIP-274: the `coll.zip` collection function, callable and \
206         `SHOW`-listed only under this opt-in (ADR-0497). A live Neo4j probe \
207         records the name as front-end registered but unreachable \
208         -- no `SHOW FUNCTIONS` row, 42N48 under CYPHER 5 and 25 -- so the default dialect must \
209         not advertise it. Row and gate are deleted when a Neo4j release ships the function.",
210        "coll-zip",
211        [GateSite::NameAdmission]
212    ),
213    (
214        CollectionHas,
215        "CIP-286: the `coll.hasAnyOf`/`coll.hasAllOf`/\
216         `coll.hasNoneOf` collection functions, callable and `SHOW`-listed only under this \
217         opt-in (ADR-0497). One row for the three-name family; deleted when CIP-286 ships.",
218        "coll-has",
219        [GateSite::NameAdmission]
220    ),
221    (
222        CypherAnnotations,
223        "CIP-281 Cypher annotations: clause-level `@name(params)` markers before a \
224         clause, parsed and semantically checked, then discarded (no runtime effect). \
225         Gates at the lexer, the one point the two behaviors differ: enabled, `@` lexes \
226         as the annotation introducer; disabled, it is the ordinary `unexpected \
227         character: @` syntax error. Row and gate are deleted when the CIP ships in a \
228         release.",
229        "cypher-annotations",
230        [GateSite::ParseOption(ParseOption::CypherAnnotations)]
231    ),
232    (
233        GqlStddevAliases,
234        "CIP-245's `stddev_samp`/`stddev_pop` spellings (ADR-0497): the corpus catalogue lists \
235         only the canonical `stdev_samp`/`stdev_pop`, and Neo4j 2026.05 answers 42N48 for the \
236         GQL spellings, so the default dialect advertises and dispatches only the `stdev_*` \
237         rows. The gate keeps the `@doc`-derived 78/78 reachable. Deleted when a release \
238         registers the spellings (or the scenarios are re-pinned).",
239        "gql-stddev-aliases",
240        [GateSite::NameAdmission]
241    ),
242    (
243        GraphTypeShowVariants,
244        "CIP-275 graph-type display variants of SHOW CURRENT GRAPH TYPE: consolidated and flattened.",
245        "graph-type-show-variants",
246        [GateSite::AstDetector(DetectorKind::GraphTypeMembership)]
247    ),
248    (
249        PathConstruction,
250        "The `PATH [n1, r1, n2, ...]` path constructor: builds a path value from an \
251         alternating node, relationship, ... list. Detected at the parse point (the \
252         `PATH` word before `[`); the disabled form is ADR-0371's authored error.",
253        "path-construction",
254        [GateSite::ParseOption(ParseOption::PathConstruction), GateSite::AstDetector(DetectorKind::PathConstruction)]
255    ),
256    (
257        PathConcatenation,
258        "The `p1 || p2` path concatenation: joins two paths that share a boundary \
259         node. Gates the `||` operator over path operands at evaluation; the disabled \
260         form is the existing `||` operand type error, not the authored error.",
261        "path-concatenation",
262        []
263    ),
264}
265
266/// The registered feature names, comma-separated, for the fail-closed
267/// unknown-name error. The table's order, the registry's order.
268fn known_feature_names() -> String {
269    PREVIEW_FEATURE_TABLE
270        .iter()
271        .map(|(_, name)| *name)
272        .collect::<Vec<_>>()
273        .join(", ")
274}
275
276/// The set of preview features enabled by `RELATE_PREVIEW` for one
277/// open store. Empty ([`PreviewFeatures::none`]) disables every gated
278/// feature.
279#[derive(Debug, Clone, Copy, PartialEq, Eq)]
280pub struct PreviewFeatures(u32);
281
282/// The fail-closed empty set: the value a store-level service bundle
283/// carries until open installs the resolved `RELATE_PREVIEW` set
284/// (ADR-0371, ADR-0378), so an executor-only `Graph::default()` gates every
285/// preview feature closed.
286impl Default for PreviewFeatures {
287    fn default() -> Self {
288        Self::none()
289    }
290}
291
292impl PreviewFeatures {
293    /// No preview features: every gate fails closed.
294    pub fn none() -> Self {
295        Self(0)
296    }
297
298    /// Parse one `RELATE_PREVIEW` value: a comma-separated list of
299    /// kebab-case feature names, whitespace tolerated around each name.
300    /// An empty or blank value enables nothing. An unknown name (including
301    /// an empty list segment) is a loud usage error naming the known
302    /// names — fail-closed, never silently ignored.
303    pub fn parse(raw: &str) -> Result<Self, Error> {
304        if raw.trim().is_empty() {
305            return Ok(Self::none());
306        }
307        let mut enabled = Self(0);
308        for name in raw.split(',') {
309            let name = name.trim();
310            let feature = PreviewFeature::from_kebab_name(name).ok_or_else(|| {
311                Error::semantic(format!(
312                    "{}: invalid RELATE_PREVIEW value: unknown preview feature \
313                     '{name}' (known features: {})",
314                    TckErrorClass::SemanticError.as_str(),
315                    known_feature_names(),
316                ))
317            })?;
318            // A fieldless variant's discriminant is its registry index.
319            enabled.0 |= 1 << (feature as u32);
320        }
321        Ok(enabled)
322    }
323
324    /// Whether `feature` is enabled for this store — the typed gate
325    /// predicate a gated feature checks where it would otherwise be parsed
326    /// or dispatched.
327    pub fn enabled(self, feature: PreviewFeature) -> bool {
328        self.0 & (1 << (feature as u32)) != 0
329    }
330
331    /// The set enabling every feature one by one, over an existing value:
332    /// the fixture constructor the gate tests build from the tables that own
333    /// the rows, so a new gated name is added in one place.
334    pub fn with_feature(self, feature: PreviewFeature) -> Self {
335        Self(self.0 | (1 << (feature as u32)))
336    }
337
338    /// The gate check: `Ok(())` when `feature` is enabled, otherwise the
339    /// authored fail-closed error of [`preview_feature_disabled`].
340    pub fn require(self, feature: PreviewFeature) -> Result<(), Error> {
341        if self.enabled(feature) {
342            Ok(())
343        } else {
344            Err(preview_feature_disabled(feature))
345        }
346    }
347}
348
349/// The authored fail-closed gate text for a preview feature invoked while
350/// disabled, already prefixed with its `SemanticError` class — the single
351/// source of the gate message. [`PreviewFeatures::require`] wraps it in an
352/// [`Error`]; layers outside this crate (the executor's graph-type
353/// semantic layer, which fails closed on the same constructs its
354/// statement-admission gate already checked when they only materialize
355/// against stored graph-type state) render it through their own error
356/// type without re-spelling it.
357pub fn preview_feature_disabled_text(feature: PreviewFeature) -> String {
358    let name = feature.kebab_name();
359    format!(
360        "{}: preview feature '{name}' is not enabled: set RELATE_PREVIEW={name}",
361        TckErrorClass::SemanticError.as_str(),
362    )
363}
364
365/// The authored fail-closed gate error for a preview feature invoked while
366/// disabled (the house style of the ADR-0229 §2 authored text): the
367/// engine renders `semantic error: SemanticError: preview feature
368/// '<name>' is not enabled: set RELATE_PREVIEW=<name>`.
369pub(crate) fn preview_feature_disabled(feature: PreviewFeature) -> Error {
370    Error::semantic(preview_feature_disabled_text(feature))
371}
372
373#[cfg(test)]
374mod tests {
375    use super::*;
376
377    #[test]
378    fn registry_names_are_unique_and_round_trip() {
379        // The macro single-sources the variant list and the rows, so
380        // exhaustiveness is a compile guarantee; these pin the rest: no
381        // name spelled twice, and every row's name parses back to its
382        // variant.
383        let mut seen = std::collections::HashSet::new();
384        for (feature, name) in PREVIEW_FEATURE_TABLE {
385            assert_eq!(feature.kebab_name(), *name);
386            assert!(seen.insert(*name), "duplicate name {name}");
387            assert_eq!(PreviewFeature::from_kebab_name(name), Some(*feature));
388        }
389        assert_eq!(PreviewFeature::from_kebab_name("nope"), None);
390    }
391
392    #[test]
393    fn gate_sites_never_repeat_within_a_row() {
394        for feature in PREVIEW_FEATURES {
395            let mut seen = std::collections::HashSet::new();
396            for site in feature.gate_sites() {
397                assert!(
398                    seen.insert(*site),
399                    "{} repeats {site:?}",
400                    feature.kebab_name()
401                );
402            }
403        }
404    }
405
406    #[test]
407    fn parse_empty_and_unset_value_enable_nothing() {
408        assert_eq!(PreviewFeatures::parse("").unwrap(), PreviewFeatures::none());
409        assert_eq!(
410            PreviewFeatures::parse("   ").unwrap(),
411            PreviewFeatures::none()
412        );
413        for feature in PREVIEW_FEATURES {
414            assert!(!PreviewFeatures::none().enabled(*feature));
415        }
416    }
417
418    #[test]
419    fn parse_comma_lists_and_whitespace() {
420        let features =
421            PreviewFeatures::parse(" hybrid-search,graph-type-implied-labels , local-callables ")
422                .unwrap();
423        assert!(features.enabled(PreviewFeature::HybridSearch));
424        assert!(features.enabled(PreviewFeature::GraphTypeImpliedLabels));
425        assert!(features.enabled(PreviewFeature::LocalCallables));
426        assert!(!features.enabled(PreviewFeature::GraphTypeOptProps));
427        assert!(!features.enabled(PreviewFeature::GraphTypeDefaultValues));
428        // A repeated name stays a plain enable, not an error.
429        assert_eq!(
430            PreviewFeatures::parse("hybrid-search, hybrid-search").unwrap(),
431            PreviewFeatures::parse("hybrid-search").unwrap(),
432        );
433    }
434
435    #[test]
436    fn parse_unknown_name_fails_closed_naming_known_names() {
437        let error = PreviewFeatures::parse("hybrid-search,bogus").unwrap_err();
438        assert!(matches!(error, Error::Semantic(_)), "{error}");
439        let display = error.to_string();
440        assert!(
441            display.contains("unknown preview feature 'bogus'"),
442            "{display}"
443        );
444        for (_, name) in PREVIEW_FEATURE_TABLE {
445            assert!(display.contains(name), "{display} misses {name}");
446        }
447        // An empty segment is an unknown name, not a silent skip.
448        let error = PreviewFeatures::parse("hybrid-search,,local-callables").unwrap_err();
449        assert!(
450            error.to_string().contains("unknown preview feature ''"),
451            "{}",
452            error
453        );
454    }
455
456    #[test]
457    fn parse_each_registered_name_enables_exactly_that_feature() {
458        // Table-driven over the one registry: every row's name parses to a
459        // set with exactly that row enabled, so a new row is covered
460        // without a new test. (The `ontology` row is ADR-0378's
461        // procedure-family exception to ADR-0371's syntax-only scope
462        // policy; it needs no special case.)
463        for feature in PREVIEW_FEATURES {
464            let enabled = PreviewFeatures::parse(feature.kebab_name()).unwrap();
465            assert!(enabled.enabled(*feature), "{}", feature.kebab_name());
466            for other in PREVIEW_FEATURES {
467                if other != feature {
468                    assert!(
469                        !enabled.enabled(*other),
470                        "{} also enabled {}",
471                        feature.kebab_name(),
472                        other.kebab_name()
473                    );
474                }
475            }
476        }
477    }
478
479    #[test]
480    fn require_gates_with_the_authored_disabled_error() {
481        let features = PreviewFeatures::parse("local-callables").unwrap();
482        assert!(features.require(PreviewFeature::LocalCallables).is_ok());
483        let error = features.require(PreviewFeature::HybridSearch).unwrap_err();
484        assert_eq!(
485            error.to_string(),
486            "semantic error: SemanticError: preview feature 'hybrid-search' is not enabled: \
487             set RELATE_PREVIEW=hybrid-search"
488        );
489        // The disabled text is stable for every registered feature.
490        for (feature, name) in PREVIEW_FEATURE_TABLE {
491            let error = preview_feature_disabled(*feature);
492            assert!(
493                error.to_string().ends_with(&format!(
494                    "preview feature '{name}' is not enabled: set RELATE_PREVIEW={name}"
495                )),
496                "{}",
497                error
498            );
499        }
500    }
501}