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