relate-executor 1.3.0

In-memory graph and Cypher physical executor
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
//! The schema-DDL `OPTIONS` module — the one owner of every option rule a
//! `CREATE INDEX`/`CREATE CONSTRAINT` carries: the outer map's key/class
//! policy and its literal-vs-parameter resolution (ADR-0489), the
//! `CREATE INDEX` target shape, and the per-kind `indexConfig` vocabulary.
//!
//! Every rejection here is either the statement *shape* rule (Neo4j's
//! front-end `SemanticError.*` constructions, surfaced as `SyntaxError`) or
//! the run-time argument validator's (`ArgumentError`). For the
//! `indexConfig` *value* path it is always the latter: live Neo4j reports
//! `Neo.ClientError.General.InvalidArguments` for a non-map or foreign
//! config and `Neo.ClientError.Statement.ArgumentError` for an unknown
//! setting or analyzer name — both the openCypher `ArgumentError` class
//! (live-verified 2026-11-02/03 on neo4j:2026.09-enterprise).

use std::collections::{BTreeMap, HashSet};
use std::hash::Hash;

use relate_core::{Error, Result, Value};
use relate_parser::{IndexKind, OptionsForm};

use crate::eval::eval;
use crate::exec::fulltext::Analyzer;
use crate::overlay::ExecGraph;
use crate::row::Row;

// ---------------------------------------------------------------------
// The shared `indexConfig` vocabulary (ADR-0489)
// ---------------------------------------------------------------------

/// The one outer `OPTIONS` key every index kind admits and records; the
/// inner per-kind schema lives in [`create_config`] and the vector
/// feature module, the stored read in `exec::vector::stored_config`.
pub(crate) const KEY_INDEX_CONFIG: &str = "indexConfig";

/// The one non-MAP `indexConfig` rejection: every index kind's config slot
/// rejects a non-map the same way, so the sentence is shared rather than
/// re-authored per kind (live Neo4j reports
/// `Neo.ClientError.General.InvalidArguments` for all of them, ADR-0489).
pub(crate) const INDEX_CONFIG_NOT_A_MAP: &str = "Invalid input for 'indexConfig'. Expected a MAP.";

/// One navigation of the `indexConfig` option — Map or absent, anything
/// else is rejected at this boundary, never silently dropped. A borrow: the
/// one mutating consumer (the vector CREATE defaults) clones at its point of
/// mutation.
pub(crate) fn index_config(
    options: &BTreeMap<String, Value>,
) -> Result<Option<&BTreeMap<String, Value>>> {
    Ok(index_config_or(options, &|_| {
        // ADR-0489: a rejected `indexConfig` value is the DDL argument
        // validator's failure (Neo4j `Neo.ClientError.General.
        // InvalidArguments`), not a statement-shape syntax error.
        Error::argument_error(INDEX_CONFIG_NOT_A_MAP)
    })?
    .map(|(_, map)| map))
}

/// [`index_config`] with the caller's own non-map rejection: a surface whose
/// authored text names the offending value builds it here rather than
/// navigating the key a second time. The found value rides with the map, so
/// a rejection naming the whole `indexConfig` value needs no re-rendering.
pub(crate) fn index_config_or<'a>(
    options: &'a BTreeMap<String, Value>,
    rejected: &dyn Fn(&Value) -> Error,
) -> Result<Option<(&'a Value, &'a BTreeMap<String, Value>)>> {
    match options.get(KEY_INDEX_CONFIG) {
        None => Ok(None),
        Some(value @ Value::Map(map)) => Ok(Some((value, map.as_ref()))),
        Some(value) => Err(rejected(value)),
    }
}

// ---------------------------------------------------------------------
// Outer OPTIONS key policy and resolution (ADR-0489)
// ---------------------------------------------------------------------

