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 relate_core::{ArithmeticFailure, Error};
19
20/// The `code` of a statement the parser rejects (engine `Syntax`).
21pub const SYNTAX_ERROR_CODE: &str = "Neo.ClientError.Statement.SyntaxError";
22
23/// The `code` sent when a query calls a procedure the engine does not
24/// register (ADR-0138): neo4j-browser branches on the exact Neo4j code for
25/// its `dbms.clientConfig` → `dbms.listConfig` fallback.
26pub const PROCEDURE_NOT_FOUND_CODE: &str = "Neo.ClientError.Procedure.ProcedureNotFound";
27
28/// The `code` of a statement that references an absent parameter
29/// (ADR-0308).
30pub const PARAMETER_MISSING_CODE: &str = "Neo.ClientError.Statement.ParameterMissing";
31
32/// The `code` of an unknown database, from a `db` extra or a `USE` target.
33pub const DATABASE_NOT_FOUND_CODE: &str = "Neo.ClientError.Database.DatabaseNotFound";
34
35/// The `code` of every other caller-facing `Semantic` and `Execution`
36/// engine error.
37pub const SEMANTIC_ERROR_CODE: &str = "Neo.ClientError.Statement.SemanticError";
38
39/// The `code` of a type failure (`Type`, `TypeError`, `InvalidArgumentType`).
40pub const TYPE_ERROR_CODE: &str = "Neo.ClientError.Statement.TypeError";
41
42/// The `code` of a DDL argument-value rejection (`ArgumentError`): the code
43/// Neo4j 2026.09 sends for an invalid `OPTIONS`/`indexConfig` value
44/// (ADR-0489).
45pub const ARGUMENT_ERROR_CODE: &str = "Neo.ClientError.General.InvalidArguments";
46
47/// The `code` of a run-time argument rejection (`ArgumentValue`): what Neo4j
48/// 2026.10.1 sends for `range()`'s zero step and for the
49/// `substring()`/`left()`/`right()` int32-range rejections — the same
50/// `ArgumentError` class as [`ARGUMENT_ERROR_CODE`], a different stage.
51pub const ARGUMENT_VALUE_ERROR_CODE: &str = "Neo.ClientError.Statement.ArgumentError";
52
53/// The `code` of an arithmetic failure (`Arithmetic`: division or modulo by
54/// zero, rounding necessary).
55pub const ARITHMETIC_ERROR_CODE: &str = "Neo.ClientError.Statement.ArithmeticError";
56
57/// The `code` of a uniqueness-constraint violation.
58pub const CONSTRAINT_VALIDATION_FAILED_CODE: &str =
59    "Neo.ClientError.Schema.ConstraintValidationFailed";
60
61/// The `code` of a query stopped by `--query-timeout-secs` (the engine's
62/// `Cancelled`).
63pub const TRANSACTION_TIMED_OUT_CODE: &str = "Neo.ClientError.Transaction.TransactionTimedOut";
64
65/// The `code` of a write-write conflict: a `TransientError`, so drivers'
66/// managed transactions retry it (the engine never does, ADR-0017).
67pub const OUTDATED_CODE: &str = "Neo.TransientError.Transaction.Outdated";
68
69/// The `code` of both memory conditions — a write over
70/// `--logical-graph-size-limit` (`Capacity`) and a result over
71/// `--max-result-bytes` — the one Neo4j memory code in the non-retryable
72/// `ClientError` class (ADR-0307 item 4).
73pub const TRANSACTION_OUT_OF_MEMORY_CODE: &str =
74    "Neo.ClientError.General.TransactionOutOfMemoryError";
75
76/// The `code` of a retryable processing cap
77/// (`concurrent-logical-workspace-limit`). Transient, so a driver's managed
78/// transaction retries the statement.
79pub const MEMORY_POOL_OUT_OF_MEMORY_CODE: &str =
80    "Neo.TransientError.General.MemoryPoolOutOfMemoryError";
81
82/// The `code` sent when an internal-class engine error is genericized at a
83/// trust boundary (ADR-0260, ADR-0307).
84pub const UNKNOWN_ERROR_CODE: &str = "Neo.DatabaseError.General.UnknownError";
85
86// The GQLSTATUS column (ADR-0502 §2's error shape). The values are the
87// codes the repo's surfaces emit today: the engine-documented codes of
88// ADR-0116 §9 for the fixed-namespace classes, and the GQL general error
89// code for every class without a class-specific code — exactly the split
90// HTTP's error envelope (ADR-0232) has always made.
91
92/// The GQL general error code: the code of a caller-facing class without a
93/// class-specific GQLSTATUS.
94pub const GQLSTATUS_GENERAL: &str = "42000";
95
96/// The GQLSTATUS of a rejected statement (the `SyntaxError` class).
97pub const GQLSTATUS_SYNTAX: &str = "42N06";
98
99/// The GQLSTATUS of an absent query parameter (ADR-0308).
100const GQLSTATUS_PARAMETER_MISSING: &str = "42N02";
101
102/// The GQLSTATUS of a type failure.
103const GQLSTATUS_TYPE: &str = "22G03";
104
105/// The GQLSTATUS of an unknown database (ADR-0116 §9).
106pub const GQLSTATUS_DATABASE_NOT_FOUND: &str = "42N00";
107
108/// The GQLSTATUS of an unsupported administration command (ADR-0116 §9).
109const GQLSTATUS_UNSUPPORTED_ADMINISTRATION_COMMAND: &str = "51N27";
110
111/// The GQLSTATUS of a write against the read-only `system_ontologies`
112/// namespace (ADR-0116 §9).
113const GQLSTATUS_WRITE_ON_READ_ONLY: &str = "42N18";
114
115/// The GQLSTATUS of an engine-internal failure.
116const GQLSTATUS_INTERNAL: &str = "50N42";
117
118/// Which stage of statement handling an error belongs to (ADR-0319): a
119/// compile-class error fails the statement before any work is done (Bolt's
120/// RUN), a runtime-class error is discovered while producing rows (Bolt's
121/// first PULL/DISCARD), and an internal-class error is not the statement's
122/// fault and is genericized at every trust boundary (ADR-0260).
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub enum ErrorStage {
125    /// The statement itself is rejected: the RUN fails under the code.
126    Compile,
127    /// Discovered while executing: reported at the first row pull.
128    Runtime,
129    /// Engine-internal: genericized for the client (ADR-0260).
130    Internal,
131}
132
133impl ErrorStage {
134    /// The one string spelling of the stage (ADR-0502 §2: the error shape's
135    /// `stage` field) — `"compile"`, `"runtime"` or `"internal"`. The C ABI
136    /// and the Python binding both render it from here, so the spelling is
137    /// single-sourced.
138    ///
139    /// ```
140    /// use relate_error::ErrorStage;
141    ///
142    /// assert_eq!(ErrorStage::Compile.as_str(), "compile");
143    /// assert_eq!(ErrorStage::Runtime.as_str(), "runtime");
144    /// assert_eq!(ErrorStage::Internal.as_str(), "internal");
145    /// ```
146    pub fn as_str(self) -> &'static str {
147        match self {
148            ErrorStage::Compile => "compile",
149            ErrorStage::Runtime => "runtime",
150            ErrorStage::Internal => "internal",
151        }
152    }
153}
154
155/// The classification of one query-engine error (ADR-0502 §2): everything
156/// the ABI v2 error shape carries beside the message, and everything the
157/// surfaces need to render a failure. Built only by [`error_info`] — the
158/// one exhaustive classification, so a new engine variant does not compile
159/// until it is classified here.
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub struct ErrorInfo {
162    /// The Neo4j status code the caller-facing classes carry; the
163    /// internal class carries the genericized `UnknownError` code
164    /// (ADR-0260).
165    pub neo4j_code: &'static str,
166    /// The GQLSTATUS (the codes the repo's surfaces emit today, see the
167    /// module docs).
168    pub gql_status: &'static str,
169    /// The compile/runtime/internal stage (ADR-0319).
170    pub stage: ErrorStage,
171    /// The drivers' transient test (ADR-0502): whether a driver's managed
172    /// transaction retries the statement. True for a write-write conflict
173    /// and a retryable processing cap, false for everything else.
174    pub retryable: bool,
175}
176
177/// The message a trust boundary may show the client for `e` — the
178/// message-exposure half of ADR-0260 (OPLANE_REQ-00340359), derived from
179/// the one classification beside it: the caller-facing classes carry the
180/// engine's Display text; the internal class carries the fixed
181/// [`INTERNAL_MESSAGE`], because engine-internal, IO, storage and locked
182/// messages can hold file paths and engine internals. A boundary that
183/// wants the original for its own log reads it itself (it has `e`) —
184/// this helper never leaks it.
185pub fn client_message(e: &Error) -> std::borrow::Cow<'_, str> {
186    match error_info(e).stage {
187        ErrorStage::Compile | ErrorStage::Runtime => std::borrow::Cow::Owned(e.to_string()),
188        ErrorStage::Internal => std::borrow::Cow::Borrowed(INTERNAL_MESSAGE),
189    }
190}
191
192/// Log the internal class's original message to stderr — the
193/// boundary-log half of the same ADR-0260 policy
194/// (OPLANE_REQ-00340359): the class whose message [`client_message`]
195/// genericizes is the one whose original an operator needs server-side,
196/// so the stage decision and the log format live here once, beside the
197/// redaction they complement. `boundary` names the calling surface in
198/// the line (`"bolt"`, `"http"`, `"ffi"`); a boundary that gates its
199/// channel (the C ABI's host opt-in) applies its gate at its own call
200/// site.
201pub fn log_internal_original(e: &Error, boundary: &str) {
202    if let ErrorStage::Internal = error_info(e).stage {
203        eprintln!("{boundary} internal error: {e}");
204    }
205}
206
207/// The openCypher error class nested in a still-stringly `Syntax`/
208/// `Semantic`/`Execution` payload: the legacy constraint-class tokens
209/// first, then a leading `<Class>:` name token. [`nested_error_class`]
210/// returns `None` when the payload carries no recognized class — the
211/// caller's variant-level class is then the answer.
212///
213/// The closed vocabulary of that scan: one variant per class name the
214/// engine's CE formatters (`relate_core::ce_messages`,
215/// ADR-0116 §9/ADR-0117 §6) and the legacy constraint classes embed. The
216/// token parsing stays at the scan's one boundary; every consumer matches
217/// the typed variant.
218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
219pub enum NestedErrorClass {
220    /// The legacy constraint family (`ConstraintValidationFailed:` /
221    /// `ConstraintVerificationFailed:` tokens, anywhere in the payload).
222    ConstraintVerificationFailed,
223    /// A DDL argument-value rejection (`ArgumentError:`).
224    ArgumentError,
225    /// A missing node or relationship (`EntityNotFound:`).
226    EntityNotFound,
227    /// A registered procedure's own failure (`ProcedureError:`).
228    ProcedureError,
229    /// A rejected statement (`SyntaxError:`).
230    SyntaxError,
231    /// A semantic rejection (`SemanticError:`).
232    SemanticError,
233    /// An unsupported administration command (ADR-0116 §9).
234    UnsupportedAdministrationCommand,
235    /// A write against the read-only `system_ontologies` namespace
236    /// (ADR-0116 §9).
237    WriteOnReadOnlyAccessDatabase,
238    /// An unknown database (`DatabaseNotFound:`).
239    DatabaseNotFound,
240    /// A transaction-state failure (`TransactionError:`).
241    TransactionError,
242}
243
244impl NestedErrorClass {
245    /// Every class the scan recognizes, in enum order — the one list the
246    /// scan's exact-match half and the round-trip test derive from, so a
247    /// new variant lands in both by construction and the ten spellings are
248    /// written exactly once (in [`as_str`](Self::as_str)).
249    pub(crate) const ALL: [NestedErrorClass; 10] = [
250        NestedErrorClass::ConstraintVerificationFailed,
251        NestedErrorClass::ArgumentError,
252        NestedErrorClass::EntityNotFound,
253        NestedErrorClass::ProcedureError,
254        NestedErrorClass::SyntaxError,
255        NestedErrorClass::SemanticError,
256        NestedErrorClass::UnsupportedAdministrationCommand,
257        NestedErrorClass::WriteOnReadOnlyAccessDatabase,
258        NestedErrorClass::DatabaseNotFound,
259        NestedErrorClass::TransactionError,
260    ];
261
262    /// The one string spelling of the class — the `<Class>:` token the
263    /// engine embeds and the bindings report. Derived from the enum, so
264    /// the spelling is single-sourced.
265    ///
266    /// ```
267    /// use relate_error::{nested_error_class, NestedErrorClass};
268    ///
269    /// assert_eq!(
270    ///     NestedErrorClass::ConstraintVerificationFailed.as_str(),
271    ///     "ConstraintVerificationFailed"
272    /// );
273    /// assert_eq!(
274    ///     nested_error_class("ArgumentError: bad options"),
275    ///     Some(NestedErrorClass::ArgumentError)
276    /// );
277    /// assert_eq!(NestedErrorClass::ArgumentError.as_str(), "ArgumentError");
278    /// ```
279    pub fn as_str(self) -> &'static str {
280        match self {
281            NestedErrorClass::ConstraintVerificationFailed => "ConstraintVerificationFailed",
282            NestedErrorClass::ArgumentError => "ArgumentError",
283            NestedErrorClass::EntityNotFound => "EntityNotFound",
284            NestedErrorClass::ProcedureError => "ProcedureError",
285            NestedErrorClass::SyntaxError => "SyntaxError",
286            NestedErrorClass::SemanticError => "SemanticError",
287            NestedErrorClass::UnsupportedAdministrationCommand => {
288                "UnsupportedAdministrationCommand"
289            }
290            NestedErrorClass::WriteOnReadOnlyAccessDatabase => "WriteOnReadOnlyAccessDatabase",
291            NestedErrorClass::DatabaseNotFound => "DatabaseNotFound",
292            NestedErrorClass::TransactionError => "TransactionError",
293        }
294    }
295}
296
297/// The one canonical scan (AGENTS.md: one canonical helper per policy) of
298/// a still-stringly payload's nested class, consulted by both consumers of
299/// the nested-class fact: [`error_info`]'s GQLSTATUS for these payloads,
300/// and the language bindings' `binding_error_metadata`. A string that
301/// merely resembles a typed class's token does not adopt that class — the
302/// recognized names are the ones [`NestedErrorClass`] closes over.
303pub fn nested_error_class(payload: &str) -> Option<NestedErrorClass> {
304    // The one documented alias: the legacy constraint class was spelled
305    // `ConstraintValidationFailed:` and can appear anywhere in the payload,
306    // not only as the leading token, so the leading-name lookup below
307    // cannot carry it.
308    if payload.contains("ConstraintValidationFailed:")
309        || payload.contains("ConstraintVerificationFailed:")
310    {
311        return Some(NestedErrorClass::ConstraintVerificationFailed);
312    }
313    // A leading `<Class>:` name token. The class names are distinct and the
314    // historical match was exact equality, so this lookup over
315    // [`NestedErrorClass::ALL`] is behavior-identical to the exact-match
316    // arms it replaces — and a new variant joins the scan by joining ALL.
317    let name = payload.split_once(':').map(|(name, _)| name.trim())?;
318    NestedErrorClass::ALL
319        .into_iter()
320        .find(|&class| class.as_str() == name)
321}
322
323/// The GQLSTATUS of a still-stringly payload: a recognized nested class
324/// carries its own code (the engine-documented ones of ADR-0116 §9, the
325/// syntax class's own code, the GQL general code for every other nested
326/// class), and a payload with no nested class carries `own` — its
327/// variant's code. The exact split HTTP's error envelope (ADR-0232) has
328/// always made over the same scan.
329fn stringly_gql_status(payload: &str, own: &'static str) -> &'static str {
330    match nested_error_class(payload) {
331        None => own,
332        Some(NestedErrorClass::DatabaseNotFound) => GQLSTATUS_DATABASE_NOT_FOUND,
333        Some(NestedErrorClass::UnsupportedAdministrationCommand) => {
334            GQLSTATUS_UNSUPPORTED_ADMINISTRATION_COMMAND
335        }
336        Some(NestedErrorClass::WriteOnReadOnlyAccessDatabase) => GQLSTATUS_WRITE_ON_READ_ONLY,
337        Some(NestedErrorClass::SyntaxError) => GQLSTATUS_SYNTAX,
338        // The recognized nested classes without a class-specific GQLSTATUS
339        // carry the general code, never the variant's own — named, not
340        // wildcarded, so a future variant forces its own decision here.
341        Some(
342            NestedErrorClass::ConstraintVerificationFailed
343            | NestedErrorClass::ArgumentError
344            | NestedErrorClass::EntityNotFound
345            | NestedErrorClass::ProcedureError
346            | NestedErrorClass::SemanticError
347            | NestedErrorClass::TransactionError,
348        ) => GQLSTATUS_GENERAL,
349    }
350}
351
352/// The fixed client message every trust boundary substitutes for an
353/// internal-class failure (ADR-0260, OPLANE_REQ-00340359): engine-internal,
354/// IO, storage and locked errors — and caught panic payloads — can carry
355/// file paths and engine internals, so their Display text stays
356/// server-side (logged by the boundary) and the client sees this. The
357/// caller-facing classes pass their Display text through verbatim.
358pub const INTERNAL_MESSAGE: &str = "internal error";
359
360/// The internal class's own row of the ADR-0307 table: the genericized
361/// `UnknownError` code, the internal GQLSTATUS, the internal stage, never
362/// retryable (ADR-0260 — an internal failure is not the statement's
363/// fault). [`error_info`] returns exactly this row for an engine-internal
364/// failure, and publishes it for the boundaries that fail before the
365/// engine sees anything — a null or poisoned handle, an argument decode
366/// refusal, a caught panic — so they render the internal classification
367/// without fabricating an engine error to classify.
368pub const INTERNAL_ERROR_INFO: ErrorInfo = ErrorInfo {
369    neo4j_code: UNKNOWN_ERROR_CODE,
370    gql_status: GQLSTATUS_INTERNAL,
371    stage: ErrorStage::Internal,
372    retryable: false,
373};
374
375/// Classify a query-engine error (ADR-0307, single-sourced by ADR-0502 §2).
376/// Exhaustive on purpose: a new engine variant does not compile until it
377/// has a code, a GQLSTATUS, a stage and a retryable verdict — the match
378/// that Bolt's `failures::error_class` used to own alone.
379///
380/// ```
381/// use relate_error::{error_info, ErrorStage, PARAMETER_MISSING_CODE};
382///
383/// let e = relate_core::Error::parameters_missing(["p"]);
384/// let info = error_info(&e);
385/// assert_eq!(info.neo4j_code, PARAMETER_MISSING_CODE);
386/// assert_eq!(info.gql_status, "42N02");
387/// assert_eq!(info.stage, ErrorStage::Compile);
388/// assert!(!info.retryable);
389/// ```
390pub fn error_info(e: &Error) -> ErrorInfo {
391    use ErrorStage::{Compile, Runtime};
392    match e {
393        // --- Compile class: the statement is rejected before any work. ---
394        Error::Syntax(payload) => ErrorInfo {
395            neo4j_code: SYNTAX_ERROR_CODE,
396            gql_status: stringly_gql_status(payload, GQLSTATUS_SYNTAX),
397            stage: Compile,
398            retryable: false,
399        },
400        Error::ProcedureNotFound { .. } => ErrorInfo {
401            neo4j_code: PROCEDURE_NOT_FOUND_CODE,
402            // Live Neo4j sends 42001 for an unregistered procedure, so its
403            // GQLSTATUS is the syntax code even though the binding class is
404            // `ProcedureError` (ADR-0565).
405            gql_status: GQLSTATUS_SYNTAX,
406            stage: Compile,
407            retryable: false,
408        },
409        Error::ParameterMissing(_) => ErrorInfo {
410            neo4j_code: PARAMETER_MISSING_CODE,
411            gql_status: GQLSTATUS_PARAMETER_MISSING,
412            stage: Compile,
413            retryable: false,
414        },
415        Error::DatabaseNotFound { .. } => ErrorInfo {
416            neo4j_code: DATABASE_NOT_FOUND_CODE,
417            gql_status: GQLSTATUS_DATABASE_NOT_FOUND,
418            stage: Compile,
419            retryable: false,
420        },
421        // ADR-0489: a DDL option/index-config argument rejection is
422        // discovered while the statement is validated, before any write, so
423        // it fails the RUN (Neo4j sends it under the same code at RUN).
424        Error::ArgumentError(_) => ErrorInfo {
425            neo4j_code: ARGUMENT_ERROR_CODE,
426            gql_status: GQLSTATUS_GENERAL,
427            stage: Compile,
428            retryable: false,
429        },
430        // --- Runtime class: discovered while producing rows. ---
431        // The function-argument validator's rejections share the DDL
432        // argument class but are discovered while rows are produced, so live
433        // fails the PULL — its own code and stage, not the DDL one's.
434        Error::ArgumentValue { .. } => ErrorInfo {
435            neo4j_code: ARGUMENT_VALUE_ERROR_CODE,
436            gql_status: GQLSTATUS_GENERAL,
437            stage: Runtime,
438            retryable: false,
439        },
440        Error::Type(_) | Error::TypeError(_) | Error::InvalidArgumentType(_) => ErrorInfo {
441            neo4j_code: TYPE_ERROR_CODE,
442            gql_status: GQLSTATUS_TYPE,
443            stage: Runtime,
444            retryable: false,
445        },
446        // Division and modulo by zero were historically `Type` (the
447        // bindings' TypeError class); rounding necessary was a nameless
448        // `Execution` token — the GQLSTATUS column keeps that split.
449        Error::Arithmetic(ArithmeticFailure::DivisionByZero | ArithmeticFailure::ModuloByZero) => {
450            ErrorInfo {
451                neo4j_code: ARITHMETIC_ERROR_CODE,
452                gql_status: GQLSTATUS_TYPE,
453                stage: Runtime,
454                retryable: false,
455            }
456        }
457        Error::Arithmetic(ArithmeticFailure::RoundingNecessary) => ErrorInfo {
458            neo4j_code: ARITHMETIC_ERROR_CODE,
459            gql_status: GQLSTATUS_GENERAL,
460            stage: Runtime,
461            retryable: false,
462        },
463        Error::UniquenessViolation { .. } => ErrorInfo {
464            neo4j_code: CONSTRAINT_VALIDATION_FAILED_CODE,
465            gql_status: GQLSTATUS_GENERAL,
466            stage: Runtime,
467            retryable: false,
468        },
469        Error::Cancelled => ErrorInfo {
470            neo4j_code: TRANSACTION_TIMED_OUT_CODE,
471            gql_status: GQLSTATUS_GENERAL,
472            stage: Runtime,
473            retryable: false,
474        },
475        // A `TransientError` code: drivers' managed transactions retry it.
476        Error::Conflict => ErrorInfo {
477            neo4j_code: OUTDATED_CODE,
478            gql_status: GQLSTATUS_GENERAL,
479            stage: Runtime,
480            retryable: true,
481        },
482        // The capacity family — the graph cap, the expression cap and the
483        // per-record WAL payload cap (ADR-0494) — is the one memory code.
484        Error::Capacity { .. } => ErrorInfo {
485            neo4j_code: TRANSACTION_OUT_OF_MEMORY_CODE,
486            gql_status: GQLSTATUS_GENERAL,
487            stage: Runtime,
488            retryable: false,
489        },
490        // A retryable cap (`concurrent-logical-workspace-limit`) is a
491        // transient memory refusal: drivers retry it, and the message stays
492        // the engine's. A non-retryable cap is the same client memory code
493        // as `Capacity`.
494        Error::ResourceLimit { retryable, .. } => ErrorInfo {
495            neo4j_code: if *retryable {
496                MEMORY_POOL_OUT_OF_MEMORY_CODE
497            } else {
498                TRANSACTION_OUT_OF_MEMORY_CODE
499            },
500            gql_status: GQLSTATUS_GENERAL,
501            stage: Runtime,
502            retryable: *retryable,
503        },
504        Error::Semantic(payload) | Error::Execution(payload) => ErrorInfo {
505            neo4j_code: SEMANTIC_ERROR_CODE,
506            gql_status: stringly_gql_status(payload, GQLSTATUS_GENERAL),
507            stage: Runtime,
508            retryable: false,
509        },
510        // --- Internal class (ADR-0260): genericized at every trust
511        // boundary. The engine-internal failure carries the internal
512        // GQLSTATUS; the storage/IO/locked family has always ridden the GQL
513        // general code on the HTTP wire, so it does here. ---
514        Error::Internal(_) => INTERNAL_ERROR_INFO,
515        Error::Storage(_) | Error::Io(_) | Error::Locked(_) => ErrorInfo {
516            gql_status: GQLSTATUS_GENERAL,
517            ..INTERNAL_ERROR_INFO
518        },
519    }
520}
521
522#[cfg(test)]
523mod tests {
524    use super::*;
525    use relate_core::ErrorKind;
526    use ErrorStage::{Compile, Internal, Runtime};
527
528    /// The published internal row is exactly the row `error_info`
529    /// classifies an engine-internal failure under — the fact
530    /// [`INTERNAL_ERROR_INFO`] exists to single-source for the boundaries
531    /// that fail without an engine error.
532    #[test]
533    fn internal_error_info_is_error_infos_internal_row() {
534        assert_eq!(
535            error_info(&Error::Internal(String::new())),
536            INTERNAL_ERROR_INFO
537        );
538    }
539
540    /// The ADR-0307 table as it now lives here, one row per engine
541    /// variant: the Neo4j code and the compile/runtime/internal stage,
542    /// byte-identical to the table Bolt's failure tests pin over the wire.
543    #[test]
544    fn every_engine_variant_carries_its_adr_0307_code_and_stage() {
545        let rows: Vec<(Error, &str, ErrorStage)> = vec![
546            (Error::syntax("parse error"), SYNTAX_ERROR_CODE, Compile),
547            (
548                Error::procedure_not_found("dbms.noSuchProc"),
549                PROCEDURE_NOT_FOUND_CODE,
550                Compile,
551            ),
552            (
553                Error::parameters_missing(["p"]),
554                PARAMETER_MISSING_CODE,
555                Compile,
556            ),
557            (
558                Error::database_not_found("nosuchdb"),
559                DATABASE_NOT_FOUND_CODE,
560                Compile,
561            ),
562            (
563                Error::argument_error("bad options"),
564                ARGUMENT_ERROR_CODE,
565                Compile,
566            ),
567            (
568                Error::argument_value_kind(ErrorKind::NumberOutOfRange, "range() step"),
569                ARGUMENT_VALUE_ERROR_CODE,
570                Runtime,
571            ),
572            (Error::ty("expected number"), TYPE_ERROR_CODE, Runtime),
573            (Error::type_error("x"), TYPE_ERROR_CODE, Runtime),
574            (Error::invalid_argument_type("x"), TYPE_ERROR_CODE, Runtime),
575            (
576                Error::arithmetic(ArithmeticFailure::DivisionByZero),
577                ARITHMETIC_ERROR_CODE,
578                Runtime,
579            ),
580            (
581                Error::arithmetic(ArithmeticFailure::ModuloByZero),
582                ARITHMETIC_ERROR_CODE,
583                Runtime,
584            ),
585            (
586                Error::arithmetic(ArithmeticFailure::RoundingNecessary),
587                ARITHMETIC_ERROR_CODE,
588                Runtime,
589            ),
590            (
591                Error::uniqueness_violation("p_id"),
592                CONSTRAINT_VALIDATION_FAILED_CODE,
593                Runtime,
594            ),
595            (Error::cancelled(), TRANSACTION_TIMED_OUT_CODE, Runtime),
596            (Error::conflict(), OUTDATED_CODE, Runtime),
597            (
598                Error::capacity(7, 5),
599                TRANSACTION_OUT_OF_MEMORY_CODE,
600                Runtime,
601            ),
602            (
603                Error::capacity_wal_payload(67_108_864, Error::WAL_PAYLOAD_CAP_BYTES),
604                TRANSACTION_OUT_OF_MEMORY_CODE,
605                Runtime,
606            ),
607            (
608                Error::resource_limit(Error::CONCURRENT_LOGICAL_WORKSPACE_LIMIT, 16, true),
609                MEMORY_POOL_OUT_OF_MEMORY_CODE,
610                Runtime,
611            ),
612            (
613                Error::resource_limit(Error::CONCURRENT_LOGICAL_WORKSPACE_LIMIT, 16, false),
614                TRANSACTION_OUT_OF_MEMORY_CODE,
615                Runtime,
616            ),
617            (
618                Error::semantic("variable `n` not defined"),
619                SEMANTIC_ERROR_CODE,
620                Runtime,
621            ),
622            (
623                Error::execution("node ID exhausted"),
624                SEMANTIC_ERROR_CODE,
625                Runtime,
626            ),
627            (Error::internal("boom"), UNKNOWN_ERROR_CODE, Internal),
628            (Error::storage("/x"), UNKNOWN_ERROR_CODE, Internal),
629            (Error::io("os error 2"), UNKNOWN_ERROR_CODE, Internal),
630            (Error::Locked("/x".into()), UNKNOWN_ERROR_CODE, Internal),
631        ];
632        for (e, code, stage) in rows {
633            let i = error_info(&e);
634            assert_eq!(i.neo4j_code, code, "{e}");
635            assert_eq!(i.stage, stage, "{e}");
636        }
637    }
638
639    /// The drivers' transient test: a write-write conflict and a retryable
640    /// processing cap are the only retryable classes.
641    #[test]
642    fn only_the_transient_classes_are_retryable() {
643        let retryable = [
644            Error::conflict(),
645            Error::resource_limit(Error::CONCURRENT_LOGICAL_WORKSPACE_LIMIT, 16, true),
646        ];
647        let not_retryable = [
648            Error::syntax("x"),
649            Error::semantic("x"),
650            Error::argument_error("x"),
651            Error::parameter_missing("x"),
652            Error::database_not_found("x"),
653            Error::ty("x"),
654            Error::arithmetic(ArithmeticFailure::RoundingNecessary),
655            Error::uniqueness_violation("u"),
656            Error::cancelled(),
657            Error::capacity(7, 5),
658            // The non-retryable cap is a client memory refusal: retrying
659            // fails again.
660            Error::resource_limit(Error::CONCURRENT_LOGICAL_WORKSPACE_LIMIT, 16, false),
661            Error::execution("x"),
662            Error::internal("x"),
663            Error::storage("x"),
664            Error::io("x"),
665            Error::Locked("x".into()),
666        ];
667        for e in &retryable {
668            let i = error_info(e);
669            assert!(i.retryable, "{e}");
670        }
671        for e in &not_retryable {
672            let i = error_info(e);
673            assert!(!i.retryable, "{e}");
674        }
675    }
676
677    /// The GQLSTATUS column: the codes the repo's surfaces emit today —
678    /// the engine-documented codes for the fixed-namespace classes and the
679    /// typed classes HTTP maps, the GQL general code for every other
680    /// caller-facing class, the internal code for the engine-internal
681    /// failure.
682    #[test]
683    fn gql_status_is_the_code_the_surfaces_emit_today() {
684        let rows: Vec<(Error, &str)> = vec![
685            (Error::syntax("bad query"), GQLSTATUS_SYNTAX),
686            // A syntax error whose text merely resembles a typed class's
687            // token keeps the syntax code (ADR-0307).
688            (Error::syntax("ProcedureNotFound: dbms.x"), GQLSTATUS_SYNTAX),
689            (Error::procedure_not_found("dbms.x"), GQLSTATUS_SYNTAX),
690            (Error::parameter_missing("p"), GQLSTATUS_PARAMETER_MISSING),
691            (
692                Error::database_not_found("movies"),
693                GQLSTATUS_DATABASE_NOT_FOUND,
694            ),
695            (
696                Error::argument_error("InvalidIndexConfig"),
697                GQLSTATUS_GENERAL,
698            ),
699            (
700                Error::argument_value_kind(ErrorKind::NumberOutOfRange, "range() step"),
701                GQLSTATUS_GENERAL,
702            ),
703            (Error::ty("x"), GQLSTATUS_TYPE),
704            (Error::type_error("x"), GQLSTATUS_TYPE),
705            (Error::invalid_argument_type("x"), GQLSTATUS_TYPE),
706            (
707                Error::arithmetic(ArithmeticFailure::DivisionByZero),
708                GQLSTATUS_TYPE,
709            ),
710            (
711                Error::arithmetic(ArithmeticFailure::RoundingNecessary),
712                GQLSTATUS_GENERAL,
713            ),
714            (Error::uniqueness_violation("u"), GQLSTATUS_GENERAL),
715            (Error::cancelled(), GQLSTATUS_GENERAL),
716            (Error::conflict(), GQLSTATUS_GENERAL),
717            (Error::capacity(7, 5), GQLSTATUS_GENERAL),
718            (
719                Error::resource_limit(Error::CONCURRENT_LOGICAL_WORKSPACE_LIMIT, 16, true),
720                GQLSTATUS_GENERAL,
721            ),
722            (
723                Error::semantic("variable `n` not defined"),
724                GQLSTATUS_GENERAL,
725            ),
726            (Error::execution("node ID exhausted"), GQLSTATUS_GENERAL),
727            (Error::internal("boom"), GQLSTATUS_INTERNAL),
728            (Error::storage("/x"), GQLSTATUS_GENERAL),
729            (Error::io("os error 2"), GQLSTATUS_GENERAL),
730            (Error::Locked("/x".into()), GQLSTATUS_GENERAL),
731        ];
732        for (e, status) in rows {
733            let i = error_info(&e);
734            assert_eq!(i.gql_status, status, "{e}");
735        }
736    }
737
738    /// A nested `<Class>:` token in a still-stringly payload carries its
739    /// own documented GQLSTATUS (ADR-0116 §9), exactly the code HTTP's
740    /// envelope has always resolved through the same scan.
741    #[test]
742    fn a_nested_class_token_carries_its_own_gql_status() {
743        let rows: Vec<(Error, &str)> = vec![
744            (
745                Error::semantic("WriteOnReadOnlyAccessDatabase: No write operations are allowed"),
746                GQLSTATUS_WRITE_ON_READ_ONLY,
747            ),
748            (
749                Error::semantic("UnsupportedAdministrationCommand: CREATE DATABASE foo"),
750                GQLSTATUS_UNSUPPORTED_ADMINISTRATION_COMMAND,
751            ),
752            (
753                Error::semantic("DatabaseNotFound: Graph not found: movies"),
754                GQLSTATUS_DATABASE_NOT_FOUND,
755            ),
756            (
757                Error::execution("ConstraintVerificationFailed: duplicate"),
758                GQLSTATUS_GENERAL,
759            ),
760            // A recognized class without a class-specific code carries the
761            // general code, never the variant's own.
762            (Error::syntax("ArgumentError: x"), GQLSTATUS_GENERAL),
763            (Error::semantic("SyntaxError: x"), GQLSTATUS_SYNTAX),
764            // Lookalike tokens adopt nothing: the variant's own code.
765            (
766                Error::execution("while running: InvalidArgumentType: q"),
767                GQLSTATUS_GENERAL,
768            ),
769            (
770                Error::syntax("TypeError: not the typed class"),
771                GQLSTATUS_SYNTAX,
772            ),
773        ];
774        for (e, status) in rows {
775            let i = error_info(&e);
776            assert_eq!(i.gql_status, status, "{e}");
777        }
778    }
779
780    /// The canonical nested-class scan: the names the engine embeds are
781    /// recovered, lookalikes are not, and every recovered class renders
782    /// the token it was scanned from.
783    #[test]
784    fn nested_error_class_recovers_the_embedded_names() {
785        assert_eq!(
786            nested_error_class("ArgumentError: x"),
787            Some(NestedErrorClass::ArgumentError)
788        );
789        assert_eq!(
790            nested_error_class("outer context: ConstraintVerificationFailed: duplicate key"),
791            Some(NestedErrorClass::ConstraintVerificationFailed)
792        );
793        assert_eq!(
794            nested_error_class("outer: ConstraintValidationFailed: bad"),
795            Some(NestedErrorClass::ConstraintVerificationFailed)
796        );
797        assert_eq!(nested_error_class("no class here"), None);
798        assert_eq!(nested_error_class("nested ParameterMissing: p"), None);
799        assert_eq!(nested_error_class(""), None);
800    }
801
802    /// The closed vocabulary: every class in [`NestedErrorClass::ALL`] is
803    /// recovered from its own rendered token, so the enum, the scan and
804    /// the wire spelling cannot drift.
805    #[test]
806    fn every_nested_class_renders_its_embedded_token() {
807        for class in NestedErrorClass::ALL {
808            let token = class.as_str();
809            let scanned = nested_error_class(&format!("{token}: x"))
810                .unwrap_or_else(|| panic!("token {token} not recognized by the scan"));
811            assert_eq!(scanned.as_str(), token);
812        }
813    }
814}