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