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