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