/// The outer `OPTIONS` allowlist every schema DDL command admits, in both
/// spellings. Cypher 25 removed `indexProvider`, so `indexConfig` is the
/// only key. A literal spelling is the front end's syntax-class rejection
/// before its value expression is lowered (an absent parameter in the value
/// slot must not change the class); a whole-map parameter carrying a foreign
/// key is the argument validator's rejection after resolution — the same
/// allowlist, the class differing by provenance.
pub(crate) const ADMITTED_OPTION_KEYS: &[&str] = &[KEY_INDEX_CONFIG];

/// Live's rejection text for a non-admitted `OPTIONS` key: name the key and
/// the admitted spelling(s), rendered from [`ADMITTED_OPTION_KEYS`] so the
/// text and the allowlist cannot drift. `indexProvider` was deprecated and
/// then removed upstream, so the schema DDL resolvers read the same text
/// for every non-admitted key. The *class* stays by provenance — a literal
/// key is the front end's `SyntaxError`, a whole-map parameter's is the
/// argument validator's `ArgumentError` — matching live 2026.10.1's driver
/// codes; the GQL status (22N04) rides inside live's message, which is why
/// this text names no code of its own.
pub(crate) fn rejected_option_key_message(key: &str) -> String {
    let expected = ADMITTED_OPTION_KEYS
        .iter()
        .map(|admitted| format!("'{admitted}'"))
        .collect::<Vec<_>>()
        .join(", ");
    format!("Invalid input '{key}' for 'OPTIONS'. Expected {expected}.")
}

/// The literal-spelling rejection the schema DDL resolvers share: the front
/// end's syntax class carrying the pinned text.
fn literal_option_key(key: &str) -> Error {
    Error::syntax(rejected_option_key_message(key))
}

/// The parameter-spelling twin: the argument validator's class, its message
/// key lowercased as live does.
fn parameter_option_key(key: &str) -> Error {
    Error::argument_error(rejected_option_key_message(&key.to_lowercase()))
}

/// The schema DDL resolvers' one key policy (the index and constraint
/// twins): the shared allowlist, the syntax class for a literal foreign
/// key, the argument class for a whole-map parameter's.
fn ddl_option_key_policy() -> OptionKeyPolicy<'static> {
    OptionKeyPolicy {
        admitted: ADMITTED_OPTION_KEYS,
        literal: &literal_option_key,
        parameter: &parameter_option_key,
    }
}

/// The one whole-map `OPTIONS $param` → map invariant: an absent parameter
/// is `ParameterMissing` (ADR-0308), a non-MAP is the run-time argument
/// validator's `ArgumentError` carrying the caller's text (ADR-0489). The
/// schema DDL resolvers and the graph-type resolver share it, so no caller
/// re-spells the two rejections.
pub(crate) fn parameter_map<'a>(
    params: &'a BTreeMap<String, Value>,
    parameter: &str,
    not_a_map: &str,
) -> Result<&'a BTreeMap<String, Value>> {
    match params.get(parameter) {
        Some(Value::Map(map)) => Ok(map),
        None => Err(Error::parameters_missing([parameter])),
        Some(_) => Err(Error::argument_error(not_a_map)),
    }
}

/// The outer-map key policy [`resolve_options`] applies: the admitted keys
/// and the rejection each spelling raises for a foreign key. The class and
/// wording differ by surface -- the statement's own front end rejects a
/// literal foreign key as a syntax error, a whole-map parameter's foreign
/// key is the argument validator's, and the graph-type body reports its
/// kinds' own messages in both spellings -- so the caller supplies them.
pub(crate) struct OptionKeyPolicy<'a> {
    /// The keys the calling command admits.
    pub(crate) admitted: &'a [&'a str],
    /// The literal-spelling rejection for a foreign key.
    pub(crate) literal: &'a dyn Fn(&str) -> Error,
    /// The resolved-parameter-spelling rejection for a foreign key.
    pub(crate) parameter: &'a dyn Fn(&str) -> Error,
}

