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 one registry: each preview feature's variant, doc comment, and
46/// kebab-case `RELATE_PREVIEW` name are declared from this single
47/// list, so a variant cannot exist without its name and vice versa — a
48/// forgotten row is a compile error, not a runtime `expect`. Every other
49/// spelling of a feature name derives from [`PREVIEW_FEATURE_TABLE`].
50macro_rules! preview_feature_registry {
51    ($(($variant:ident, $doc:literal, $name:literal)),* $(,)?) => {
52        /// A gated preview Cypher feature. The table order is the
53        /// registry order; rows are never renumbered, only appended.
54        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
55        pub enum PreviewFeature {
56            $(
57                #[doc = $doc]
58                $variant,
59            )*
60        }
61
62        /// The one registry: each preview feature with its kebab-case
63        /// `RELATE_PREVIEW` name. The table order is the registry
64        /// order; rows are never renumbered, only appended.
65        pub const PREVIEW_FEATURE_TABLE: &[(PreviewFeature, &str)] =
66            &[$((PreviewFeature::$variant, $name)),*];
67
68        /// Every registered feature, registry order — the enumeration
69        /// callers iterate instead of re-spelling the vocabulary.
70        pub const PREVIEW_FEATURES: &[PreviewFeature] = &[$(PreviewFeature::$variant),*];
71
72        /// The registry width bound: the bitset's `u32` holds every
73        /// registered feature — a 33rd row is a compile error, not a
74        /// runtime wrap.
75        const _: () = assert!([$(stringify!($variant)),*].len() <= 32);
76
77        impl PreviewFeature {
78            /// The feature's kebab-case `RELATE_PREVIEW` name. The
79            /// exhaustive match is the compile guarantee the registry
80            /// exists for — coverage cannot drift from the table.
81            pub fn kebab_name(self) -> &'static str {
82                match self {
83                    $(PreviewFeature::$variant => $name,)*
84                }
85            }
86
87            /// The feature for a kebab-case `RELATE_PREVIEW` name.
88            /// `None` when `name` is not a registered feature.
89            pub fn from_kebab_name(name: &str) -> Option<Self> {
90                match name {
91                    $($name => Some(PreviewFeature::$variant),)*
92                    _ => None,
93                }
94            }
95        }
96    };
97}
98
99preview_feature_registry! {
100    (HybridSearch, "CIP-278 hybrid search `COMBINE` (reserved; lands later).", "hybrid-search"),
101    (LocalCallables, "CIP-231 local callables: DEFINE PROCEDURE/FUNCTION, ADR-0382.", "local-callables"),
102    (GraphTypeOptProps, "CIP-283 graph-type optional properties (`prop :: ANY` in element types).", "graph-type-opt-props"),
103    (GraphTypeDefaultValues, "CIP-262 graph-type property default values (`DEFAULT ON COMMIT <value expression>`).", "graph-type-default-values"),
104    (GraphTypeImpliedLabels, "CIP-266 graph-type implied labels that identify node element types (inheritance).", "graph-type-implied-labels"),
105    (
106        Ontology,
107        "The ontology feature's whole dialect surface: the `db.ontology.*` procedures \
108         (ADR-0378: the first non-syntax extension of ADR-0371's scope policy — the \
109         family's contract tracks the non-final Ontology Graph Spec and CIP-287) and, \
110         through the namespace registry's mapping, the `system_ontologies` namespace's \
111         visibility (ADR-0593 — the namespace exists to host this feature's stored \
112         document, so its listing advertises the same non-final surface the procedures \
113         do). Row, mapping and gates are removed once the spec and CIP-287 are final.",
114        "ontology"
115    ),
116    (
117        ObfuscatedLiterals,
118        "The Neo4j obfuscated literal `******`: parsed to a dummy `false` \
119         for semantic analysis, never executed. Gates at the lexer, the one point the two \
120         behaviors differ: enabled it lexes as a literal, disabled the stream is the ordinary \
121         `*` tokens and the parser's own syntax error -- Neo4j's disabled form is a syntax \
122         error, not ADR-0371's authored preview error, so the gate never reaches the front \
123         detector loop (its arm returns false).",
124        "obfuscated-literals"
125    ),
126    (
127        MixedLabelSyntax,
128        "Neo4j's mixed-label-syntax extra semantic feature: legacy \
129         colon-conjunction, GQL label-expression symbols and the `IS` introducer may mix \
130         across the label expressions of one clause (gates at parse, threaded to the parser \
131         as `ParseOptions`; mixing inside ONE label expression stays rejected).",
132        "mixed-label-syntax"
133    ),
134    (
135        Float16CoordinateTypes,
136        "The FLOAT16/BFLOAT16 vector coordinate types (CIP-280, ADR-0464), mirroring \
137         Neo4j's own configuration toggle: the types in a \
138         `VECTOR<…>` type expression and the `vector(<list>, <dim>, <type>)` constructor. \
139         Detected on the parsed AST; the disabled form is ADR-0371's authored error.",
140        "float16-coordinate-types"
141    ),
142    (
143        ChronologicalComparisons,
144        "Cypher 25's four chronological comparison operators \
145         (`a IS [NOT] BEFORE | AFTER | SAME INSTANT | SAME REPRESENTATION b`), mirroring \
146         Neo4j's own toggle. Detected on the \
147         parsed AST; the disabled form is ADR-0371's authored error.",
148        "chronological-comparisons"
149    ),
150    (
151        ComplexSearchPatterns,
152        "Neo4j's vector-search complex-pattern mode: \
153         a SEARCH clause's MATCH statement keeps its own pattern shape -- several components, \
154         variable-length hops, quantified and selected paths, several bound variables, \
155         predicates outside the binding -- instead of the floor's single node or \
156         single-hop relationship. Widens the front's SEARCH validation; disabled, every \
157         pattern-shape rejection keeps firing.",
158        "complex-search-patterns"
159    ),
160    (
161        CollectionZip,
162        "CIP-274: the `coll.zip` collection function, callable and \
163         `SHOW`-listed only under this opt-in (ADR-0497). A live Neo4j probe \
164         records the name as front-end registered but unreachable \
165         -- no `SHOW FUNCTIONS` row, 42N48 under CYPHER 5 and 25 -- so the default dialect must \
166         not advertise it. Row and gate are deleted when a Neo4j release ships the function.",
167        "coll-zip"
168    ),
169    (
170        CollectionHas,
171        "CIP-286: the `coll.hasAnyOf`/`coll.hasAllOf`/\
172         `coll.hasNoneOf` collection functions, callable and `SHOW`-listed only under this \
173         opt-in (ADR-0497). One row for the three-name family; deleted when CIP-286 ships.",
174        "coll-has"
175    ),
176    (
177        GqlStddevAliases,
178        "CIP-245's `stddev_samp`/`stddev_pop` spellings (ADR-0497): the corpus catalogue lists \
179         only the canonical `stdev_samp`/`stdev_pop`, and Neo4j 2026.05 answers 42N48 for the \
180         GQL spellings, so the default dialect advertises and dispatches only the `stdev_*` \
181         rows. The gate keeps the `@doc`-derived 78/78 reachable. Deleted when a release \
182         registers the spellings (or the scenarios are re-pinned).",
183        "gql-stddev-aliases"
184    ),
185}
186
187/// The registered feature names, comma-separated, for the fail-closed
188/// unknown-name error. The table's order, the registry's order.
189fn known_feature_names() -> String {
190    PREVIEW_FEATURE_TABLE
191        .iter()
192        .map(|(_, name)| *name)
193        .collect::<Vec<_>>()
194        .join(", ")
195}
196
197/// The set of preview features enabled by `RELATE_PREVIEW` for one
198/// open store. Empty ([`PreviewFeatures::none`]) disables every gated
199/// feature.
200#[derive(Debug, Clone, Copy, PartialEq, Eq)]
201pub struct PreviewFeatures(u32);
202
203/// The fail-closed empty set: the value a store-level service bundle
204/// carries until open installs the resolved `RELATE_PREVIEW` set
205/// (ADR-0371, ADR-0378), so an executor-only `Graph::default()` gates every
206/// preview feature closed.
207impl Default for PreviewFeatures {
208    fn default() -> Self {
209        Self::none()
210    }
211}
212
213impl PreviewFeatures {
214    /// No preview features: every gate fails closed.
215    pub fn none() -> Self {
216        Self(0)
217    }
218
219    /// Parse one `RELATE_PREVIEW` value: a comma-separated list of
220    /// kebab-case feature names, whitespace tolerated around each name.
221    /// An empty or blank value enables nothing. An unknown name (including
222    /// an empty list segment) is a loud usage error naming the known
223    /// names — fail-closed, never silently ignored.
224    pub fn parse(raw: &str) -> Result<Self, Error> {
225        if raw.trim().is_empty() {
226            return Ok(Self::none());
227        }
228        let mut enabled = Self(0);
229        for name in raw.split(',') {
230            let name = name.trim();
231            let feature = PreviewFeature::from_kebab_name(name).ok_or_else(|| {
232                Error::semantic(format!(
233                    "{}: invalid RELATE_PREVIEW value: unknown preview feature \
234                     '{name}' (known features: {})",
235                    TckErrorClass::SemanticError.as_str(),
236                    known_feature_names(),
237                ))
238            })?;
239            // A fieldless variant's discriminant is its registry index.
240            enabled.0 |= 1 << (feature as u32);
241        }
242        Ok(enabled)
243    }
244
245    /// Whether `feature` is enabled for this store — the typed gate
246    /// predicate a gated feature checks where it would otherwise be parsed
247    /// or dispatched.
248    pub fn enabled(self, feature: PreviewFeature) -> bool {
249        self.0 & (1 << (feature as u32)) != 0
250    }
251
252    /// The set enabling every feature one by one, over an existing value:
253    /// the fixture constructor the gate tests build from the tables that own
254    /// the rows, so a new gated name is added in one place.
255    pub fn with_feature(self, feature: PreviewFeature) -> Self {
256        Self(self.0 | (1 << (feature as u32)))
257    }
258
259    /// The gate check: `Ok(())` when `feature` is enabled, otherwise the
260    /// authored fail-closed error of [`preview_feature_disabled`].
261    pub fn require(self, feature: PreviewFeature) -> Result<(), Error> {
262        if self.enabled(feature) {
263            Ok(())
264        } else {
265            Err(preview_feature_disabled(feature))
266        }
267    }
268}
269
270/// The authored fail-closed gate text for a preview feature invoked while
271/// disabled, already prefixed with its `SemanticError` class — the single
272/// source of the gate message. [`PreviewFeatures::require`] wraps it in an
273/// [`Error`]; layers outside this crate (the executor's graph-type
274/// semantic layer, which fails closed on the same constructs its
275/// statement-admission gate already checked when they only materialize
276/// against stored graph-type state) render it through their own error
277/// type without re-spelling it.
278pub fn preview_feature_disabled_text(feature: PreviewFeature) -> String {
279    let name = feature.kebab_name();
280    format!(
281        "{}: preview feature '{name}' is not enabled: set RELATE_PREVIEW={name}",
282        TckErrorClass::SemanticError.as_str(),
283    )
284}
285
286/// The authored fail-closed gate error for a preview feature invoked while
287/// disabled (the house style of the ADR-0229 §2 authored text): the
288/// engine renders `semantic error: SemanticError: preview feature
289/// '<name>' is not enabled: set RELATE_PREVIEW=<name>`.
290pub(crate) fn preview_feature_disabled(feature: PreviewFeature) -> Error {
291    Error::semantic(preview_feature_disabled_text(feature))
292}
293
294#[cfg(test)]
295mod tests {
296    use super::*;
297
298    #[test]
299    fn registry_names_are_unique_and_round_trip() {
300        // The macro single-sources the variant list and the rows, so
301        // exhaustiveness is a compile guarantee; these pin the rest: no
302        // name spelled twice, and every row's name parses back to its
303        // variant.
304        let mut seen = std::collections::HashSet::new();
305        for (feature, name) in PREVIEW_FEATURE_TABLE {
306            assert_eq!(feature.kebab_name(), *name);
307            assert!(seen.insert(*name), "duplicate name {name}");
308            assert_eq!(PreviewFeature::from_kebab_name(name), Some(*feature));
309        }
310        assert_eq!(PreviewFeature::from_kebab_name("nope"), None);
311    }
312
313    #[test]
314    fn parse_empty_and_unset_value_enable_nothing() {
315        assert_eq!(PreviewFeatures::parse("").unwrap(), PreviewFeatures::none());
316        assert_eq!(
317            PreviewFeatures::parse("   ").unwrap(),
318            PreviewFeatures::none()
319        );
320        for feature in PREVIEW_FEATURES {
321            assert!(!PreviewFeatures::none().enabled(*feature));
322        }
323    }
324
325    #[test]
326    fn parse_comma_lists_and_whitespace() {
327        let features =
328            PreviewFeatures::parse(" hybrid-search,graph-type-implied-labels , local-callables ")
329                .unwrap();
330        assert!(features.enabled(PreviewFeature::HybridSearch));
331        assert!(features.enabled(PreviewFeature::GraphTypeImpliedLabels));
332        assert!(features.enabled(PreviewFeature::LocalCallables));
333        assert!(!features.enabled(PreviewFeature::GraphTypeOptProps));
334        assert!(!features.enabled(PreviewFeature::GraphTypeDefaultValues));
335        // A repeated name stays a plain enable, not an error.
336        assert_eq!(
337            PreviewFeatures::parse("hybrid-search, hybrid-search").unwrap(),
338            PreviewFeatures::parse("hybrid-search").unwrap(),
339        );
340    }
341
342    #[test]
343    fn parse_unknown_name_fails_closed_naming_known_names() {
344        let error = PreviewFeatures::parse("hybrid-search,bogus").unwrap_err();
345        assert!(matches!(error, Error::Semantic(_)), "{error}");
346        let display = error.to_string();
347        assert!(
348            display.contains("unknown preview feature 'bogus'"),
349            "{display}"
350        );
351        for (_, name) in PREVIEW_FEATURE_TABLE {
352            assert!(display.contains(name), "{display} misses {name}");
353        }
354        // An empty segment is an unknown name, not a silent skip.
355        let error = PreviewFeatures::parse("hybrid-search,,local-callables").unwrap_err();
356        assert!(
357            error.to_string().contains("unknown preview feature ''"),
358            "{}",
359            error
360        );
361    }
362
363    #[test]
364    fn parse_each_registered_name_enables_exactly_that_feature() {
365        // Table-driven over the one registry: every row's name parses to a
366        // set with exactly that row enabled, so a new row is covered
367        // without a new test. (The `ontology` row is ADR-0378's
368        // procedure-family exception to ADR-0371's syntax-only scope
369        // policy; it needs no special case.)
370        for feature in PREVIEW_FEATURES {
371            let enabled = PreviewFeatures::parse(feature.kebab_name()).unwrap();
372            assert!(enabled.enabled(*feature), "{}", feature.kebab_name());
373            for other in PREVIEW_FEATURES {
374                if other != feature {
375                    assert!(
376                        !enabled.enabled(*other),
377                        "{} also enabled {}",
378                        feature.kebab_name(),
379                        other.kebab_name()
380                    );
381                }
382            }
383        }
384    }
385
386    #[test]
387    fn require_gates_with_the_authored_disabled_error() {
388        let features = PreviewFeatures::parse("local-callables").unwrap();
389        assert!(features.require(PreviewFeature::LocalCallables).is_ok());
390        let error = features.require(PreviewFeature::HybridSearch).unwrap_err();
391        assert_eq!(
392            error.to_string(),
393            "semantic error: SemanticError: preview feature 'hybrid-search' is not enabled: \
394             set RELATE_PREVIEW=hybrid-search"
395        );
396        // The disabled text is stable for every registered feature.
397        for (feature, name) in PREVIEW_FEATURE_TABLE {
398            let error = preview_feature_disabled(*feature);
399            assert!(
400                error.to_string().ends_with(&format!(
401                    "preview feature '{name}' is not enabled: set RELATE_PREVIEW={name}"
402                )),
403                "{}",
404                error
405            );
406        }
407    }
408}