Skip to main content

relate_error/
classification.rs

1//! The one classification of a query-engine error (ADR-0502 §2): the
2//! Neo4j status code, the GQLSTATUS, the compile/runtime/internal stage
3//! (ADR-0319's split) and the drivers' transient test, single-sourced in
4//! [`error_info`] so Bolt's FAILURE rendering, HTTP's error envelope, the
5//! CLI's exit-code classifier, Python and the C ABI are thin derivations —
6//! never second tables that drift.
7//!
8//! The exhaustive match and the Neo4j code constants moved here from Bolt's
9//! `failures::error_class` (ADR-0307's table, the most complete of the four
10//! historical sites); the move is a move, not a redesign — every consumer
11//! keeps its exact observable output. The GQLSTATUS column is new wire data
12//! for the typed C ABI v2's one error shape; its values are the codes the
13//! repo's surfaces already emit (HTTP's error envelope, ADR-0232 — the
14//! engine-documented fixed-namespace codes of ADR-0116 §9 and the GQL
15//! general code for every other class), so deriving a surface from
16//! [`ErrorInfo`] cannot change what that surface sends today.
17
18use crate::nested_class::{
19    nested_error_class, stringly_gql_status, NestedErrorClass,
20    GQLSTATUS_CONSTRAINT_CREATION_FAILED, GQLSTATUS_DATABASE_NOT_FOUND, GQLSTATUS_GENERAL,
21    GQLSTATUS_INTERNAL, GQLSTATUS_PARAMETER_MISSING, GQLSTATUS_PROCEDURE_CALL, GQLSTATUS_SYNTAX,
22    GQLSTATUS_TYPE,
23};
24use relate_core::{ArgumentFault, ArithmeticFailure, Error};
25
26/// The `code` of a statement the parser rejects (engine `Syntax`).
27pub const SYNTAX_ERROR_CODE: &str = "Neo.ClientError.Statement.SyntaxError";
28
29/// The `code` sent when a query calls a procedure the engine does not
30/// register (ADR-0138): neo4j-browser branches on the exact Neo4j code for
31/// its `dbms.clientConfig` → `dbms.listConfig` fallback.
32pub const PROCEDURE_NOT_FOUND_CODE: &str = "Neo.ClientError.Procedure.ProcedureNotFound";
33
34/// A registered call failing its own signature (live's
35/// `Neo.ClientError.Procedure.ProcedureCallFailed`, probed on 2026.10.1).
36pub const PROCEDURE_CALL_FAILED_CODE: &str = "Neo.ClientError.Procedure.ProcedureCallFailed";
37
38/// The `code` of a statement that references an absent parameter
39/// (ADR-0308).
40pub const PARAMETER_MISSING_CODE: &str = "Neo.ClientError.Statement.ParameterMissing";
41
42/// The `code` of an unknown database, from a `db` extra or a `USE` target.
43pub const DATABASE_NOT_FOUND_CODE: &str = "Neo.ClientError.Database.DatabaseNotFound";
44
45/// The `code` of every other caller-facing `Semantic` and `Execution`
46/// engine error.
47pub const SEMANTIC_ERROR_CODE: &str = "Neo.ClientError.Statement.SemanticError";
48
49/// The `code` of a well-formed reference to something that does not exist
50/// (`EntityNotFound:` token): what Neo4j 2026.10.1 sends for
51/// `db.nameFromElementId` over an element id naming an unknown database.
52pub const ENTITY_NOT_FOUND_CODE: &str = "Neo.ClientError.Statement.EntityNotFound";
53
54/// The `code` of a type failure (`Type`, `TypeError`, `InvalidArgumentType`).
55pub const TYPE_ERROR_CODE: &str = "Neo.ClientError.Statement.TypeError";
56
57/// The `code` of a DDL argument-value rejection (`ArgumentError`): the code
58/// Neo4j 2026.09 sends for an invalid `OPTIONS`/`indexConfig` value
59/// (ADR-0489).
60pub const ARGUMENT_ERROR_CODE: &str = "Neo.ClientError.General.InvalidArguments";
61
62/// The `code` of a run-time argument rejection (`ArgumentValue`): what Neo4j
63/// 2026.10.1 sends for `range()`'s zero step and for the
64/// `substring()`/`left()`/`right()` int32-range rejections — the same
65/// `ArgumentError` class as [`ARGUMENT_ERROR_CODE`], a different stage.
66pub const ARGUMENT_VALUE_ERROR_CODE: &str = "Neo.ClientError.Statement.ArgumentError";
67
68/// The GQLSTATUS of a run-time argument rejection's per-site fault — live's
69/// codes for `point()`'s in-map rejections (probed on 2026.09.0): the one
70/// table a site's code derives from.
71fn argument_fault_gql_status(fault: ArgumentFault) -> &'static str {
72    match fault {
73        ArgumentFault::InvalidDimension => "22N20",
74        ArgumentFault::UnknownCrs => "22N21",
75        ArgumentFault::InvalidLatitude => "22N23",
76        ArgumentFault::NonFiniteCoordinate => "22N24",
77        ArgumentFault::WrongType => GQLSTATUS_TYPE,
78        ArgumentFault::General(_) => GQLSTATUS_GENERAL,
79    }
80}
81
82/// The `code` of an arithmetic failure (`Arithmetic`: division or modulo by
83/// zero, rounding necessary).
84pub const ARITHMETIC_ERROR_CODE: &str = "Neo.ClientError.Statement.ArithmeticError";
85
86/// The `code` of a uniqueness-constraint violation.
87pub const CONSTRAINT_VALIDATION_FAILED_CODE: &str =
88    "Neo.ClientError.Schema.ConstraintValidationFailed";
89
90/// The `code` of a query stopped by `--query-timeout-secs` (the engine's
91/// `Cancelled`).
92pub const TRANSACTION_TIMED_OUT_CODE: &str = "Neo.ClientError.Transaction.TransactionTimedOut";
93/// A statement stopped by a deadline the request itself set (a driver's
94/// `tx_timeout`, an HTTP `maxExecutionTime`), ADR-0692.
95pub const TRANSACTION_TIMED_OUT_CLIENT_CONFIGURATION_CODE: &str =
96    "Neo.ClientError.Transaction.TransactionTimedOutClientConfiguration";
97
98/// The `code` of a write-write conflict: a `TransientError`, so drivers'
99/// managed transactions retry it (the engine never does, ADR-0017).
100pub const OUTDATED_CODE: &str = "Neo.TransientError.Transaction.Outdated";
101
102/// The `code` of both memory conditions — a write over
103/// `--logical-graph-size-limit` (`Capacity`) and a result over
104/// `--max-result-bytes` — the one Neo4j memory code in the non-retryable
105/// `ClientError` class (ADR-0307 item 4).
106pub const TRANSACTION_OUT_OF_MEMORY_CODE: &str =
107    "Neo.ClientError.General.TransactionOutOfMemoryError";
108
109/// The `code` of a retryable processing cap
110/// (`concurrent-logical-workspace-limit`). Transient, so a driver's managed
111/// transaction retries the statement.
112pub const MEMORY_POOL_OUT_OF_MEMORY_CODE: &str =
113    "Neo.TransientError.General.MemoryPoolOutOfMemoryError";
114
115/// The `code` sent when an internal-class engine error is genericized at a
116/// trust boundary (ADR-0260, ADR-0307).
117pub const UNKNOWN_ERROR_CODE: &str = "Neo.DatabaseError.General.UnknownError";
118
119// The GQLSTATUS column (ADR-0502 §2's error shape). The values are the
120// documented Neo4j GQLSTATUS codes: the engine-documented codes of
121// ADR-0116 §9 for the fixed-namespace classes, the documented schema/DDL
122// condition codes below (live-verified 2026-11-12 on Neo4j 2026.10.1), and
123// the GQL general error code for every class without a class-specific code
124// — exactly the split HTTP's error envelope (ADR-0232) has always made.
125
126/// Which stage of statement handling an error belongs to (ADR-0319): a
127/// compile-class error fails the statement before any work is done (Bolt's
128/// RUN), a runtime-class error is discovered while producing rows (Bolt's
129/// first PULL/DISCARD), and an internal-class error is not the statement's
130/// fault and is genericized at every trust boundary (ADR-0260).
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132pub enum ErrorStage {
133    /// The statement itself is rejected: the RUN fails under the code.
134    Compile,
135    /// Discovered while executing: reported at the first row pull.
136    Runtime,
137    /// Engine-internal: genericized for the client (ADR-0260).
138    Internal,
139}
140
141impl ErrorStage {
142    /// The one string spelling of the stage (ADR-0502 §2: the error shape's
143    /// `stage` field) — `"compile"`, `"runtime"` or `"internal"`. The C ABI
144    /// and the Python binding both render it from here, so the spelling is
145    /// single-sourced.
146    ///
147    /// ```
148    /// use relate_error::ErrorStage;
149    ///
150    /// assert_eq!(ErrorStage::Compile.as_str(), "compile");
151    /// assert_eq!(ErrorStage::Runtime.as_str(), "runtime");
152    /// assert_eq!(ErrorStage::Internal.as_str(), "internal");
153    /// ```
154    pub fn as_str(self) -> &'static str {
155        match self {
156            ErrorStage::Compile => "compile",
157            ErrorStage::Runtime => "runtime",
158            ErrorStage::Internal => "internal",
159        }
160    }
161}
162
163/// The classification of one query-engine error (ADR-0502 §2): everything
164/// the ABI v2 error shape carries beside the message, and everything the
165/// surfaces need to render a failure. Built only by [`error_info`] — the
166/// one exhaustive classification, so a new engine variant does not compile
167/// until it is classified here.
168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169pub struct ErrorInfo {
170    /// The Neo4j status code the caller-facing classes carry; the
171    /// internal class carries the genericized `UnknownError` code
172    /// (ADR-0260).
173    pub neo4j_code: &'static str,
174    /// The GQLSTATUS (the codes the repo's surfaces emit today, see the
175    /// module docs).
176    pub gql_status: &'static str,
177    /// The compile/runtime/internal stage (ADR-0319).
178    pub stage: ErrorStage,
179    /// The drivers' transient test (ADR-0502): whether a driver's managed
180    /// transaction retries the statement. True for a write-write conflict
181    /// and a retryable processing cap, false for everything else.
182    pub retryable: bool,
183}
184
185/// The message a trust boundary may show the client for `e` — the
186/// message-exposure half of ADR-0260 (OPLANE_REQ-00340359), derived from
187/// the one classification beside it: the caller-facing classes carry the
188/// engine's Display text; the internal class carries the fixed
189/// [`INTERNAL_MESSAGE`], because engine-internal, IO, storage and locked
190/// messages can hold file paths and engine internals. A boundary that
191/// wants the original for its own log reads it itself (it has `e`) —
192/// this helper never leaks it.
193pub fn client_message(e: &Error) -> std::borrow::Cow<'_, str> {
194    match error_info(e).stage {
195        ErrorStage::Compile | ErrorStage::Runtime => std::borrow::Cow::Owned(e.to_string()),
196        ErrorStage::Internal => std::borrow::Cow::Borrowed(INTERNAL_MESSAGE),
197    }
198}
199
200/// Log the internal class's original message to stderr — the
201/// boundary-log half of the same ADR-0260 policy
202/// (OPLANE_REQ-00340359): the class whose message [`client_message`]
203/// genericizes is the one whose original an operator needs server-side,
204/// so the stage decision and the log format live here once, beside the
205/// redaction they complement. `boundary` names the calling surface in
206/// the line (`"bolt"`, `"http"`, `"ffi"`); a boundary that gates its
207/// channel (the C ABI's host opt-in) applies its gate at its own call
208/// site.
209pub fn log_internal_original(e: &Error, boundary: &str) {
210    if let ErrorStage::Internal = error_info(e).stage {
211        eprintln!("{boundary} internal error: {e}");
212    }
213}
214
215/// The openCypher error class nested in a still-stringly `Syntax`/
216/// `Semantic`/`Execution` payload: the legacy constraint-class tokens
217/// first, then a leading `<Class>:` name token. [`nested_error_class`]
218/// returns `None` when the payload carries no recognized class — the
219/// caller's variant-level class is then the answer.
220///
221/// The fixed client message every trust boundary substitutes for an
222/// internal-class failure (ADR-0260, OPLANE_REQ-00340359): engine-internal,
223/// IO, storage and locked errors — and caught panic payloads — can carry
224/// file paths and engine internals, so their Display text stays
225/// server-side (logged by the boundary) and the client sees this. The
226/// caller-facing classes pass their Display text through verbatim.
227pub const INTERNAL_MESSAGE: &str = "internal error";
228
229/// The internal class's own row of the ADR-0307 table: the genericized
230/// `UnknownError` code, the internal GQLSTATUS, the internal stage, never
231/// retryable (ADR-0260 — an internal failure is not the statement's
232/// fault). [`error_info`] returns exactly this row for an engine-internal
233/// failure, and publishes it for the boundaries that fail before the
234/// engine sees anything — a null or poisoned handle, an argument decode
235/// refusal, a caught panic — so they render the internal classification
236/// without fabricating an engine error to classify.
237pub const INTERNAL_ERROR_INFO: ErrorInfo = ErrorInfo {
238    neo4j_code: UNKNOWN_ERROR_CODE,
239    gql_status: GQLSTATUS_INTERNAL,
240    stage: ErrorStage::Internal,
241    retryable: false,
242};
243
244/// Classify a query-engine error (ADR-0307, single-sourced by ADR-0502 §2).
245/// Exhaustive on purpose: a new engine variant does not compile until it
246/// has a code, a GQLSTATUS, a stage and a retryable verdict — the match
247/// that Bolt's `failures::error_class` used to own alone.
248///
249/// ```
250/// use relate_error::{error_info, ErrorStage, PARAMETER_MISSING_CODE};
251///
252/// let e = relate_core::Error::parameters_missing(["p"]);
253/// let info = error_info(&e);
254/// assert_eq!(info.neo4j_code, PARAMETER_MISSING_CODE);
255/// assert_eq!(info.gql_status, "42N02");
256/// assert_eq!(info.stage, ErrorStage::Compile);
257/// assert!(!info.retryable);
258/// ```
259pub fn error_info(e: &Error) -> ErrorInfo {
260    use ErrorStage::{Compile, Runtime};
261    match e {
262        // --- Compile class: the statement is rejected before any work. ---
263        Error::Syntax(payload) => ErrorInfo {
264            neo4j_code: SYNTAX_ERROR_CODE,
265            gql_status: stringly_gql_status(nested_error_class(payload), GQLSTATUS_SYNTAX),
266            stage: Compile,
267            retryable: false,
268        },
269        Error::ProcedureNotFound { .. } => ErrorInfo {
270            neo4j_code: PROCEDURE_NOT_FOUND_CODE,
271            // Live Neo4j sends 42001 for an unregistered procedure, so its
272            // GQLSTATUS is the syntax code even though the binding class is
273            // `ProcedureError` (ADR-0565).
274            gql_status: GQLSTATUS_SYNTAX,
275            stage: Compile,
276            retryable: false,
277        },
278        Error::ParameterMissing(_) => ErrorInfo {
279            neo4j_code: PARAMETER_MISSING_CODE,
280            gql_status: GQLSTATUS_PARAMETER_MISSING,
281            stage: Compile,
282            retryable: false,
283        },
284        Error::DatabaseNotFound { .. } => ErrorInfo {
285            neo4j_code: DATABASE_NOT_FOUND_CODE,
286            gql_status: GQLSTATUS_DATABASE_NOT_FOUND,
287            stage: Compile,
288            retryable: false,
289        },
290        // ADR-0489: a DDL option/index-config argument rejection is
291        // discovered while the statement is validated, before any write, so
292        // it fails the RUN (Neo4j sends it under the same code at RUN).
293        Error::ArgumentError(_) => ErrorInfo {
294            neo4j_code: ARGUMENT_ERROR_CODE,
295            gql_status: GQLSTATUS_GENERAL,
296            stage: Compile,
297            retryable: false,
298        },
299        // --- Runtime class: discovered while producing rows. ---
300        // The function-argument validator's rejections share the DDL
301        // argument class but are discovered while rows are produced, so live
302        // fails the PULL — its own code and stage, not the DDL one's.
303        Error::ArgumentValue { fault, .. } => ErrorInfo {
304            neo4j_code: ARGUMENT_VALUE_ERROR_CODE,
305            gql_status: argument_fault_gql_status(*fault),
306            stage: Runtime,
307            retryable: false,
308        },
309        // A registered call failing its own signature: live fails the PULL
310        // with ProcedureCallFailed and its 42001 (probed 2026-11-20 on
311        // 2026.10.1 for both the temporal constructors' value rejections
312        // and `duration.between`'s non-temporal operands) — the one
313        // procedure-family site where the recorded GQLSTATUS is live's,
314        // not ADR-0565's compile-time syntax mapping.
315        Error::ProcedureCall(_) => ErrorInfo {
316            neo4j_code: PROCEDURE_CALL_FAILED_CODE,
317            gql_status: GQLSTATUS_PROCEDURE_CALL,
318            stage: Runtime,
319            retryable: false,
320        },
321        Error::Type(_) | Error::TypeError(_) | Error::InvalidArgumentType(_) => ErrorInfo {
322            neo4j_code: TYPE_ERROR_CODE,
323            gql_status: GQLSTATUS_TYPE,
324            stage: Runtime,
325            retryable: false,
326        },
327        // Division and modulo by zero were historically `Type` (the
328        // bindings' TypeError class); rounding necessary was a nameless
329        // `Execution` token — the GQLSTATUS column keeps that split.
330        Error::Arithmetic(ArithmeticFailure::DivisionByZero | ArithmeticFailure::ModuloByZero) => {
331            ErrorInfo {
332                neo4j_code: ARITHMETIC_ERROR_CODE,
333                gql_status: GQLSTATUS_TYPE,
334                stage: Runtime,
335                retryable: false,
336            }
337        }
338        Error::Arithmetic(ArithmeticFailure::RoundingNecessary) => ErrorInfo {
339            neo4j_code: ARITHMETIC_ERROR_CODE,
340            gql_status: GQLSTATUS_GENERAL,
341            stage: Runtime,
342            retryable: false,
343        },
344        Error::UniquenessViolation { .. } => ErrorInfo {
345            neo4j_code: CONSTRAINT_VALIDATION_FAILED_CODE,
346            gql_status: GQLSTATUS_GENERAL,
347            stage: Runtime,
348            retryable: false,
349        },
350        Error::Cancelled => ErrorInfo {
351            neo4j_code: TRANSACTION_TIMED_OUT_CODE,
352            gql_status: GQLSTATUS_GENERAL,
353            stage: Runtime,
354            retryable: false,
355        },
356        Error::TimedOut { requested, .. } => ErrorInfo {
357            neo4j_code: if *requested {
358                TRANSACTION_TIMED_OUT_CLIENT_CONFIGURATION_CODE
359            } else {
360                TRANSACTION_TIMED_OUT_CODE
361            },
362            gql_status: GQLSTATUS_GENERAL,
363            stage: Runtime,
364            retryable: false,
365        },
366        // A `TransientError` code: drivers' managed transactions retry it.
367        Error::Conflict => ErrorInfo {
368            neo4j_code: OUTDATED_CODE,
369            gql_status: GQLSTATUS_GENERAL,
370            stage: Runtime,
371            retryable: true,
372        },
373        // The capacity family — the graph cap, the expression cap and the
374        // per-record WAL payload cap (ADR-0494) — is the one memory code.
375        Error::Capacity { .. } => ErrorInfo {
376            neo4j_code: TRANSACTION_OUT_OF_MEMORY_CODE,
377            gql_status: GQLSTATUS_GENERAL,
378            stage: Runtime,
379            retryable: false,
380        },
381        // A retryable cap (`concurrent-logical-workspace-limit`) is a
382        // transient memory refusal: drivers retry it, and the message stays
383        // the engine's. A non-retryable cap is the same client memory code
384        // as `Capacity`.
385        Error::ResourceLimit { retryable, .. } => ErrorInfo {
386            neo4j_code: if *retryable {
387                MEMORY_POOL_OUT_OF_MEMORY_CODE
388            } else {
389                TRANSACTION_OUT_OF_MEMORY_CODE
390            },
391            gql_status: GQLSTATUS_GENERAL,
392            stage: Runtime,
393            retryable: *retryable,
394        },
395        Error::Semantic(payload) | Error::Execution(payload) => {
396            let nested = nested_error_class(payload);
397            ErrorInfo {
398                neo4j_code: match nested {
399                    Some(NestedErrorClass::EntityNotFound) => ENTITY_NOT_FOUND_CODE,
400                    _ => SEMANTIC_ERROR_CODE,
401                },
402                gql_status: stringly_gql_status(nested, GQLSTATUS_GENERAL),
403                stage: Runtime,
404                retryable: false,
405            }
406        }
407        // The creation condition is typed, so it carries its own row rather
408        // than a token the classifier recovers from the rendered message.
409        // Its client code is the constraint code every creation over
410        // violating data has always reported (the legacy
411        // `ConstraintVerificationFailed` class the bindings keep), and its
412        // documented GQLSTATUS is `50N11`.
413        Error::ConstraintCreationFailed { .. } => ErrorInfo {
414            neo4j_code: CONSTRAINT_VALIDATION_FAILED_CODE,
415            gql_status: GQLSTATUS_CONSTRAINT_CREATION_FAILED,
416            stage: Runtime,
417            retryable: false,
418        },
419        // --- Internal class (ADR-0260): genericized at every trust
420        // boundary. The engine-internal failure carries the internal
421        // GQLSTATUS; the storage/IO/locked family has always ridden the GQL
422        // general code on the HTTP wire, so it does here. ---
423        Error::Internal(_) => INTERNAL_ERROR_INFO,
424        Error::Storage(_) | Error::Io(_) | Error::Locked(_) => ErrorInfo {
425            gql_status: GQLSTATUS_GENERAL,
426            ..INTERNAL_ERROR_INFO
427        },
428    }
429}
430
431#[cfg(test)]
432mod tests;