/// The one `OPTIONS` resolution sequence (ADR-0489), shared by
/// `CREATE CONSTRAINT`, `CREATE INDEX` and the graph-type body, one arm per
/// form:
///
/// - `Absent` yields no options;
/// - `Literal` checks every key against the policy *before* any value
///   expression is lowered (so a shape rejection wins over an absent
///   parameter in a value slot), then lowers and evaluates the values;
/// - `Parameter` resolves the whole map (absent → `ParameterMissing`,
///   non-MAP → `ArgumentError`), then checks its keys against the policy.
pub(crate) fn resolve_options(
    graph: &ExecGraph<'_>,
    form: &OptionsForm,
    params: &BTreeMap<String, Value>,
    policy: &OptionKeyPolicy<'_>,
    not_a_map: &'static str,
) -> Result<BTreeMap<String, Value>> {
    let mut options = BTreeMap::new();
    match form {
        OptionsForm::Absent => {}
        OptionsForm::Literal(entries) => {
            if let Some((key, _)) = entries
                .iter()
                .find(|(key, _)| !policy.admitted.contains(&key.as_str()))
            {
                return Err((policy.literal)(key));
            }
            for (key, expression) in entries {
                options.insert(
                    key.clone(),
                    eval(
                        graph,
                        &Row::new(),
                        &relate_front::lower_expr(expression)?,
                        params,
                    )?,
                );
            }
        }
        OptionsForm::Parameter(parameter) => {
            options = parameter_map(params, parameter, not_a_map)?.clone();
            // The resolved map has no value expressions, so its keys are
            // checked after resolution; that provenance is the argument
            // validator's class.
            if let Some(key) = options
                .keys()
                .find(|key| !policy.admitted.contains(&key.as_str()))
            {
                return Err((policy.parameter)(key));
            }
        }
    }
    Ok(options)
}

/// The `CREATE CONSTRAINT` options shape (ADR-0489): an
/// index-backed constraint admits only `indexConfig`, and any other literal
/// key is the front end's syntax error, rejected before the value
/// expression is lowered and before the schema-conflict checks run. A
/// rejected `indexConfig` *value*, and every rejection reached through a
/// whole-map `OPTIONS $param` (including a non-map parameter), is the
/// argument validator's `ArgumentError`. EXISTENCE and PROPERTY TYPE
/// constraints admit no options at all: any entry is rejected, whether
/// written literally or supplied by the parameter (live-verified 2026-11-02
/// on neo4j:2026.09-enterprise). Running before the conflict gate makes the
/// shape class win over an equivalent rule, matching Neo4j's compile-time
/// ordering.
pub(crate) fn validate_constraint_options(
    graph: &ExecGraph<'_>,
    c: &relate_parser::CreateConstraintClause,
    constraint_type: relate_model::ConstraintType,
    params: &BTreeMap<String, Value>,
) -> Result<()> {
    let options = resolve_options(
        graph,
        &c.options,
        params,
        &ddl_option_key_policy(),
        "Could not create constraint with options: expected a map value.",
    )?;
    // EXISTENCE and PROPERTY TYPE constraints admit no options at all
    // (Neo4j 22N81): an empty map is accepted, any entry is not.
    if matches!(
        constraint_type,
        relate_model::ConstraintType::Exists | relate_model::ConstraintType::PropertyType
    ) {
        return if options.is_empty() {
            Ok(())
        } else {
            Err(Error::argument_error(
                "InvalidOptionsMap: this constraint has no valid options values",
            ))
        };
    }
    // The one admitted value shape: an empty `indexConfig` map, navigated
    // through the module's one accessor.
    if index_config(&options)?.is_some_and(|config| !config.is_empty()) {
        return Err(Error::argument_error("InvalidOptionsMap"));
    }
    Ok(())
}

// ---------------------------------------------------------------------
// CREATE INDEX target shape
// ---------------------------------------------------------------------

