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