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    ParameterWrongTypeException => TypeError,
217    InvalidPropertyType => TypeError,
218    InvalidPropertyValueType => TypeError,
219    // Indexing a map with a non-string key (`{name: 'Apa'}[0]`) is a runtime
220    // `TypeError: MapElementAccessByNonString` (Map2).
221    MapElementAccessByNonString => TypeError,
222    // --- Argument value / arithmetic errors ---
223    ArgumentError => ArgumentError,
224    // The `InvalidArgumentValue` detail is classified as TypeError by both the
225    // openCypher TCK (expressions/graph/Graph3-4, typeConversion/TypeConversion1-4)
226    // and the in-repo cip-eval suite (63 TypeError vs 0 ArgumentError occurrences).
227    InvalidArgumentValue => TypeError,
228    ArithmeticError => ArgumentError,
229    // A numeric argument outside its permitted range: `range()` step 0,
230    // `percentileCont`/`percentileDisc` percentile outside [0,1] — a runtime
231    // `ArgumentError: NumberOutOfRange` (List11, Aggregation6).
232    NumberOutOfRange => ArgumentError,
233    // ADR-0395: a statement's nested evaluation (CALL bodies,
234    // EXISTS/COUNT/COLLECT subqueries, FOREACH clause lists, NEXT
235    // stages) exceeded the fixed per-statement pass budget — the runtime
236    // twin of the compile-side cloned-node budget (ADR-0382). Raised as
237    // an `Error::Execution` payload whose `Kind:` prefix names this row.
238    NestedEvaluationBudgetExceeded => ArgumentError,
239    // ADR-0478 Decision 6: a frontier-NFA walk's incident-edge visits
240    // exceeded the fixed per-run work budget — the traversal twin of
241    // ADR-0395's pass budget, so a frontier that would blow up (huge
242    // diameter x automaton states) fails loud in milliseconds instead of
243    // by watchdog cancel after RSS growth. Raised as an
244    // `Error::Execution` payload whose `Kind:` prefix names this row.
245    WalkBudgetExceeded => ArgumentError,
246    // ADR-0462 (LABS-606): a dynamically constructed `Value` would nest
247    // past `MAX_VALUE_DEPTH` (a `reduce`/list-comprehension accumulator
248    // growing one level per iteration is the canonical shape) — the value
249    // twin of ADR-0257's static parse-nesting limit. Raised as an
250    // `Error::Execution` payload whose `Kind:` prefix names this row.
251    ValueDepthExceeded => ArgumentError,
252    // --- Parameters ---
253    ParameterMissing => ParameterMissing,
254    // --- Entity access ---
255    EntityNotFound => EntityNotFound,
256    DeletedEntityAccess => EntityNotFound,
257    // --- Constraints ---
258    ConstraintViolation => ConstraintVerificationFailed,
259    // Deleting a still-connected node without `DETACH` is a runtime
260    // `ConstraintVerificationFailed: DeleteConnectedNode` (Delete1). Distinct
261    // from a general `ConstraintViolation` so the finer detail survives.
262    DeleteConnectedNode => ConstraintVerificationFailed,
263    // --- Procedures ---
264    ProcedureError => ProcedureError,
265    // Calling a procedure that is not registered is a
266    // `ProcedureError: ProcedureNotFound` (Call1).
267    ProcedureNotFound => ProcedureError,
268    // --- Schema / database / graph-type / data / transaction (semantic) ---
269    SchemaError => SemanticError,
270    MergeReadOwnWrites => SemanticError,
271    DataException => SemanticError,
272    DataError => SemanticError,
273    DatabaseNotFound => SemanticError,
274    DatabaseExists => SemanticError,
275    DatabaseError => SemanticError,
276    SystemDatabaseRequired => SemanticError,
277    GraphTypeNotFound => SemanticError,
278    InternalError => SemanticError,
279    TransactionError => SemanticError,
280    // ADR-0116 §9: a database administration command outside the CE-supported
281    // set (Neo4j's `Neo.ClientError.Statement.UnsupportedAdministrationCommand`,
282    // GQLSTATUS 51N27).
283    UnsupportedAdministrationCommand => SemanticError,
284    // ADR-0116 §9: a write against the read-only `system_ontologies`
285    // namespace (GQLSTATUS 42N18).
286    WriteOnReadOnlyAccessDatabase => SemanticError,
287}
288
289impl ErrorKind {
290    /// The openCypher-TCK error *detail* name for this kind — what the harness
291    /// compares against the `<Detail>` slot of `a <Class> should be raised at
292    /// <phase>: <Detail>`. Equal to [`ErrorKind::as_str`] for every kind except
293    /// the aliased ones below. Never used for `Display`.
294    ///
295    /// Currently one alias exists:
296    ///
297    /// | `ErrorKind` variant | Display / `as_str` | TCK detail (`tck_detail`) |
298    /// |---------------------|--------------------|---------------------------|
299    /// | [`ErrorKind::ParameterMissing`] | `ParameterMissing` | `MissingParameter` |
300    pub fn tck_detail(&self) -> &'static str {
301        match self {
302            // The TCK spells our `ParameterMissing` as `MissingParameter`
303            // (clauses/call/Call1 scenario 11). `as_str` stays `ParameterMissing`
304            // for Display/`from_name` round-trip compatibility.
305            ErrorKind::ParameterMissing => "MissingParameter",
306            other => other.as_str(),
307        }
308    }
309
310    /// Parses a TCK error-*detail* name into an [`ErrorKind`] — the inverse of
311    /// [`ErrorKind::tck_detail`]. Handles the aliases first, then delegates to
312    /// [`ErrorKind::from_name`]. Returns `None` for unrecognized names.
313    pub fn from_tck_detail(name: &str) -> Option<ErrorKind> {
314        match name {
315            "MissingParameter" => Some(ErrorKind::ParameterMissing),
316            other => ErrorKind::from_name(other),
317        }
318    }
319}
320
321/// The one spelling of an undefined-variable rejection's detail (after the
322/// `UndefinedVariable:` kind token): `variable '<name>' not defined`. Both
323/// error channels — the typed `relate_error::EngineError`
324/// and the executor's string-carrying [`crate::Error`] — render the same
325/// text.
326pub fn undefined_variable_detail(name: &str) -> String {
327    format!("variable '{name}' not defined")
328}
329
330/// The one spelling of a duplicate-binding rejection's detail (after the
331/// `VariableAlreadyBound:` kind token): `variable '<name>' already declared`.
332pub fn duplicate_variable_detail(name: &str) -> String {
333    format!("variable '{name}' already declared")
334}
335
336/// The one spelling of an unknown-function rejection's detail (after the
337/// `UnknownFunction:` kind token): `unknown function <name>()`. The planner's
338/// binder, the executor's scalar-eval backstop and the front's preview-name
339/// admission gate all render this text, so a gated name is rejected exactly
340/// like a name the registry has never known.
341pub fn unknown_function_detail(name: &str) -> String {
342    format!("unknown function {name}()")
343}
344
345#[cfg(test)]
346mod tests;