/// The kinds that take exactly one property, with the rejection each raises
/// when the count differs (Neo4j's two messages, live-verified): POINT/TEXT
/// report the property-count rule in the front end, VECTOR reports its own
/// unsupported-shape error. One table, consulted once.
fn single_property_rejection(kind: IndexKind) -> Option<&'static str> {
    match kind {
        IndexKind::Point | IndexKind::Text => {
            Some("InvalidArguments: this index type requires one property")
        }
        IndexKind::Vector => Some("UnsupportedIndexOrConstraint"),
        IndexKind::Range | IndexKind::Fulltext | IndexKind::Lookup => None,
    }
}

/// The duplicated-token policy: no token repeats within its vocabulary.
fn has_duplicates<'a, T: Hash + Eq + 'a>(mut items: impl Iterator<Item = &'a T>) -> bool {
    let mut seen = HashSet::new();
    items.any(|item| !seen.insert(item))
}

/// The label text the catalog records for a `CREATE INDEX` clause — the
/// one place the label-less rule lives. A LOOKUP index is the one
/// label-less form (the legacy catalog encoding stores it with an empty
/// label); every other kind must name a label or relationship type, a
/// statement-shape `SyntaxError` — never a fabricated empty label.
pub(crate) fn index_label(c: &relate_parser::CreateIndexClause) -> Result<String> {
    match c.labels.first() {
        Some(label) => Ok(label.to_string()),
        None if c.kind == IndexKind::Lookup => Ok(String::new()),
        None => Err(Error::syntax(
            "a non-LOOKUP index must name a label or relationship type",
        )),
    }
}

/// The `CREATE INDEX` target-shape policy: the single-property kinds'
/// property count and the duplicated-token rule (22N76 — the label and the
/// property vocabularies are separate sets, each without duplicates, for
/// every index kind), and the label-less rule (LOOKUP only). Runs before the OPTIONS shape so a target rejection
/// wins over a config one.
fn validate_index_target(c: &relate_parser::CreateIndexClause) -> Result<()> {
    if let Some(detail) = single_property_rejection(c.kind) {
        if c.properties.len() != 1 {
            return Err(Error::syntax(detail));
        }
    }
    // Raised before the conflict gate so `IF NOT EXISTS` can never mask it.
    index_label(c)?;
    if has_duplicates(c.labels.iter())
        || has_duplicates(c.properties.iter().chain(&c.with_properties))
    {
        return Err(Error::semantic("IndexContainsDuplicatedTokens"));
    }
    Ok(())
}

/// The committed-schema path's per-kind index options resolution
/// (ADR-0649 §6): the same per-kind `ConfigPolicy` a `CREATE INDEX`
/// runs, over the flat option payload a committed ontology envelope
/// carries. Nests the payload under `indexConfig` (the one key the
/// engine's stored readers navigate), validates the kind's vocabulary
/// and values — refusing what a CREATE would reject — and completes
/// the kind's defaults, returning the resolved options map the
/// catalog detail records. Public for the facade's open-tail
/// application (`relate::committed`), the one external consumer: the
/// committed file is untrusted input, and its option payloads get the
/// DDL path's own validation rather than a parallel one.
pub fn resolve_committed_index_options(
    kind: crate::redo::IndexKindSpec,
    flat: BTreeMap<String, Value>,
) -> Result<BTreeMap<String, Value>> {
    let mut options = BTreeMap::new();
    options.insert(KEY_INDEX_CONFIG.to_string(), Value::Map(flat.into()));
    ConfigPolicy::for_kind(kind.into()).validate(&mut options)?;
    Ok(options)
}

/// One committed index as the facade's open tail hands it to the DDL
/// home (ADR-0649 §6): the catalog row's identity, its typed detail,
/// and its evaluated options — borrowed from the codec's carrier, so
/// no second owned spelling of the carrier exists.
pub struct CommittedIndexFact<'a> {
    pub name: &'a str,
    pub detail: &'a crate::redo::IndexDetailSpec,
    pub options: &'a BTreeMap<String, Value>,
}

