Skip to main content

relate_engine_api/redo/
index.rs

1//! The index-DDL payload family: the typed index kind, the serving-pair
2//! predicates, the legacy property encoding, and the detail spec its
3//! `CatalogIndexDetail` op carries. A private sibling re-exported at the
4//! `redo` root (the one-public-path pattern), so callers keep using
5//! `crate::redo::…`.
6
7use std::collections::BTreeMap;
8
9use relate_catalog::{ConstraintDef, IndexDef};
10use relate_core::Value;
11use serde::{Deserialize, Serialize};
12
13use super::RedoOp;
14
15/// The DDL index kind carried by [`IndexDetailSpec`]: a
16/// serde-serializable mirror of `relate_parser::IndexKind`.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
18pub enum IndexKindSpec {
19    Range,
20    Point,
21    Text,
22    Fulltext,
23    Lookup,
24    Vector,
25}
26
27impl IndexKindSpec {
28    /// Every variant; derived inverses (and their tests) iterate this so
29    /// the variant list is maintained in exactly one place.
30    pub const ALL: [IndexKindSpec; 6] = [
31        IndexKindSpec::Range,
32        IndexKindSpec::Point,
33        IndexKindSpec::Text,
34        IndexKindSpec::Fulltext,
35        IndexKindSpec::Lookup,
36        IndexKindSpec::Vector,
37    ];
38
39    /// The upper-case display name Neo4j's `SHOW INDEXES` `type` column
40    /// uses (same strings as `relate_parser::IndexKind::display_name`).
41    /// The `SHOW INDEXES` `type` column spelling — the parser's own display
42    /// name, so the six names live once in the crate that owns the dialect.
43    pub fn display_name(&self) -> &'static str {
44        relate_parser::IndexKind::from(*self).display_name()
45    }
46
47    /// Parse the display name back into the kind — the inverse of
48    /// [`IndexKindSpec::display_name`], used to recover the kind of
49    /// legacy catalog rows that predate `CatalogIndexDetail` from their
50    /// `{props}#{KIND}#{name}` property encoding. Derived from the one
51    /// string table in `display_name` so the two directions cannot drift.
52    pub fn from_display_name(name: &str) -> Option<Self> {
53        Self::ALL
54            .into_iter()
55            .find(|kind| kind.display_name() == name)
56    }
57
58    /// The Neo4j `SHOW INDEXES` `indexProvider` column value for this
59    /// kind. Exhaustive on purpose: a new index kind fails to compile
60    /// here instead of silently falling back to `range-1.0`.
61    pub fn provider_name(&self) -> &'static str {
62        match self {
63            IndexKindSpec::Range => "range-1.0",
64            IndexKindSpec::Point => "point-1.0",
65            IndexKindSpec::Text => "text-3.0",
66            IndexKindSpec::Fulltext => "fulltext-2.0",
67            IndexKindSpec::Lookup => "token-lookup-1.0",
68            IndexKindSpec::Vector => "vector-2026.08",
69        }
70    }
71
72    /// The DDL default `indexConfig` this kind records when the statement
73    /// names none — the one mutator the DDL layer applies. `None` for the
74    /// kinds whose default config is the empty map: RANGE, TEXT and LOOKUP
75    /// record none, and VECTOR's metric-dependent defaults are applied by
76    /// `vector_config::apply_defaults` through the vector OPTIONS pipeline
77    /// (`catalog_schema::create_config`), which is why this table omits it.
78    /// The table lives beside [`IndexKindSpec::display_name`] and
79    /// [`IndexKindSpec::provider_name`] so a new kind states its default
80    /// here, never in a `_`-glued match one layer above.
81    pub fn default_config(&self) -> Option<fn(&mut BTreeMap<String, Value>)> {
82        match self {
83            IndexKindSpec::Point => Some(apply_point_defaults),
84            IndexKindSpec::Fulltext => Some(apply_fulltext_defaults),
85            IndexKindSpec::Range
86            | IndexKindSpec::Text
87            | IndexKindSpec::Lookup
88            | IndexKindSpec::Vector => None,
89        }
90    }
91
92    /// The one LOOKUP discrimination: a LOOKUP index carries no
93    /// label/property tokens. Every LOOKUP reader — the row's null-ed
94    /// `labelsOrTypes`/`properties` cells, the createStatement's EACH form,
95    /// the notification descriptor's tail — asks this, never its own
96    /// `matches!`.
97    pub fn is_lookup(&self) -> bool {
98        matches!(self, IndexKindSpec::Lookup)
99    }
100
101    /// The kind of one index row, resolved once — the detail's kind when the
102    /// detail join hits, else the legacy `{props}#{KIND}#{name}` encoding's
103    /// kind for a detail-less legacy WAL/checkpoint row (`catalog_create_index`
104    /// writes both redo ops in one statement today), else RANGE. The one
105    /// resolution every kind reader consults — the kind filter, the row's
106    /// type/provider columns and LOOKUP nulling, the createStatement's own
107    /// `detail.kind`, and the planner-IR diagnostic table's `type` cell.
108    /// The RANGE default covers exactly the encoding's two no-kind shapes:
109    /// the bare pre-encoding form (`name`, written before kinds existed —
110    /// RANGE by history, the only kind that era stored) and an unparseable
111    /// kind segment (`name#NOTAKIND#idx`, pinned to no kind by the redo
112    /// decoder's own tests). The second cannot occur in a store this engine
113    /// wrote — [`legacy_property_encoding`] only ever embeds a valid
114    /// [`IndexKindSpec`] — so the default never fabricates a kind over a
115    /// reachable row.
116    pub fn resolve(detail: Option<&IndexDetailSpec>, legacy_property: &str) -> Self {
117        detail
118            .map(|detail| detail.kind)
119            .or_else(|| split_legacy_property_encoding(legacy_property).1)
120            .unwrap_or(IndexKindSpec::Range)
121    }
122}
123
124/// The spatial bounds Neo4j records for a `POINT` index that names none:
125/// one key per coordinate reference system, each a `[min…]`/`[max…]` list.
126fn apply_point_defaults(config: &mut BTreeMap<String, Value>) {
127    const DEFAULTS: &[(&str, &[f64])] = &[
128        ("spatial.cartesian.min", &[-1000000.0, -1000000.0]),
129        ("spatial.cartesian.max", &[1000000.0, 1000000.0]),
130        (
131            "spatial.cartesian-3d.min",
132            &[-1000000.0, -1000000.0, -1000000.0],
133        ),
134        (
135            "spatial.cartesian-3d.max",
136            &[1000000.0, 1000000.0, 1000000.0],
137        ),
138        ("spatial.wgs-84.min", &[-180.0, -90.0]),
139        ("spatial.wgs-84.max", &[180.0, 90.0]),
140        ("spatial.wgs-84-3d.min", &[-180.0, -90.0, -1000000.0]),
141        ("spatial.wgs-84-3d.max", &[180.0, 90.0, 1000000.0]),
142    ];
143    for (key, values) in DEFAULTS {
144        let coordinates = values
145            .iter()
146            .map(|value| Value::Float(*value))
147            .collect::<Vec<_>>();
148        config
149            .entry((*key).to_string())
150            .or_insert_with(|| Value::List(coordinates.into()));
151    }
152}
153
154/// The fulltext config Neo4j records when the statement names none.
155fn apply_fulltext_defaults(config: &mut BTreeMap<String, Value>) {
156    config
157        .entry("fulltext.analyzer".to_string())
158        .or_insert_with(|| Value::String("standard-no-stop-words".into()));
159    config
160        .entry("fulltext.eventually_consistent".to_string())
161        .or_insert(Value::Bool(false));
162}
163
164impl From<IndexKindSpec> for relate_parser::IndexKind {
165    fn from(kind: IndexKindSpec) -> Self {
166        match kind {
167            IndexKindSpec::Range => relate_parser::IndexKind::Range,
168            IndexKindSpec::Point => relate_parser::IndexKind::Point,
169            IndexKindSpec::Text => relate_parser::IndexKind::Text,
170            IndexKindSpec::Fulltext => relate_parser::IndexKind::Fulltext,
171            IndexKindSpec::Lookup => relate_parser::IndexKind::Lookup,
172            IndexKindSpec::Vector => relate_parser::IndexKind::Vector,
173        }
174    }
175}
176
177impl From<relate_parser::IndexKind> for IndexKindSpec {
178    fn from(kind: relate_parser::IndexKind) -> Self {
179        match kind {
180            relate_parser::IndexKind::Range => IndexKindSpec::Range,
181            relate_parser::IndexKind::Point => IndexKindSpec::Point,
182            relate_parser::IndexKind::Text => IndexKindSpec::Text,
183            relate_parser::IndexKind::Fulltext => IndexKindSpec::Fulltext,
184            relate_parser::IndexKind::Lookup => IndexKindSpec::Lookup,
185            relate_parser::IndexKind::Vector => IndexKindSpec::Vector,
186        }
187    }
188}
189
190/// The index side of an ADR-0372 serving-pair check: the rule's kind,
191/// entity kind, labels, and properties, as the creating statement spells
192/// them (or as the materialized `index_details` record them).
193#[derive(Clone, Copy)]
194pub struct ServingPairIndex<'a> {
195    pub kind: IndexKindSpec,
196    pub relationship: bool,
197    pub labels: &'a [String],
198    pub properties: &'a [String],
199}
200
201/// The constraint side of an ADR-0372 serving-pair check.
202#[derive(Clone, Copy)]
203pub struct ServingPairConstraint<'a> {
204    pub backed: bool,
205    pub relationship: bool,
206    pub label: &'a str,
207    pub properties: &'a [String],
208}
209
210/// ADR-0372's serving-pair conflict, the one canonical form, owning the
211/// whole match: the pair's typed fields in, the verdict out. A schema rule
212/// pair conflicts only when the index kind is RANGE — the only kind that
213/// can serve a constraint's backing (ADR-0339) — and the constraint is
214/// index-backed (uniqueness/key), on the same label and properties.
215/// Property-type/existence constraints and FULLTEXT/VECTOR/POINT indexes
216/// coexist with everything. All three creation directions consult this; a
217/// change to the rule lands here once.
218pub fn serving_pair_conflicts(
219    index: ServingPairIndex<'_>,
220    constraint: ServingPairConstraint<'_>,
221) -> bool {
222    index.kind == IndexKindSpec::Range
223        && index.relationship == constraint.relationship
224        && index.labels.len() == 1
225        && constraint.label == index.labels[0]
226        && constraint.properties == index.properties
227        && constraint.backed
228}
229
230/// Decode a legacy `IndexDef.property` string: split the value `catalog_create_index`
231/// (and the constraint-backed index
232/// path) into its props head and index kind. A bare property name (no
233/// `#`) is its own head with no kind. The single decoder for this
234/// format — every reader of `IndexDef.property` goes through here.
235pub fn split_legacy_property_encoding(property: &str) -> (&str, Option<IndexKindSpec>) {
236    match property.split_once('#') {
237        None => (property, None),
238        Some((head, rest)) => (
239            head,
240            rest.split('#')
241                .next()
242                .and_then(IndexKindSpec::from_display_name),
243        ),
244    }
245}
246
247/// Encode an `IndexDef.property` in the legacy `{property}#{KIND}#{name}`
248/// format — the encoder half of [`split_legacy_property_encoding`], which
249/// decodes the result back to `(property, Some(kind))`.
250pub fn legacy_property_encoding(property: &str, kind: IndexKindSpec, name: &str) -> String {
251    format!("{property}#{}#{name}", kind.display_name())
252}
253
254/// Decode a legacy `IndexDef.property` string into its property-name
255/// list: the comma-join head of [`split_legacy_property_encoding`]
256/// split back into names (a bare single property name is its own
257/// one-element list). The list half of the format's decoder pair —
258/// every reader that wants the names (not the raw head) decodes through
259/// here, never an inline comma split one layer above the canonical
260/// decoder.
261pub fn legacy_property_names(property: &str) -> Vec<String> {
262    split_legacy_property_encoding(property)
263        .0
264        .split(',')
265        .map(str::to_string)
266        .collect()
267}
268
269/// One index's typed facts as every reader resolves them, through the fixed
270/// precedence the `SHOW INDEXES` row and the `00NA0` note share: the index's
271/// [`IndexDetailSpec`], then the owning constraint (a constraint-backed
272/// index), then the legacy [`IndexDef`] encoding. No reader re-spells the
273/// chain, so a new detail field lands in every rendering at once.
274#[derive(Clone, Debug, PartialEq, Eq)]
275pub struct IndexFacts {
276    pub kind: IndexKindSpec,
277    pub relationship: bool,
278    pub labels: Vec<String>,
279    pub properties: Vec<String>,
280    /// CIP-235 `WITH [...]` single-stage-filtering properties (VECTOR).
281    pub with_properties: Vec<String>,
282}
283
284impl IndexFacts {
285    /// Resolve one index's facts. `backing` is the index's index-backed
286    /// constraint of the same name, when the caller has already joined it
287    /// (the SHOW row); `None` elsewhere. A detail-less, constraint-less row
288    /// is the legacy encoding: a node index, its label from the
289    /// [`IndexDef`] and its properties from the encoding's head.
290    pub fn resolve(
291        index: &IndexDef,
292        detail: Option<&IndexDetailSpec>,
293        backing: Option<&ConstraintDef>,
294    ) -> Self {
295        let kind = IndexKindSpec::resolve(detail, &index.property);
296        let relationship = detail.is_some_and(|detail| detail.relationship)
297            || backing.is_some_and(|constraint| constraint.relationship);
298        if let Some(detail) = detail {
299            return Self {
300                kind,
301                relationship,
302                labels: detail.labels.clone(),
303                properties: detail.properties.clone(),
304                with_properties: detail.with_properties.clone(),
305            };
306        }
307        if let Some(constraint) = backing {
308            return Self {
309                kind,
310                relationship,
311                labels: vec![constraint.label.clone()],
312                properties: constraint.properties.clone(),
313                with_properties: Vec::new(),
314            };
315        }
316        Self {
317            kind,
318            relationship,
319            labels: vec![index.label.clone()],
320            properties: legacy_property_names(&index.property),
321            with_properties: Vec::new(),
322        }
323    }
324}
325
326/// Resolve every named index's [`IndexFacts`] with the detail and
327/// backing-constraint joins done once, in the caller's order, for the
328/// statement-scoped index readers; the SHOW row resolves its own rows
329/// through the same [`backing_constraint_by_name`] join this shares.
330#[doc(hidden)]
331pub fn resolve_index_facts(
332    indexes: &[relate_catalog::IndexDef],
333    details: &std::collections::BTreeMap<String, IndexDetailSpec>,
334    constraints: &[relate_catalog::ConstraintDef],
335) -> Vec<IndexFacts> {
336    indexes
337        .iter()
338        .map(|index| {
339            let detail = details.get(&index.name);
340            let backing = backing_constraint_by_name(&index.name, constraints);
341            IndexFacts::resolve(index, detail, backing)
342        })
343        .collect()
344}
345
346/// The index-backed constraint of the given name, when one exists — the
347/// one owner-constraint join every index reader resolves through (moved
348/// from `exec::catalog` beside `IndexFacts`, its every consumer: the
349/// SHOW row, the graph-counts row, and [`resolve_index_facts`]).
350#[doc(hidden)]
351pub fn backing_constraint_by_name<'a>(
352    name: &str,
353    constraints: &'a [relate_catalog::ConstraintDef],
354) -> Option<&'a relate_catalog::ConstraintDef> {
355    constraints
356        .iter()
357        .find(|def| def.name == name && def.is_index_backed())
358}
359
360/// Typed payload of [`RedoOp::CatalogIndexDetail`]: the catalog facts of
361/// a `CREATE INDEX`, captured once at DDL-execution time from the parsed
362/// clause. `apply_redo` stores it verbatim -- it never formats a CREATE
363/// INDEX string and re-parses it.
364#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
365pub struct IndexDetailSpec {
366    pub kind: IndexKindSpec,
367    /// True for a relationship (`FOR ()-[r:T]-()`) index.
368    pub relationship: bool,
369    /// Node labels, or (for a relationship index) relationship types;
370    /// more than one entry only for the `A|B` disjunctive form, empty for
371    /// a LOOKUP index.
372    #[serde(default)]
373    pub labels: Vec<String>,
374    #[serde(default)]
375    pub properties: Vec<String>,
376    /// CIP-235 `WITH [...]` single-stage-filtering properties (VECTOR).
377    #[serde(default)]
378    pub with_properties: Vec<String>,
379}
380
381impl IndexDetailSpec {
382    /// Node `(label, property)` pairs this detail materializes and charges.
383    /// Relationship indexes, multi-label indexes, and kinds other than
384    /// single-property TEXT or POINT, or RANGE, contribute nothing.
385    pub fn covered_pairs(&self) -> Vec<(&str, &str, IndexKindSpec)> {
386        if self.relationship || self.labels.len() != 1 || self.properties.is_empty() {
387            return Vec::new();
388        }
389        let label = self.labels[0].as_str();
390        match self.kind {
391            IndexKindSpec::Text | IndexKindSpec::Point if self.properties.len() == 1 => {
392                vec![(label, self.properties[0].as_str(), self.kind)]
393            }
394            IndexKindSpec::Range => self
395                .properties
396                .iter()
397                .map(|property| (label, property.as_str(), IndexKindSpec::Range))
398                .collect(),
399            _ => Vec::new(),
400        }
401    }
402
403    /// The node `(label, property)` pairs this index serves an equality seek
404    /// on. Derived from [`Self::covered_pairs`] so the entity, label-count
405    /// and kind gates live once: only a single-label node RANGE index
406    /// contributes, and it contributes **every** covered property — the
407    /// executor materializes and seeks each component of a composite index,
408    /// so leading-only coverage would under-report it. A relationship index
409    /// never yields a node pair, and a property name is never split on a
410    /// comma.
411    pub fn range_seek_pairs(&self) -> Vec<(&str, &str)> {
412        self.covered_pairs()
413            .into_iter()
414            .filter_map(|(label, property, kind)| {
415                (kind == IndexKindSpec::Range).then_some((label, property))
416            })
417            .collect()
418    }
419}
420
421/// Apply the catalog index ops in `ops` to `details`. This is the speculative
422/// projection `estimate_redo_delta` uses; committed replay in `apply_redo`
423/// stores the same two ops.
424pub fn project_index_details(details: &mut BTreeMap<String, IndexDetailSpec>, ops: &[RedoOp]) {
425    for op in ops {
426        match op {
427            RedoOp::CatalogIndexDetail { name, detail, .. } => {
428                details.insert(name.clone(), detail.clone());
429            }
430            RedoOp::DropIndex { name } => {
431                details.remove(name);
432            }
433            _ => {}
434        }
435    }
436}