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 and ADR-0741: a built-in surface whose contract tracks a
14//! non-final external spec — the `ontology` row gates the
15//! `db.ontology.*` procedure family, the `dbms.listCapabilities` row
16//! `ontology.supported.version`, and, through the namespace registry's
17//! one fixed-namespace → feature mapping, the `system_ontologies`
18//! namespace's visibility. (b) ADR-0497: a
19//! *name admission* gate — a function name an approved CIP adds that no
20//! reference release ships, or one the corpus records as unreachable
21//! (`coll-zip`, `coll-has`, `gql-stddev-aliases`). A name
22//! gate hides a name; it never widens grammar, and its disabled form is the
23//! registry's ordinary unknown-function rejection rather than the authored
24//! error below: a name that must not exist cannot be named in an error
25//! without advertising it. (c) ADR-0593: a fixed namespace's visibility —
26//! the name-gate rule in namespace form, so a hidden database is
27//! indistinguishable from an unknown one at every resolution site: listed
28//! by no catalog, rejected by the site's own unknown-database path, never
29//! the authored error. (d) ADR-0703: a *storage representation* — the
30//! `vortex-store` row gates an experimental property store's attach at
31//! `Database::open` itself, so its disabled form is not an error at all:
32//! the default compact records answer unchanged, and no statement can ask
33//! for the store by name. None of the exceptions is general — additive
34//! function names and surfaces on our own pinned contract still never
35//! gate. Each gated feature checks the gate where it would otherwise be
36//! parsed or dispatched; while disabled a syntax or procedure-family check
37//! fails with [`preview_feature_disabled`]'s authored error.
38//!
39//! The registry macro is the single source: variant, doc, and name are
40//! declared once, and the macro emits every derivation — the enum, the
41//! exhaustive `kebab_name`/`from_kebab_name` matches (coverage is a
42//! compile guarantee), and [`PREVIEW_FEATURE_TABLE`], the registry view
43//! the fail-closed known-names list renders from. A later feature PR adds
44//! its row here and gates its syntax; nothing else names the feature.
45
46use crate::error_kinds::TckErrorClass;
47
48use crate::Error;
49
50/// One declaration list per closed payload vocabulary: the macro emits
51/// the enum and its `ALL` enumeration from the same list, so a variant
52/// cannot exist without its row in `ALL` and vice versa — the compile
53/// guarantee the site audits rest on.
54macro_rules! closed_vocabulary {
55    ($name:ident, $doc:literal, [$($variant:ident),* $(,)?]) => {
56        #[doc = $doc]
57        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
58        pub enum $name {
59            $($variant,)*
60        }
61
62        impl $name {
63            /// Every variant, declaration order — derived from the same
64            /// list as the enum, so a new variant joins it without a
65            /// second edit.
66            pub const ALL: &'static [$name] = &[$($name::$variant),*];
67        }
68    };
69}
70
71closed_vocabulary!(
72    ParseOption,
73    "The `ParseOptions` field a parse-site feature switches on, one \
74     variant per option. The front applies each through one total `match`.",
75    [
76        ObfuscatedLiterals,
77        MixedLabelSyntax,
78        CypherAnnotations,
79        PathConstruction
80    ]
81);
82
83closed_vocabulary!(
84    DetectorKind,
85    "The front's AST detector a detected feature is checked by, one \
86     variant per distinct detector. The front dispatches through one \
87     total `match`.",
88    [
89        HybridSearch,
90        LocalCallables,
91        Float16,
92        PathConstruction,
93        Chronological,
94    ]
95);
96
97/// Where in the pipeline a preview feature's gate is checked, for the
98/// sites whose consumers a test can read. A feature gated where this
99/// vocabulary cannot name the site (statement validation, run-time
100/// evaluation, the executor's graph-type layer) declares
101/// [`GateSite::GatedElsewhere`]; a row never declares no site.
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
103pub enum GateSite {
104    /// The lexer or parser decides it, through this parse option.
105    ParseOption(ParseOption),
106    /// The front's AST detector loop rejects the feature's syntax.
107    AstDetector(DetectorKind),
108    /// The graph-type family: the front's one graph-type walk reports the
109    /// features a statement's graph-type bodies use, checked in the same
110    /// admission loop.
111    GraphTypeMembership,
112    /// A function name is admitted or hidden by the function registry.
113    NameAdmission,
114    /// Procedure dispatch gates a built-in procedure family.
115    ProcedureDispatch,
116    /// The namespace registry hides a fixed namespace.
117    Namespace,
118    /// A `dbms.listCapabilities` row lists only while the opt-in is set —
119    /// a row-content gate, not a call gate: the procedure stays callable
120    /// and its always-on rows are unchanged.
121    CapabilityListing,
122    /// Gated at a site this vocabulary does not name; the row's own doc says
123    /// where. Distinct from "ungated": an empty site list is rejected.
124    GatedElsewhere,
125}
126
127/// Where a [`GateSite`]'s gate is checked — the closed owner vocabulary
128/// each consumer matches once, so a new site names its consumer where
129/// the site is declared and no consumer re-lists the sites it does not
130/// own. The front owns the parse options, the AST detectors and the one
131/// graph-type walk; everything else belongs to a consumer outside the
132/// front (function admission, procedure dispatch, the namespace
133/// mapping, the capability-row producer, the evaluator, the open-time
134/// attach).
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
136pub enum GateOwner {
137    /// [`GateSite::ParseOption`]'s owner.
138    Parse(ParseOption),
139    /// [`GateSite::AstDetector`]'s owner.
140    Detect(DetectorKind),
141    /// [`GateSite::GraphTypeMembership`]'s owner.
142    GraphTypeWalk,
143    /// An owner outside the front (the enum's doc names them).
144    External,
145}
146
147impl GateSite {
148    /// The site's owner: the one classification every consumer matches,
149    /// so the front's totals and the facade's audits hold one stable
150    /// match over this small vocabulary instead of re-listing the site
151    /// subsets they do not act on.
152    pub fn owner(self) -> GateOwner {
153        match self {
154            GateSite::ParseOption(option) => GateOwner::Parse(option),
155            GateSite::AstDetector(kind) => GateOwner::Detect(kind),
156            GateSite::GraphTypeMembership => GateOwner::GraphTypeWalk,
157            GateSite::NameAdmission
158            | GateSite::ProcedureDispatch
159            | GateSite::Namespace
160            | GateSite::CapabilityListing
161            | GateSite::GatedElsewhere => GateOwner::External,
162        }
163    }
164
165    /// Every payload-less site, one row per variant — the enumerable
166    /// subset the audits iterate. The payload-carrying sites — those
167    /// whose [`owner`](Self::owner) is `Parse` or `Detect` — enumerate
168    /// through their own payload vocabularies
169    /// ([`ParseOption::ALL`], [`DetectorKind::ALL`]); a new payload-less
170    /// variant joins this list, and the registry's gate-site audit fails
171    /// if a declared site is missing from it.
172    pub const ALL: &'static [GateSite] = &[
173        GateSite::GraphTypeMembership,
174        GateSite::NameAdmission,
175        GateSite::ProcedureDispatch,
176        GateSite::Namespace,
177        GateSite::CapabilityListing,
178        GateSite::GatedElsewhere,
179    ];
180}
181
182/// The one registry: each preview feature's variant, doc comment,
183/// kebab-case `RELATE_PREVIEW` name, and gate sites are declared from this single
184/// list, so a variant cannot exist without its name and vice versa — a
185/// forgotten row is a compile error, not a runtime `expect`. Every other
186/// spelling of a feature name derives from [`PREVIEW_FEATURE_TABLE`].
187macro_rules! preview_feature_registry {
188    ($(($variant:ident, $doc:literal, $name:literal, [$($site:expr),* $(,)?])),* $(,)?) => {
189        /// A gated preview Cypher feature. The table order is the
190        /// registry order; rows are never renumbered, only appended.
191        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
192        pub enum PreviewFeature {
193            $(
194                #[doc = $doc]
195                $variant,
196            )*
197        }
198
199        /// The one registry: each preview feature with its kebab-case
200        /// `RELATE_PREVIEW` name. The table order is the registry
201        /// order; rows are never renumbered, only appended.
202        pub const PREVIEW_FEATURE_TABLE: &[(PreviewFeature, &str)] =
203            &[$((PreviewFeature::$variant, $name)),*];
204
205        /// Every registered feature, registry order — the enumeration
206        /// callers iterate instead of re-spelling the vocabulary.
207        pub const PREVIEW_FEATURES: &[PreviewFeature] = &[$(PreviewFeature::$variant),*];
208
209        /// The registry width bound: the bitset's `u32` holds every
210        /// registered feature — a 33rd row is a compile error, not a
211        /// runtime wrap.
212        const _: () = assert!([$(stringify!($variant)),*].len() <= 32);
213
214        // A row never declares no gate site: an empty list would conflate
215        // "gated where the vocabulary cannot name it" (`GatedElsewhere`)
216        // with "not gated".
217        $(
218            const _: () = assert!(
219                ![$(stringify!($site)),*].is_empty(),
220                concat!(stringify!($variant), " declares no gate site")
221            );
222        )*
223
224        impl PreviewFeature {
225            /// The feature's kebab-case `RELATE_PREVIEW` name. The
226            /// exhaustive match is the compile guarantee the registry
227            /// exists for — coverage cannot drift from the table.
228            pub fn kebab_name(self) -> &'static str {
229                match self {
230                    $(PreviewFeature::$variant => $name,)*
231                }
232            }
233
234            /// The pipeline sites that check this feature's gate.
235            pub fn gate_sites(self) -> &'static [GateSite] {
236                match self {
237                    $(PreviewFeature::$variant => &[$($site),*],)*
238                }
239            }
240
241            /// The feature for a kebab-case `RELATE_PREVIEW` name.
242            /// `None` when `name` is not a registered feature.
243            pub fn from_kebab_name(name: &str) -> Option<Self> {
244                match name {
245                    $($name => Some(PreviewFeature::$variant),)*
246                    _ => None,
247                }
248            }
249        }
250    };
251}
252
253preview_feature_registry! {
254    (HybridSearch, "CIP-278 hybrid search `COMBINE` (reserved; lands later).", "hybrid-search", [GateSite::AstDetector(DetectorKind::HybridSearch)]),
255    (LocalCallables, "CIP-231 local callables: DEFINE PROCEDURE/FUNCTION, ADR-0382.", "local-callables", [GateSite::AstDetector(DetectorKind::LocalCallables)]),
256    (GraphTypeOptProps, "CIP-283 graph-type optional properties (`prop :: ANY` in element types).", "graph-type-opt-props", [GateSite::GraphTypeMembership]),
257    (GraphTypeDefaultValues, "CIP-262 graph-type property default values (`DEFAULT ON COMMIT <value expression>`).", "graph-type-default-values", [GateSite::GraphTypeMembership]),
258    (GraphTypeImpliedLabels, "CIP-266 graph-type implied labels that identify node element types (inheritance).", "graph-type-implied-labels", [GateSite::GraphTypeMembership]),
259    (
260        Ontology,
261        "The ontology feature's whole dialect surface: the `db.ontology.*` procedures \
262         (ADR-0378: the first non-syntax extension of ADR-0371's scope policy — the \
263         family's contract tracks the non-final Ontology Graph Spec and CIP-287), the \
264         `system_ontologies` namespace's visibility through the namespace registry's \
265         mapping (ADR-0593 — the namespace exists to host this feature's stored \
266         document, so its listing advertises the same non-final surface the procedures \
267         do), and the `dbms.listCapabilities` row `ontology.supported.version` \
268         (ADR-0741 — the supported-spec-version fact ontology tooling reads, absent \
269         while the opt-in is off like every other surface of the feature). Row, \
270         mapping and gates are removed once the spec and CIP-287 are final.",
271        "ontology",
272        [GateSite::ProcedureDispatch, GateSite::Namespace, GateSite::CapabilityListing]
273    ),
274    (
275        ObfuscatedLiterals,
276        "The Neo4j obfuscated literal `******`: parsed to a dummy `false` \
277         for semantic analysis, never executed. Gates at the lexer, the one point the two \
278         behaviors differ: enabled it lexes as a literal, disabled the stream is the ordinary \
279         `*` tokens and the parser's own syntax error -- Neo4j's disabled form is a syntax \
280         error, not ADR-0371's authored preview error, so the gate never reaches the front \
281         detector loop (the registry names no detector site for it).",
282        "obfuscated-literals",
283        [GateSite::ParseOption(ParseOption::ObfuscatedLiterals)]
284    ),
285    (
286        MixedLabelSyntax,
287        "Neo4j's mixed-label-syntax extra semantic feature: legacy \
288         colon-conjunction, GQL label-expression symbols and the `IS` introducer may mix \
289         across the label expressions of one clause (gates at parse, threaded to the parser \
290         as `ParseOptions`; mixing inside ONE label expression stays rejected).",
291        "mixed-label-syntax",
292        [GateSite::ParseOption(ParseOption::MixedLabelSyntax)]
293    ),
294    (
295        Float16CoordinateTypes,
296        "The FLOAT16/BFLOAT16 vector coordinate types (CIP-280, ADR-0464), mirroring \
297         Neo4j's own configuration toggle: the types in a \
298         `VECTOR<…>` type expression and the `vector(<list>, <dim>, <type>)` constructor. \
299         Detected on the parsed AST; the disabled form is ADR-0371's authored error.",
300        "float16-coordinate-types",
301        [GateSite::AstDetector(DetectorKind::Float16)]
302    ),
303    (
304        ChronologicalComparisons,
305        "Cypher 25's four chronological comparison operators \
306         (`a IS [NOT] BEFORE | AFTER | SAME INSTANT | SAME REPRESENTATION b`), mirroring \
307         Neo4j's own toggle. Detected on the \
308         parsed AST; the disabled form is ADR-0371's authored error.",
309        "chronological-comparisons",
310        [GateSite::AstDetector(DetectorKind::Chronological)]
311    ),
312    (
313        CollectionZip,
314        "CIP-274: the `coll.zip` collection function, callable and \
315         `SHOW`-listed only under this opt-in (ADR-0497). A live Neo4j probe \
316         records the name as front-end registered but unreachable \
317         -- no `SHOW FUNCTIONS` row, 42N48 under CYPHER 5 and 25 -- so the default dialect must \
318         not advertise it. Row and gate are deleted when a Neo4j release ships the function.",
319        "coll-zip",
320        [GateSite::NameAdmission]
321    ),
322    (
323        CollectionHas,
324        "CIP-286: the `coll.hasAnyOf`/`coll.hasAllOf`/\
325         `coll.hasNoneOf` collection functions, callable and `SHOW`-listed only under this \
326         opt-in (ADR-0497). One row for the three-name family; deleted when CIP-286 ships.",
327        "coll-has",
328        [GateSite::NameAdmission]
329    ),
330    (
331        CypherAnnotations,
332        "CIP-281 Cypher annotations: clause-level `@name(params)` markers before a \
333         clause, parsed and semantically checked, then discarded (no runtime effect). \
334         Gates at the lexer, the one point the two behaviors differ: enabled, `@` lexes \
335         as the annotation introducer; disabled, it is the ordinary `unexpected \
336         character: @` syntax error. Row and gate are deleted when the CIP ships in a \
337         release.",
338        "cypher-annotations",
339        [GateSite::ParseOption(ParseOption::CypherAnnotations)]
340    ),
341    (
342        GqlStddevAliases,
343        "CIP-245's `stddev_samp`/`stddev_pop` spellings (ADR-0497): the corpus catalogue lists \
344         only the canonical `stdev_samp`/`stdev_pop`, and Neo4j 2026.05 answers 42N48 for the \
345         GQL spellings, so the default dialect advertises and dispatches only the `stdev_*` \
346         rows. The gate keeps the `@doc`-derived 78/78 reachable. Deleted when a release \
347         registers the spellings (or the scenarios are re-pinned).",
348        "gql-stddev-aliases",
349        [GateSite::NameAdmission]
350    ),
351    (
352        GraphTypeShowVariants,
353        "CIP-275 graph-type display variants of SHOW CURRENT GRAPH TYPE: consolidated and flattened.",
354        "graph-type-show-variants",
355        [GateSite::GraphTypeMembership]
356    ),
357    (
358        PathConstruction,
359        "The `PATH [n1, r1, n2, ...]` path constructor: builds a path value from an \
360         alternating node, relationship, ... list. Detected at the parse point (the \
361         `PATH` word before `[`); the disabled form is ADR-0371's authored error.",
362        "path-construction",
363        [GateSite::ParseOption(ParseOption::PathConstruction), GateSite::AstDetector(DetectorKind::PathConstruction)]
364    ),
365    (
366        PathConcatenation,
367        "The `p1 || p2` path concatenation: joins two paths that share a boundary \
368         node. Gates the `||` operator over path operands at evaluation; the disabled \
369         form is the existing `||` operand type error, not the authored error.",
370        "path-concatenation",
371        [GateSite::GatedElsewhere]
372    ),
373    (
374        VortexStore,
375        "The Vortex columnar property store (ADR-0665), experimental: an \
376         alternative storage representation behind the executor's PropStore \
377         seam. The registry's first storage-representation row (ADR-0703): \
378         the gate is at `Database::open`, not at a parse or dispatch site — \
379         the row attaches the store for every open in the process (the typed \
380         `OpenOptions::vortex_store` field opts in one open), and a build \
381         without the `vortex-store` cargo feature fails the open closed \
382         naming the feature. While disabled nothing changes: the default \
383         compact records answer, and no statement can ask for the store, so \
384         there is no authored disabled-error.",
385        "vortex-store",
386        [GateSite::GatedElsewhere]
387    ),
388}
389
390/// The registered feature names, comma-separated, for the fail-closed
391/// unknown-name error. The table's order, the registry's order.
392fn known_feature_names() -> String {
393    PREVIEW_FEATURE_TABLE
394        .iter()
395        .map(|(_, name)| *name)
396        .collect::<Vec<_>>()
397        .join(", ")
398}
399
400/// The set of preview features enabled by `RELATE_PREVIEW` for one
401/// open store. Empty ([`PreviewFeatures::none`]) disables every gated
402/// feature.
403#[derive(Debug, Clone, Copy, PartialEq, Eq)]
404pub struct PreviewFeatures(u32);
405
406/// The fail-closed empty set: the value a store-level service bundle
407/// carries until open installs the resolved `RELATE_PREVIEW` set
408/// (ADR-0371, ADR-0378), so an executor-only `Graph::default()` gates every
409/// preview feature closed.
410impl Default for PreviewFeatures {
411    fn default() -> Self {
412        Self::none()
413    }
414}
415
416impl PreviewFeatures {
417    /// No preview features: every gate fails closed.
418    pub fn none() -> Self {
419        Self(0)
420    }
421
422    /// Parse one opt-in value — the single grammar every preview
423    /// source shares (ADR-0719): the `RELATE_PREVIEW` environment
424    /// variable, the store-committed `relate.yaml` `preview:` list,
425    /// and the typed `OpenOptions.preview` field all resolve through
426    /// here, each naming its own `source` in a failure. A
427    /// comma-separated list of kebab-case feature names, whitespace
428    /// tolerated around each name. An empty or blank value enables
429    /// nothing. An unknown name (including an empty list segment) is a
430    /// loud usage error naming the known names — fail-closed, never
431    /// silently ignored.
432    pub fn parse_named(source: &str, raw: &str) -> Result<Self, Error> {
433        if raw.trim().is_empty() {
434            return Ok(Self::none());
435        }
436        Self::from_names(source, raw.split(',').map(str::trim))
437    }
438
439    /// Resolve already-separated feature names — the per-name half of
440    /// the one grammar, for a source whose names arrive as a typed list
441    /// (the store-committed `relate.yaml` `preview:` sequence, ADR-0719)
442    /// rather than one comma string. Every name resolves against the
443    /// registry or the whole call fails naming `source` and the known
444    /// names; an empty name is an unknown name, never a silent skip. No
445    /// names enables nothing.
446    pub fn from_names<'a>(
447        source: &str,
448        names: impl IntoIterator<Item = &'a str>,
449    ) -> Result<Self, Error> {
450        names.into_iter().try_fold(Self::none(), |enabled, name| {
451            let feature = PreviewFeature::from_kebab_name(name).ok_or_else(|| {
452                Error::semantic(format!(
453                    "{}: invalid {source} value: unknown preview feature \
454                     '{name}' (known features: {})",
455                    TckErrorClass::SemanticError.as_str(),
456                    known_feature_names(),
457                ))
458            })?;
459            Ok(enabled.with_feature(feature))
460        })
461    }
462
463    /// An optional surface parameter — absent opts into nothing, present
464    /// parses with [`Self::parse_named`]. The one statement of the
465    /// "optional opt-in" rule the binding surfaces (the wasm and Python
466    /// parameters) share; each keeps only its own error mapping.
467    pub fn parse_optional(source: &str, raw: Option<&str>) -> Result<Self, Error> {
468        raw.map_or(Ok(Self::none()), |raw| Self::parse_named(source, raw))
469    }
470
471    /// Parse one `RELATE_PREVIEW` value: a comma-separated list of
472    /// kebab-case feature names, whitespace tolerated around each name.
473    /// An empty or blank value enables nothing. An unknown name (including
474    /// an empty list segment) is a loud usage error naming the known
475    /// names — fail-closed, never silently ignored.
476    pub fn parse(raw: &str) -> Result<Self, Error> {
477        Self::parse_named(PREVIEW_ENV_VAR, raw)
478    }
479
480    /// Whether `feature` is enabled for this store — the typed gate
481    /// predicate a gated feature checks where it would otherwise be parsed
482    /// or dispatched.
483    pub fn enabled(self, feature: PreviewFeature) -> bool {
484        self.0 & (1 << (feature as u32)) != 0
485    }
486
487    /// The set enabling every feature one by one, over an existing value:
488    /// the fixture constructor the gate tests build from the tables that own
489    /// the rows, so a new gated name is added in one place.
490    pub fn with_feature(self, feature: PreviewFeature) -> Self {
491        Self(self.0 | (1 << (feature as u32)))
492    }
493
494    /// The union of two resolved sets (ADR-0719): every preview source
495    /// is additive — the environment variable, the store-committed
496    /// config and the typed open option stack through here, and none
497    /// removes. Order is irrelevant.
498    pub fn union(self, other: Self) -> Self {
499        Self(self.0 | other.0)
500    }
501
502    /// The gate check: `Ok(())` when `feature` is enabled, otherwise the
503    /// authored fail-closed error of [`preview_feature_disabled`].
504    pub fn require(self, feature: PreviewFeature) -> Result<(), Error> {
505        if self.enabled(feature) {
506            Ok(())
507        } else {
508            Err(preview_feature_disabled(feature))
509        }
510    }
511}
512
513/// The preview opt-in's environment variable (ADR-0371) — the one
514/// spelling of its name: the open reads it, and its parse failure cites
515/// it.
516pub const PREVIEW_ENV_VAR: &str = "RELATE_PREVIEW";
517
518/// The store-committed config file's one spelling (ADR-0719 decision 1:
519/// no JSON twin, no second name) — the store-committed preview carrier's
520/// name, here beside the variable's so every layer that names a carrier
521/// (the storage reader, the `SHOW SETTINGS` provenance) reads one fact.
522pub const STORE_CONFIG_FILE: &str = "relate.yaml";
523
524/// One of the preview opt-in's three additive carriers (ADR-0719
525/// decision 3) — the typed vocabulary of [`PreviewSources`]. It carries
526/// no display text: each layer that names a carrier (a parse failure, the
527/// `SHOW SETTINGS` provenance) spells it where that text belongs.
528#[derive(Debug, Clone, Copy, PartialEq, Eq)]
529pub enum PreviewSource {
530    /// The `RELATE_PREVIEW` environment variable — the machine's local
531    /// extra, where an environment exists.
532    Env,
533    /// The store-committed `relate.yaml` `preview:` list — the store's
534    /// declared contract.
535    Config,
536    /// The typed `OpenOptions.preview` field — the embedder's choice,
537    /// each surface's own opt-in spelling (the CLI's `--preview`, the
538    /// wasm parameter, the Python keyword).
539    Option,
540}
541
542/// The preview opt-in's resolved sources (ADR-0719 decision 3): the
543/// three additive carriers, kept per-set so the resolved surface can
544/// report which source enabled each feature. The union is derived —
545/// never stored beside its parts — so the parts and the whole cannot
546/// drift: every gate reads [`Self::union`], and `SHOW SETTINGS`
547/// (ADR-0719 decision 6) reads [`Self::carriers`] for the provenance it
548/// reports.
549#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
550pub struct PreviewSources {
551    /// [`PreviewSource::Env`]'s set.
552    pub env: PreviewFeatures,
553    /// [`PreviewSource::Config`]'s set.
554    pub config: PreviewFeatures,
555    /// [`PreviewSource::Option`]'s set.
556    pub option: PreviewFeatures,
557}
558
559impl PreviewSources {
560    /// Every carrier with its set, in the fixed order the provenance
561    /// reports them — the one table [`Self::union`] and
562    /// [`Self::carriers`] read. Built by an exhaustive destructure, so a
563    /// new carrier field is a compile error here, never a source silently
564    /// left out of the union.
565    fn parts(&self) -> [(PreviewSource, PreviewFeatures); 3] {
566        let Self {
567            env,
568            config,
569            option,
570        } = *self;
571        [
572            (PreviewSource::Env, env),
573            (PreviewSource::Config, config),
574            (PreviewSource::Option, option),
575        ]
576    }
577
578    /// The three sources' additive union (ADR-0719 decision 3) — the
579    /// resolved set every gate reads, derived here so it is never
580    /// stored beside the parts it comes from.
581    pub fn union(&self) -> PreviewFeatures {
582        self.parts()
583            .into_iter()
584            .fold(PreviewFeatures::none(), |set, (_, part)| set.union(part))
585    }
586
587    /// The carriers that enabled `feature`, in [`Self::parts`]' order —
588    /// the provenance `SHOW SETTINGS` reports. Empty exactly when the
589    /// union has the feature off.
590    pub fn carriers(&self, feature: PreviewFeature) -> impl Iterator<Item = PreviewSource> {
591        self.parts()
592            .into_iter()
593            .filter(move |(_, part)| part.enabled(feature))
594            .map(|(source, _)| source)
595    }
596}
597
598/// The authored fail-closed gate text for a preview feature invoked while
599/// disabled, already prefixed with its `SemanticError` class — the single
600/// source of the gate message. [`PreviewFeatures::require`] wraps it in an
601/// [`Error`]; layers outside this crate (the executor's graph-type
602/// semantic layer, which fails closed on the same constructs its
603/// statement-admission gate already checked when they only materialize
604/// against stored graph-type state) render it through their own error
605/// type without re-spelling it.
606pub fn preview_feature_disabled_text(feature: PreviewFeature) -> String {
607    let name = feature.kebab_name();
608    format!(
609        "{}: preview feature '{name}' is not enabled: set RELATE_PREVIEW={name}",
610        TckErrorClass::SemanticError.as_str(),
611    )
612}
613
614/// The authored fail-closed gate error for a preview feature invoked while
615/// disabled (the house style of the ADR-0229 §2 authored text): the
616/// engine renders `semantic error: SemanticError: preview feature
617/// '<name>' is not enabled: set RELATE_PREVIEW=<name>`.
618pub(crate) fn preview_feature_disabled(feature: PreviewFeature) -> Error {
619    Error::semantic(preview_feature_disabled_text(feature))
620}
621
622#[cfg(test)]
623mod tests {
624    use super::*;
625
626    #[test]
627    fn registry_names_are_unique_and_round_trip() {
628        // The macro single-sources the variant list and the rows, so
629        // exhaustiveness is a compile guarantee; these pin the rest: no
630        // name spelled twice, and every row's name parses back to its
631        // variant.
632        let mut seen = std::collections::HashSet::new();
633        for (feature, name) in PREVIEW_FEATURE_TABLE {
634            assert_eq!(feature.kebab_name(), *name);
635            assert!(seen.insert(*name), "duplicate name {name}");
636            assert_eq!(PreviewFeature::from_kebab_name(name), Some(*feature));
637        }
638        assert_eq!(PreviewFeature::from_kebab_name("nope"), None);
639    }
640
641    #[test]
642    fn gate_sites_never_repeat_within_a_row() {
643        for feature in PREVIEW_FEATURES {
644            let mut seen = std::collections::HashSet::new();
645            for site in feature.gate_sites() {
646                assert!(
647                    seen.insert(*site),
648                    "{} repeats {site:?}",
649                    feature.kebab_name()
650                );
651            }
652        }
653    }
654
655    #[test]
656    fn every_declared_payload_less_site_is_enumerated() {
657        // `GateSite::ALL` is the hand-maintained enumeration the audits
658        // iterate; a declared payload-less site missing from it would
659        // silently escape them. The payload-carrying sites are excluded —
660        // their owner is `Parse` or `Detect` and they enumerate through
661        // their own payload vocabularies.
662        for feature in PREVIEW_FEATURES {
663            for site in feature.gate_sites() {
664                if matches!(site.owner(), GateOwner::Parse(_) | GateOwner::Detect(_)) {
665                    continue;
666                }
667                assert!(
668                    GateSite::ALL.contains(site),
669                    "{} declares {site:?}, which GateSite::ALL does not enumerate",
670                    feature.kebab_name()
671                );
672            }
673        }
674    }
675
676    #[test]
677    fn parse_empty_and_unset_value_enable_nothing() {
678        assert_eq!(PreviewFeatures::parse("").unwrap(), PreviewFeatures::none());
679        assert_eq!(
680            PreviewFeatures::parse("   ").unwrap(),
681            PreviewFeatures::none()
682        );
683        for feature in PREVIEW_FEATURES {
684            assert!(!PreviewFeatures::none().enabled(*feature));
685        }
686    }
687
688    #[test]
689    fn parse_comma_lists_and_whitespace() {
690        let features =
691            PreviewFeatures::parse(" hybrid-search,graph-type-implied-labels , local-callables ")
692                .unwrap();
693        assert!(features.enabled(PreviewFeature::HybridSearch));
694        assert!(features.enabled(PreviewFeature::GraphTypeImpliedLabels));
695        assert!(features.enabled(PreviewFeature::LocalCallables));
696        assert!(!features.enabled(PreviewFeature::GraphTypeOptProps));
697        assert!(!features.enabled(PreviewFeature::GraphTypeDefaultValues));
698        // A repeated name stays a plain enable, not an error.
699        assert_eq!(
700            PreviewFeatures::parse("hybrid-search, hybrid-search").unwrap(),
701            PreviewFeatures::parse("hybrid-search").unwrap(),
702        );
703    }
704
705    #[test]
706    fn parse_unknown_name_fails_closed_naming_known_names() {
707        let error = PreviewFeatures::parse("hybrid-search,bogus").unwrap_err();
708        assert!(matches!(error, Error::Semantic(_)), "{error}");
709        let display = error.to_string();
710        assert!(
711            display.contains("unknown preview feature 'bogus'"),
712            "{display}"
713        );
714        for (_, name) in PREVIEW_FEATURE_TABLE {
715            assert!(display.contains(name), "{display} misses {name}");
716        }
717        // An empty segment is an unknown name, not a silent skip.
718        let error = PreviewFeatures::parse("hybrid-search,,local-callables").unwrap_err();
719        assert!(
720            error.to_string().contains("unknown preview feature ''"),
721            "{}",
722            error
723        );
724    }
725
726    #[test]
727    fn parse_each_registered_name_enables_exactly_that_feature() {
728        // Table-driven over the one registry: every row's name parses to a
729        // set with exactly that row enabled, so a new row is covered
730        // without a new test. (The `ontology` row is ADR-0378's
731        // procedure-family exception to ADR-0371's syntax-only scope
732        // policy; it needs no special case.)
733        for feature in PREVIEW_FEATURES {
734            let enabled = PreviewFeatures::parse(feature.kebab_name()).unwrap();
735            assert!(enabled.enabled(*feature), "{}", feature.kebab_name());
736            for other in PREVIEW_FEATURES {
737                if other != feature {
738                    assert!(
739                        !enabled.enabled(*other),
740                        "{} also enabled {}",
741                        feature.kebab_name(),
742                        other.kebab_name()
743                    );
744                }
745            }
746        }
747    }
748
749    #[test]
750    fn require_gates_with_the_authored_disabled_error() {
751        let features = PreviewFeatures::parse("local-callables").unwrap();
752        assert!(features.require(PreviewFeature::LocalCallables).is_ok());
753        let error = features.require(PreviewFeature::HybridSearch).unwrap_err();
754        assert_eq!(
755            error.to_string(),
756            "semantic error: SemanticError: preview feature 'hybrid-search' is not enabled: \
757             set RELATE_PREVIEW=hybrid-search"
758        );
759        // The disabled text is stable for every registered feature.
760        for (feature, name) in PREVIEW_FEATURE_TABLE {
761            let error = preview_feature_disabled(*feature);
762            assert!(
763                error.to_string().ends_with(&format!(
764                    "preview feature '{name}' is not enabled: set RELATE_PREVIEW={name}"
765                )),
766                "{}",
767                error
768            );
769        }
770    }
771
772    #[test]
773    fn the_sources_union_derives_additively_from_its_parts() {
774        // ADR-0719: the parts are the stored fact and the union
775        // derives — one feature per source stacks, and a part's
776        // removal narrows the derived union the same open would
777        // otherwise resolve.
778        let sources = PreviewSources {
779            env: PreviewFeatures::parse("hybrid-search").unwrap(),
780            config: PreviewFeatures::parse("ontology").unwrap(),
781            option: PreviewFeatures::parse("local-callables").unwrap(),
782        };
783        let union = sources.union();
784        for feature in [PreviewFeature::HybridSearch, PreviewFeature::Ontology] {
785            assert!(union.enabled(feature), "{}", feature.kebab_name());
786        }
787        // A feature no source carries is off, and an empty set of
788        // sources derives nothing.
789        assert!(!union.enabled(PreviewFeature::Float16CoordinateTypes));
790        assert_eq!(PreviewSources::default().union(), PreviewFeatures::none());
791        // The parts stay separable: each source reports only its own.
792        assert!(sources.env.enabled(PreviewFeature::HybridSearch));
793        assert!(!sources.env.enabled(PreviewFeature::Ontology));
794        assert!(sources.config.enabled(PreviewFeature::Ontology));
795    }
796
797    #[test]
798    fn the_carriers_report_every_enabling_source_in_order() {
799        // ADR-0719 decision 6: the provenance names exactly the enabling
800        // carriers, in order — and none for a feature no source carries.
801        let stacked = PreviewSources {
802            env: PreviewFeatures::parse("ontology").unwrap(),
803            option: PreviewFeatures::parse("ontology").unwrap(),
804            ..PreviewSources::default()
805        };
806        assert_eq!(
807            stacked
808                .carriers(PreviewFeature::Ontology)
809                .collect::<Vec<_>>(),
810            [PreviewSource::Env, PreviewSource::Option]
811        );
812        assert_eq!(stacked.carriers(PreviewFeature::HybridSearch).count(), 0);
813    }
814
815    #[test]
816    fn from_names_resolves_each_name_without_the_comma_grammar() {
817        // A list item is one name: a comma inside it is an unknown name,
818        // never two features (ADR-0719 — the config's typed list).
819        let error = PreviewFeatures::from_names("src", ["ontology,coll-zip"]).unwrap_err();
820        assert!(
821            error
822                .to_string()
823                .contains("unknown preview feature 'ontology,coll-zip'"),
824            "{error}"
825        );
826        // An empty name is unknown, not skipped; no names enable nothing.
827        assert!(PreviewFeatures::from_names("src", [""]).is_err());
828        assert_eq!(
829            PreviewFeatures::from_names("src", []).unwrap(),
830            PreviewFeatures::none()
831        );
832        assert!(PreviewFeatures::from_names("src", ["ontology", "coll-zip"])
833            .unwrap()
834            .enabled(PreviewFeature::CollectionZip));
835    }
836}