/// The committed schema's catalog redo group (ADR-0649 §6) — the DDL
/// home's own construction, so the catalog policy (the op order, the
/// detail shape, the option resolution, the held-row retirement) has
/// one compiler-linked home with `CREATE INDEX`: a new index kind,
/// WITH-property rule, or op order added to DDL reaches the store's
/// open path through this function, never through a parallel
/// assembly. Each committed index first retires every catalog row held
/// under its name or its indexed pair (the committed file is the
/// source and wins, ADR-0649 decision 2 — a file edit that retargets
/// or renames an index overrides the machine's stale row the way any
/// later commit would, instead of failing the open on the catalog's
/// duplicate rules), then records the row and its typed detail in the
/// DDL path's own order; the group ends at the current graph type.
pub fn committed_catalog_ops(
    held: &[relate_catalog::IndexDef],
    indexes: &[CommittedIndexFact<'_>],
    graph_type: &relate_engine_api::graph_type::GraphTypeSpec,
) -> Result<Vec<crate::redo::RedoOp>> {
    use crate::redo::RedoOp;
    let mut ops = Vec::with_capacity(indexes.len() * 3 + 1);
    for index in indexes {
        // The carrier's stated contract (relate-storage's
        // `CommittedIndex`): every producer refuses label-less and
        // non-single-property entries — the typed refusal here is the
        // boundary's own check, so a future producer that misses it
        // fails the open, never panics it.
        let [label] = index.detail.labels.as_slice() else {
            return Err(Error::storage(format!(
                "the committed schema's index '{}' declares no or multiple labels",
                index.name
            )));
        };
        let [property] = index.detail.properties.as_slice() else {
            return Err(Error::storage(format!(
                "the committed schema's index '{}' declares no or multiple properties",
                index.name
            )));
        };
        // The pair half is the one pair predicate
        // (`holds_index_pair`: the legacy encoding's own decoder), so
        // a row any producer wrote retires — a raw string equality
        // would only ever match this function's own previous rows.
        for stale in held.iter().filter(|held| {
            held.name == index.name || crate::redo::holds_index_pair(held, label, property)
        }) {
            ops.push(RedoOp::DropIndex {
                name: stale.name.clone(),
            });
        }
        // The row records the same legacy-encoded property the DDL
        // create side records (`legacy_property_encoding`), so a
        // committed index and the equivalent `CREATE INDEX` install
        // byte-identical catalog rows and the catalog's own
        // pair-keyed comparisons see them as the same pair.
        ops.push(RedoOp::CreateIndex {
            name: index.name.to_string(),
            label: label.clone(),
            property: crate::redo::legacy_property_encoding(
                property,
                index.detail.kind,
                index.name,
            ),
        });
        // The option payloads get the per-kind resolution a CREATE
        // INDEX runs — the committed file is untrusted input, and an
        // option a CREATE would reject refuses here.
        let options = resolve_committed_index_options(index.detail.kind, index.options.clone())?;
        ops.push(crate::exec::ddl::index_detail_op(
            index.name,
            index.detail.clone(),
            &options,
        ));
    }
    ops.push(RedoOp::SetCurrentGraphType {
        body: graph_type.clone(),
    });
    Ok(ops)
}

/// The `CREATE INDEX` options shape (ADR-0489), the `CREATE CONSTRAINT`
/// twin's counterpart: the target shape, the shared `OPTIONS` resolution
/// (whose allowlist excludes `indexProvider` in both spellings), and the
/// per-kind `indexConfig` policy. Returns the resolved options map the
/// catalog detail records. Runs before the conflict gate so an `IF NOT
/// EXISTS`/equivalent-rule skip can never mask a shape rejection.
pub(crate) fn resolve_index_options(
    graph: &ExecGraph<'_>,
    c: &relate_parser::CreateIndexClause,
    params: &BTreeMap<String, Value>,
) -> Result<BTreeMap<String, Value>> {
    validate_index_target(c)?;
    let mut options = resolve_options(
        graph,
        &c.options,
        params,
        &ddl_option_key_policy(),
        "InvalidInputValue: OPTIONS parameter must be a MAP",
    )?;
    // Validation and the kind's defaults are the one policy's two halves.
    ConfigPolicy::for_kind(c.kind).validate(&mut options)?;
    Ok(options)
}

// ---------------------------------------------------------------------
// Per-kind indexConfig vocabulary
// ---------------------------------------------------------------------

/// One value shape an `indexConfig` setting admits.
#[derive(Clone, Copy)]
enum ValueShape {
    /// A list of numbers (a POINT index's spatial bound).
    NumericList,
    /// One of the fulltext analyzer names.
    Analyzer,
    /// A boolean.
    Boolean,
}

impl ValueShape {
    fn check(self, key: &str, value: &Value) -> Result<()> {
        match self {
            Self::NumericList => {
                if matches!(
                    value,
                    Value::List(items)
                        if items.iter().all(|item| matches!(item, Value::Float(_) | Value::Int(_)))
                ) {
                    Ok(())
                } else {
                    Err(Error::argument_error(
                        "Invalid input for 'indexConfig'. Expected to be MAP<STRING, LIST<FLOAT>>.",
                    ))
                }
            }
            Self::Analyzer => match value {
                Value::String(name) if Analyzer::from_name(name).is_some() => Ok(()),
                _ => Err(Error::argument_error(format!(
                    "Invalid input for analyzer name: {value:?}"
                ))),
            },
            Self::Boolean => {
                if matches!(value, Value::Bool(_)) {
                    Ok(())
                } else {
                    Err(Error::argument_error(format!(
                        "Invalid input for '{key}'. Expected a boolean."
                    )))
                }
            }
        }
    }
}

/// One index kind's `indexConfig` family: the settings it admits and the
/// prefixes of the families other kinds own. The shared loop in
/// [`validate_config_family`] is the only control flow.
struct ConfigFamily {
    keys: &'static [(&'static str, ValueShape)],
    /// Key prefixes that name another index kind's config — rejected as a
    /// foreign family, never as an unknown setting.
    foreign_prefixes: &'static [&'static str],
    /// Completes "Expected {…}." in the foreign-family rejection.
    foreign_expected: &'static str,
}

