Skip to main content

relate_core/
error_kinds.rs

1//! The shared error-kind vocabulary: [`ErrorKind`] (the finest TCK-aligned
2//! error name) and [`TckErrorClass`] (the eight openCypher TCK error
3//! classes), plus the one spelling of the two detail helpers the typed
4//! channel and the stringly query-error channel share.
5//!
6//! This module moved here from `relate-error` (ADR-0502 §2): the
7//! engine's one error classification — `relate_error::error_info` over
8//! [`crate::Error`] — lives in `relate-error`, which must therefore sit
9//! *above* this crate; the vocabulary both crates share sits here, at the
10//! lowest layer, and `relate-error` re-exports it so every existing
11//! `relate_error::ErrorKind` path keeps resolving.
12
13use std::fmt;
14
15/// Generates [`TckErrorClass`] with its `as_str` / `from_name` tables and
16/// the [`TckErrorClass::ALL`] roster from one variant list, so the enum,
17/// the spelling and the inverse cannot drift apart.
18macro_rules! tck_error_classes {
19    ($($variant:ident),+ $(,)?) => {
20        /// One of the eight openCypher TCK error *classes*. The spec harness
21        /// (ADR-0482) asserts an expected class, while [`ErrorKind`] carries
22        /// the finer-grained detail. Every [`ErrorKind`] maps to exactly one
23        /// class via [`ErrorKind::tck_class`].
24        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
25        pub enum TckErrorClass {
26            $($variant,)+
27        }
28
29        impl TckErrorClass {
30            /// Every class, in declaration order.
31            pub const ALL: &'static [TckErrorClass] = &[$(TckErrorClass::$variant,)+];
32
33            /// The canonical openCypher class name.
34            pub fn as_str(&self) -> &'static str {
35                match self {
36                    $(TckErrorClass::$variant => stringify!($variant),)+
37                }
38            }
39
40            /// Parses one of the eight canonical openCypher class names back
41            /// into a [`TckErrorClass`]; the inverse of
42            /// [`TckErrorClass::as_str`]. Returns `None` for any other
43            /// string.
44            ///
45            /// The spec harness's `should be raised` matcher makes the same
46            /// call over the same eight names (its `clspec/errors.py`,
47            /// ADR-0482): a step whose class is not one of them (e.g. the
48            /// harness `cip-eval` suite's `GraphTypeError`, `SchemaError`,
49            /// `ConstraintValidationFailed`) falls back to lenient any-error
50            /// matching rather than a strict class assertion.
51            pub fn from_name(name: &str) -> Option<TckErrorClass> {
52                match name {
53                    $(stringify!($variant) => Some(TckErrorClass::$variant),)+
54                    _ => None,
55                }
56            }
57        }
58    };
59}
60
61tck_error_classes! {
62    SyntaxError,
63    TypeError,
64    ArgumentError,
65    EntityNotFound,
66    SemanticError,
67    ProcedureError,
68    ParameterMissing,
69    ConstraintVerificationFailed,
70}
71
72impl fmt::Display for TckErrorClass {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        f.write_str(self.as_str())
75    }
76}
77
78/// Generates [`ErrorKind`] plus its `as_str`/`from_name`/`tck_class` tables
79/// from a single `Variant => TckClass` list, so the three stay in lockstep.
80/// The catch-all `Uncategorized` variant is appended automatically; it is the
81/// documented escape hatch for legacy strings that carry no recognized kind
82/// prefix, and it renders with no `"Kind: "` prefix at all (see
83/// `relate_error::EngineError`'s `Display`).
84macro_rules! error_kinds {
85    ($($variant:ident => $class:ident),+ $(,)?) => {
86        /// The specific, TCK-aligned name of an engine error. `kind()` returns
87        /// the most specific name available; nested detail (e.g. the
88        /// `UnsupportedIndexOrConstraint` in `"SyntaxError:
89        /// UnsupportedIndexOrConstraint: …"`) stays in the message.
90        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
91        pub enum ErrorKind {
92            $($variant,)+
93            /// Escape hatch for legacy/opaque errors with no recognized kind
94            /// prefix. Renders without a prefix so the raw message shows
95            /// through byte-for-byte.
96            Uncategorized,
97        }
98
99        impl ErrorKind {
100            /// Every non-`Uncategorized` kind, in declaration order —
101            /// generated from the same list, so coverage tests iterate the
102            /// vocabulary itself rather than a hand copy.
103            pub const ALL: &'static [ErrorKind] = &[$(ErrorKind::$variant,)+];
104
105            /// The canonical string form of this kind — the inverse of
106            /// [`ErrorKind::from_name`] for every non-`Uncategorized` variant.
107            pub fn as_str(&self) -> &'static str {
108                match self {
109                    $(ErrorKind::$variant => stringify!($variant),)+
110                    ErrorKind::Uncategorized => "Uncategorized",
111                }
112            }
113
114            /// Parses a kind name back into an [`ErrorKind`]. Returns `None`
115            /// for unrecognized names (including `"Uncategorized"`, which is
116            /// never produced by parsing).
117            pub fn from_name(name: &str) -> Option<ErrorKind> {
118                match name {
119                    $(stringify!($variant) => Some(ErrorKind::$variant),)+
120                    _ => None,
121                }
122            }
123
124            /// The openCypher TCK error *class* this kind belongs to. Total
125            /// over every variant.
126            pub fn tck_class(&self) -> TckErrorClass {
127                match self {
128                    $(ErrorKind::$variant => TckErrorClass::$class,)+
129                    ErrorKind::Uncategorized => TckErrorClass::SemanticError,
130                }
131            }
132        }
133    };
134}
135
136// The ~60 error-kind prefixes already emitted by the engine (derived by
137// grepping the `"Word:"` error-literal pattern), plus a few kinds used to
138// classify `StorageError` in `EngineError::kind`. The `=> Class` mapping to
139// the eight TCK classes is a best-effort taxonomy refined
140// against the real TCK error scenarios; it never affects `Display` bytes.
141error_kinds! {
142    // --- Syntax / structural / scope / aggregation validation ---
143    SyntaxError => SyntaxError,
144    UnexpectedSyntax => SyntaxError,
145    IncompleteQuery => SyntaxError,
146    InvalidPatternCharacter => SyntaxError,
147    InvalidLabelExpression => SyntaxError,
148    InvalidNodePatternPredicate => SyntaxError,
149    InvalidClauseComposition => SyntaxError,
150    InvalidAggregation => SyntaxError,
151    AmbiguousAggregationExpression => SyntaxError,
152    NestedAggregation => SyntaxError,
153    NegativeIntegerArgument => SyntaxError,
154    NoSingleRelationshipType => SyntaxError,
155    DifferentColumnsInUnion => SyntaxError,
156    VariableAlreadyBound => SyntaxError,
157    VariableAlreadyDefined => SyntaxError,
158    VariableTypeConflict => SyntaxError,
159    VariableShadowing => SyntaxError,
160    UndefinedVariable => SyntaxError,
161    UnknownFunction => SyntaxError,
162    NoExpressionAlias => SyntaxError,
163    NoVariablesInScope => SyntaxError,
164    RelationshipUniquenessViolation => SyntaxError,
165    CreatingVarLength => SyntaxError,
166    RequiresDirectedRelationship => SyntaxError,
167    InvalidParameterUse => SyntaxError,
168    ColumnNameConflict => SyntaxError,
169    QuantifiedPathPatternNotSupported => SyntaxError,
170    InvalidSelectivePathPatternDependency => SyntaxError,
171    GroupVariableReuse => SyntaxError,
172    SingletonReusedAsGroup => SyntaxError,
173    NonLocalGroupVariableReference => SyntaxError,
174    GroupVariableInNonAggregatingOperation => SyntaxError,
175    InvalidSearchVariableReference => SyntaxError,
176    SelfReferencingSearch => SyntaxError,
177    InvalidUseOfCommand => SyntaxError,
178    InvalidPlacementOfUseClause => SyntaxError,
179    // ADR-0116 §2 (2026-11-04): a `USE` clause targeting a non-system
180    // namespace on a statement headed by a database-administration command —
181    // CE's 42N79 auto-routing rejection, which Neo4j surfaces as a
182    // SyntaxException (Neo.ClientError.Statement.SyntaxError).
183    UseClauseWithAdministrationCommand => SyntaxError,
184    InvalidUpdatingClauseInCountSubquery => SyntaxError,
185    InvalidUpdatingClauseInCollectSubquery => SyntaxError,
186    NonConstantExpression => SyntaxError,
187    NonDeterministicDisjointBy => SyntaxError,
188    InvalidShortestPathMixing => SyntaxError,
189    InvalidShowColumn => SyntaxError,
190    InvalidNumberOfArguments => SyntaxError,
191    // ADR-0466 (LABS-610): an explicit traversal hop bound above the
192    // admission limit (`--max-traversal-depth`, default 500). Raised at the
193    // lowering boundary as a syntax error: the statement is admissibly
194    // invalid before the walker ever runs (Bolt
195    // `Neo.ClientError.Statement.SyntaxError`, HTTP 400/42N06).
196    TraversalDepthExceeded => SyntaxError,
197    // LABS-680 (ADR-0477): a statement shape `--safe` refuses. Like
198    // `TraversalDepthExceeded` it is raised at the lowering boundary and
199    // surfaces as a syntax error (Bolt `Neo.ClientError.Statement.SyntaxError`,
200    // HTTP 400/42N06, CLI exit 6). The message states that it is a policy,
201    // not a database limit.
202    SafeModeViolation => SyntaxError,
203    // Literal-lexing / literal-range failures raised by the parser and surfaced
204    // through `EngineError::Syntax`'s `ParseError::detail` tag. All are
205    // `SyntaxError`-class compile-time failures in the TCK error grammar
206    // (Literals2/3/5/6, Mathematical3, Match4).
207    IntegerOverflow => SyntaxError,
208    FloatingPointOverflow => SyntaxError,
209    InvalidNumberLiteral => SyntaxError,
210    InvalidUnicodeLiteral => SyntaxError,
211    InvalidUnicodeCharacter => SyntaxError,
212    InvalidRelationshipPattern => SyntaxError,
213    InvalidArgumentPassingMode => SyntaxError,
214    // `DELETE`ing a non-entity that is specifically a label predicate
215    // (`DELETE n:Person`, `DELETE r:T`) is a `SyntaxError: InvalidDelete`
216    // (Delete1/Delete2); a non-label non-entity expression (`DELETE 1 + 1`)
217    // stays `InvalidArgumentType` (Delete5).
218    InvalidDelete => SyntaxError,
219    // --- Type errors ---
220    TypeError => TypeError,
221    InvalidArgumentType => TypeError,
222    // A `||` operand that is statically known to be neither a string nor a
223    // list (CIP-144). Unlike the other static type checks — which openCypher
224    // surfaces as `SyntaxError: InvalidArgumentType` — Neo4j reports this
225    // one as a `TypeError`, matching its runtime twin, so the class travels
226    // apart from `InvalidArgumentType`.
227    InvalidConcatenationOperand => TypeError,
228    ParameterWrongTypeException => TypeError,
229    InvalidPropertyType => TypeError,
230    InvalidPropertyValueType => TypeError,
231    // Indexing a map with a non-string key (`{name: 'Apa'}[0]`) is a runtime
232    // `TypeError: MapElementAccessByNonString` (Map2).
233    MapElementAccessByNonString => TypeError,
234    // --- Argument value / arithmetic errors ---
235    ArgumentError => ArgumentError,
236    // The `InvalidArgumentValue` detail is classified as TypeError by both the
237    // openCypher TCK (expressions/graph/Graph3-4, typeConversion/TypeConversion1-4)
238    // and the in-repo cip-eval suite (63 TypeError vs 0 ArgumentError occurrences).
239    InvalidArgumentValue => TypeError,
240    ArithmeticError => ArgumentError,
241    // A numeric argument outside its permitted range: `range()` step 0,
242    // `percentileCont`/`percentileDisc` percentile outside [0,1] — a runtime
243    // `ArgumentError: NumberOutOfRange` (List11, Aggregation6).
244    NumberOutOfRange => ArgumentError,
245    // ADR-0395: a statement's nested evaluation (CALL bodies,
246    // EXISTS/COUNT/COLLECT subqueries, FOREACH clause lists, NEXT
247    // stages) exceeded the fixed per-statement pass budget — the runtime
248    // twin of the compile-side cloned-node budget (ADR-0382). Raised as
249    // an `Error::Execution` payload whose `Kind:` prefix names this row.
250    NestedEvaluationBudgetExceeded => ArgumentError,
251    // ADR-0478 Decision 6: a frontier-NFA walk's incident-edge visits
252    // exceeded the fixed per-run work budget — the traversal twin of
253    // ADR-0395's pass budget, so a frontier that would blow up (huge
254    // diameter x automaton states) fails loud in milliseconds instead of
255    // by watchdog cancel after RSS growth. Raised as an
256    // `Error::Execution` payload whose `Kind:` prefix names this row.
257    WalkBudgetExceeded => ArgumentError,
258    // ADR-0462 (LABS-606): a dynamically constructed `Value` would nest
259    // past `MAX_VALUE_DEPTH` (a `reduce`/list-comprehension accumulator
260    // growing one level per iteration is the canonical shape) — the value
261    // twin of ADR-0257's static parse-nesting limit. Raised as an
262    // `Error::Execution` payload whose `Kind:` prefix names this row.
263    ValueDepthExceeded => ArgumentError,
264    // --- Parameters ---
265    ParameterMissing => ParameterMissing,
266    // --- Entity access ---
267    EntityNotFound => EntityNotFound,
268    DeletedEntityAccess => EntityNotFound,
269    // --- Constraints ---
270    ConstraintViolation => ConstraintVerificationFailed,
271    // Deleting a still-connected node without `DETACH` is a runtime
272    // `ConstraintVerificationFailed: DeleteConnectedNode` (Delete1). Distinct
273    // from a general `ConstraintViolation` so the finer detail survives.
274    DeleteConnectedNode => ConstraintVerificationFailed,
275    // --- Procedures ---
276    ProcedureError => ProcedureError,
277    // Calling a procedure that is not registered is a
278    // `ProcedureError: ProcedureNotFound` (Call1).
279    ProcedureNotFound => ProcedureError,
280    // --- Schema / database / graph-type / data / transaction (semantic) ---
281    SchemaError => SemanticError,
282    MergeReadOwnWrites => SemanticError,
283    DataException => SemanticError,
284    DataError => SemanticError,
285    DatabaseNotFound => SemanticError,
286    DatabaseExists => SemanticError,
287    DatabaseError => SemanticError,
288    SystemDatabaseRequired => SemanticError,
289    GraphTypeNotFound => SemanticError,
290    InternalError => SemanticError,
291    TransactionError => SemanticError,
292    // ADR-0116 §9: a database administration command outside the CE-supported
293    // set (Neo4j's `Neo.ClientError.Statement.UnsupportedAdministrationCommand`,
294    // GQLSTATUS 51N27).
295    UnsupportedAdministrationCommand => SemanticError,
296    // ADR-0116 §9: a write against the read-only `system_ontologies`
297    // namespace (GQLSTATUS 42N18).
298    WriteOnReadOnlyAccessDatabase => SemanticError,
299}
300
301impl ErrorKind {
302    /// The openCypher-TCK error *detail* name for this kind — what the harness
303    /// compares against the `<Detail>` slot of `a <Class> should be raised at
304    /// <phase>: <Detail>`. Equal to [`ErrorKind::as_str`] for every kind except
305    /// the aliased ones below. Never used for `Display`.
306    ///
307    /// Currently one alias exists:
308    ///
309    /// | `ErrorKind` variant | Display / `as_str` | TCK detail (`tck_detail`) |
310    /// |---------------------|--------------------|---------------------------|
311    /// | [`ErrorKind::ParameterMissing`] | `ParameterMissing` | `MissingParameter` |
312    pub fn tck_detail(&self) -> &'static str {
313        match self {
314            // The TCK spells our `ParameterMissing` as `MissingParameter`
315            // (clauses/call/Call1 scenario 11). `as_str` stays `ParameterMissing`
316            // for Display/`from_name` round-trip compatibility.
317            ErrorKind::ParameterMissing => "MissingParameter",
318            other => other.as_str(),
319        }
320    }
321
322    /// Parses a TCK error-*detail* name into an [`ErrorKind`] — the inverse of
323    /// [`ErrorKind::tck_detail`]. Handles the aliases first, then delegates to
324    /// [`ErrorKind::from_name`]. Returns `None` for unrecognized names.
325    pub fn from_tck_detail(name: &str) -> Option<ErrorKind> {
326        match name {
327            "MissingParameter" => Some(ErrorKind::ParameterMissing),
328            other => ErrorKind::from_name(other),
329        }
330    }
331}
332
333/// The one spelling of an undefined-variable rejection's detail (after the
334/// `UndefinedVariable:` kind token): `variable '<name>' not defined`. Both
335/// error channels — the typed `relate_error::EngineError`
336/// and the executor's string-carrying [`crate::Error`] — render the same
337/// text.
338pub fn undefined_variable_detail(name: &str) -> String {
339    format!("variable '{name}' not defined")
340}
341
342/// The one spelling of a duplicate-binding rejection's detail (after the
343/// `VariableAlreadyBound:` kind token): `variable '<name>' already declared`.
344pub fn duplicate_variable_detail(name: &str) -> String {
345    format!("variable '{name}' already declared")
346}
347
348/// The one spelling of an unknown-function rejection's detail (after the
349/// `UnknownFunction:` kind token): `unknown function <name>()`. The planner's
350/// binder, the executor's scalar-eval backstop and the front's preview-name
351/// admission gate all render this text, so a gated name is rejected exactly
352/// like a name the registry has never known.
353pub fn unknown_function_detail(name: &str) -> String {
354    format!("unknown function {name}()")
355}
356
357#[cfg(test)]
358mod tests;