/// The point index's `indexConfig` keys: two-dimensional and 3D bounds in
/// the cartesian and WGS-84 coordinate systems (Neo4j's live allowlist,
/// 2026.09).
const POINT_FAMILY: ConfigFamily = ConfigFamily {
    keys: &[
        ("spatial.cartesian.min", ValueShape::NumericList),
        ("spatial.cartesian.max", ValueShape::NumericList),
        ("spatial.cartesian-3d.min", ValueShape::NumericList),
        ("spatial.cartesian-3d.max", ValueShape::NumericList),
        ("spatial.wgs-84.min", ValueShape::NumericList),
        ("spatial.wgs-84.max", ValueShape::NumericList),
        ("spatial.wgs-84-3d.min", ValueShape::NumericList),
        ("spatial.wgs-84-3d.max", ValueShape::NumericList),
    ],
    foreign_prefixes: &["fulltext.", "vector."],
    foreign_expected: "a spatial bound",
};

/// The `indexConfig` key naming a fulltext index's analyzer.
pub(crate) const KEY_FULLTEXT_ANALYZER: &str = "fulltext.analyzer";

/// The one stored-setting reader every typed read-side reader is a single
/// call of: navigate the outer `indexConfig` (the one [`index_config`]
/// boundary, its non-map rejection mapped to the shared drift error),
/// find the stored setting by key, then narrow — absent answers the
/// caller's default, a value the caller's typed reading fails to narrow
/// is the drift rejection. The create-time validation would have
/// rejected a stored shape this reader cannot narrow, so the rejection
/// is catalog drift, never a silently unconfigured index.
fn stored_setting<T>(
    options: &BTreeMap<String, Value>,
    index_name: &str,
    key: &str,
    default: T,
    narrow: impl Fn(&Value) -> Option<T>,
) -> Result<T> {
    let drift = || {
        Error::execution(format!(
            "InvalidIndexDefinition: fulltext index {index_name} has an invalid indexConfig option"
        ))
    };
    let config = index_config(options).map_err(|_| drift())?;
    match config.and_then(|config| config.get(key)) {
        None => Ok(default),
        Some(value) => narrow(value).ok_or_else(drift),
    }
}

/// The analyzer a stored fulltext index was created with: its
/// [`KEY_FULLTEXT_ANALYZER`] setting, the standard analyzer when absent.
pub(crate) fn index_analyzer(
    options: &BTreeMap<String, Value>,
    index_name: &str,
) -> Result<Analyzer> {
    stored_setting(
        options,
        index_name,
        KEY_FULLTEXT_ANALYZER,
        Analyzer::Standard,
        |value| match value {
            Value::String(name) => Analyzer::from_name(name),
            _ => None,
        },
    )
}

/// The `indexConfig` key naming a fulltext index's eventual consistency.
pub(crate) const KEY_FULLTEXT_EVENTUALLY_CONSISTENT: &str = "fulltext.eventually_consistent";

/// Whether a stored fulltext index was created eventually consistent: its
/// [`KEY_FULLTEXT_EVENTUALLY_CONSISTENT`] setting, `false` when absent.
/// The SEARCH clause rejects such an index (ADR-0680); the
/// `db.index.fulltext.query*` procedures are its supported surface.
pub(crate) fn index_eventually_consistent(
    options: &BTreeMap<String, Value>,
    index_name: &str,
) -> Result<bool> {
    stored_setting(
        options,
        index_name,
        KEY_FULLTEXT_EVENTUALLY_CONSISTENT,
        false,
        |value| match value {
            Value::Bool(eventually_consistent) => Some(*eventually_consistent),
            _ => None,
        },
    )
}

/// The fulltext index's two `indexConfig` settings.
const FULLTEXT_FAMILY: ConfigFamily = ConfigFamily {
    // The key vocabulary is the read side's (these constants); the create
    // side owns only the value shapes.
    keys: &[
        (KEY_FULLTEXT_ANALYZER, ValueShape::Analyzer),
        (KEY_FULLTEXT_EVENTUALLY_CONSISTENT, ValueShape::Boolean),
    ],
    foreign_prefixes: &["spatial.", "vector."],
    foreign_expected: "'fulltext.analyzer' or 'fulltext.eventually_consistent'",
};

/// The create side of the vector option schema, the read side's mirror
/// (`exec::vector::stored_config`): one adjacent pipeline — navigate the
/// outer `indexConfig` (Map or absent, anything else is rejected at the
/// [`index_config`] boundary), parse (the typed DDL errors), apply the
/// DDL defaults, and return the canonical `indexConfig` value to store
/// under [`KEY_INDEX_CONFIG`]. The parse and the defaults are the root
/// schema's ([`crate::vector_config`]) — a root module this exec file
/// imports downward, never the reverse (LABS-845).
fn create_config(options: &BTreeMap<String, Value>) -> Result<Value> {
    let mut config = index_config(options)?.cloned().unwrap_or_default();
    let parsed = crate::vector_config::parse_config(&config)?;
    crate::vector_config::apply_defaults(&mut config, &parsed);
    Ok(Value::Map(config.into()))
}

/// The per-kind `indexConfig` value policy: one variant per validation
/// strategy, so every kind — VECTOR included — has exactly one policy.
enum ConfigPolicy {
    /// The kind consumes no config: absent or empty is fine, anything else
    /// is rejected.
    Nothing { non_empty: &'static str },
    /// A key/value family, validated by the shared loop, then completed
    /// with the kind's default config so SHOW INDEXES' `options` and
    /// `createStatement` carry Neo4j's shape; a caller-supplied entry wins.
    /// The per-kind table is `IndexKindSpec::default_config`, not a match
    /// here.
    Family {
        family: &'static ConfigFamily,
        kind: crate::redo::IndexKindSpec,
    },
    /// VECTOR: the typed parse and the DDL defaults are
    /// [`create_config`]'s navigate-and-default pipeline.
    Vector,
}

impl ConfigPolicy {
    /// The kind's value policy — one variant per kind, no absent mode.
    fn for_kind(kind: IndexKind) -> Self {
        match kind {
            IndexKind::Lookup => Self::Nothing {
                non_empty: "Invalid input for index config. Expected nothing.",
            },
            IndexKind::Range | IndexKind::Text => Self::Nothing {
                non_empty: "InvalidIndexConfig",
            },
            IndexKind::Point => Self::Family {
                family: &POINT_FAMILY,
                kind: crate::redo::IndexKindSpec::from(kind),
            },
            IndexKind::Fulltext => Self::Family {
                family: &FULLTEXT_FAMILY,
                kind: crate::redo::IndexKindSpec::from(kind),
            },
            IndexKind::Vector => Self::Vector,
        }
    }

    /// Validate the resolved options map's `indexConfig` entry (absent = no
    /// config), navigating the one [`index_config`] boundary itself so every
    /// variant — the mutating VECTOR one included — shares the same entry
    /// point.
    fn validate(&self, options: &mut BTreeMap<String, Value>) -> Result<()> {
        match self {
            Self::Nothing { non_empty } => match index_config(options)? {
                None => Ok(()),
                Some(map) if map.is_empty() => Ok(()),
                Some(_) => Err(Error::argument_error(*non_empty)),
            },
            Self::Family { family, kind } => {
                // One navigation: validate the working map, then complete
                // it with the kind's defaults.
                let mut config = index_config(options)?.cloned().unwrap_or_default();
                validate_config_family(&config, family)?;
                if let Some(defaults) = kind.default_config() {
                    defaults(&mut config);
                    options.insert(KEY_INDEX_CONFIG.into(), Value::Map(config.into()));
                }
                Ok(())
            }
            Self::Vector => {
                let config = create_config(options)?;
                options.insert(KEY_INDEX_CONFIG.into(), config);
                Ok(())
            }
        }
    }
}

/// The shared per-key loop of a config family: lowercase, the foreign-family
/// prefix rejection, the table lookup, and the value shape.
fn validate_config_family(map: &BTreeMap<String, Value>, family: &ConfigFamily) -> Result<()> {
    for (key, value) in map.iter() {
        let lowered = key.to_ascii_lowercase();
        if family
            .foreign_prefixes
            .iter()
            .any(|prefix| lowered.starts_with(prefix))
        {
            return Err(Error::argument_error(format!(
                "Invalid input '{key}' for index config. Expected {}.",
                family.foreign_expected
            )));
        }
        let Some((_, shape)) = family.keys.iter().find(|(name, _)| *name == lowered) else {
            let expected: Vec<&str> = family.keys.iter().map(|(name, _)| *name).collect();
            return Err(Error::argument_error(format!(
                "Invalid input '{key}' for index setting. Expected one of {}.",
                expected.join(", ")
            )));
        };
        shape.check(key, value)?;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use relate_parser::SchemaEntityType;

    fn clause(
        kind: IndexKind,
        labels: Vec<relate_names::SmallName>,
    ) -> relate_parser::CreateIndexClause {
        relate_parser::CreateIndexClause {
            name: None,
            entity_type: SchemaEntityType::Node,
            labels,
            properties: Vec::new(),
            if_not_exists: true,
            kind,
            on_each: false,
            with_properties: Vec::new(),
            options: OptionsForm::Absent,
        }
    }

    /// The label-less rejection is a statement-shape `SyntaxError`, raised by
    /// the target-shape policy that runs ahead of the conflict gate (even
    /// under `IF NOT EXISTS`); LOOKUP stays the one label-less form.
    #[test]
    fn a_label_less_non_lookup_index_is_a_syntax_error_before_the_gate() {
        let err = validate_index_target(&clause(IndexKind::Range, Vec::new()))
            .expect_err("label-less RANGE must be rejected");
        assert!(matches!(err, Error::Syntax(_)), "{err:?}");
        validate_index_target(&clause(IndexKind::Lookup, Vec::new())).unwrap();
    }
}