relate-error 1.3.0

Typed engine errors and error classification for the Relate graph database
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! The one classification of a query-engine error (ADR-0502 §2): the
//! Neo4j status code, the GQLSTATUS, the compile/runtime/internal stage
//! (ADR-0319's split) and the drivers' transient test, single-sourced in
//! [`error_info`] so Bolt's FAILURE rendering, HTTP's error envelope, the
//! CLI's exit-code classifier, Python and the C ABI are thin derivations —
//! never second tables that drift.
//!
//! The exhaustive match and the Neo4j code constants moved here from Bolt's
//! `failures::error_class` (ADR-0307's table, the most complete of the four
//! historical sites); the move is a move, not a redesign — every consumer
//! keeps its exact observable output. The GQLSTATUS column is new wire data
//! for the typed C ABI v2's one error shape; its values are the codes the
//! repo's surfaces already emit (HTTP's error envelope, ADR-0232 — the
//! engine-documented fixed-namespace codes of ADR-0116 §9 and the GQL
//! general code for every other class), so deriving a surface from
//! [`ErrorInfo`] cannot change what that surface sends today.

use crate::nested_class::{
    nested_error_class, stringly_gql_status, NestedErrorClass,
    GQLSTATUS_CONSTRAINT_CREATION_FAILED, GQLSTATUS_DATABASE_NOT_FOUND, GQLSTATUS_GENERAL,
    GQLSTATUS_INTERNAL, GQLSTATUS_PARAMETER_MISSING, GQLSTATUS_PROCEDURE_CALL, GQLSTATUS_SYNTAX,
    GQLSTATUS_TYPE,
};
use relate_core::{ArgumentFault, ArithmeticFailure, Error};

/// The `code` of a statement the parser rejects (engine `Syntax`).
pub const SYNTAX_ERROR_CODE: &str = "Neo.ClientError.Statement.SyntaxError";

/// The `code` sent when a query calls a procedure the engine does not
/// register (ADR-0138): neo4j-browser branches on the exact Neo4j code for
/// its `dbms.clientConfig` → `dbms.listConfig` fallback.
pub const PROCEDURE_NOT_FOUND_CODE: &str = "Neo.ClientError.Procedure.ProcedureNotFound";

/// A registered call failing its own signature (live's
/// `Neo.ClientError.Procedure.ProcedureCallFailed`, probed on 2026.10.1).
pub const PROCEDURE_CALL_FAILED_CODE: &str = "Neo.ClientError.Procedure.ProcedureCallFailed";

/// The `code` of a statement that references an absent parameter
/// (ADR-0308).
pub const PARAMETER_MISSING_CODE: &str = "Neo.ClientError.Statement.ParameterMissing";

/// The `code` of an unknown database, from a `db` extra or a `USE` target.
pub const DATABASE_NOT_FOUND_CODE: &str = "Neo.ClientError.Database.DatabaseNotFound";

/// The `code` of every other caller-facing `Semantic` and `Execution`
/// engine error.
pub const SEMANTIC_ERROR_CODE: &str = "Neo.ClientError.Statement.SemanticError";

/// The `code` of a well-formed reference to something that does not exist
/// (`EntityNotFound:` token): what Neo4j 2026.10.1 sends for
/// `db.nameFromElementId` over an element id naming an unknown database.
pub const ENTITY_NOT_FOUND_CODE: &str = "Neo.ClientError.Statement.EntityNotFound";

/// The `code` of a type failure (`Type`, `TypeError`, `InvalidArgumentType`).
pub const TYPE_ERROR_CODE: &str = "Neo.ClientError.Statement.TypeError";

/// The `code` of a DDL argument-value rejection (`ArgumentError`): the code
/// Neo4j 2026.09 sends for an invalid `OPTIONS`/`indexConfig` value
/// (ADR-0489).
pub const ARGUMENT_ERROR_CODE: &str = "Neo.ClientError.General.InvalidArguments";

/// The `code` of a run-time argument rejection (`ArgumentValue`): what Neo4j
/// 2026.10.1 sends for `range()`'s zero step and for the
/// `substring()`/`left()`/`right()` int32-range rejections — the same
/// `ArgumentError` class as [`ARGUMENT_ERROR_CODE`], a different stage.
pub const ARGUMENT_VALUE_ERROR_CODE: &str = "Neo.ClientError.Statement.ArgumentError";

/// The GQLSTATUS of a run-time argument rejection's per-site fault — live's
/// codes for `point()`'s in-map rejections (probed on 2026.09.0): the one
/// table a site's code derives from.
fn argument_fault_gql_status(fault: ArgumentFault) -> &'static str {
    match fault {
        ArgumentFault::InvalidDimension => "22N20",
        ArgumentFault::UnknownCrs => "22N21",
        ArgumentFault::InvalidLatitude => "22N23",
        ArgumentFault::NonFiniteCoordinate => "22N24",
        ArgumentFault::WrongType => GQLSTATUS_TYPE,
        ArgumentFault::General(_) => GQLSTATUS_GENERAL,
    }
}

/// The `code` of an arithmetic failure (`Arithmetic`: division or modulo by
/// zero, rounding necessary).
pub const ARITHMETIC_ERROR_CODE: &str = "Neo.ClientError.Statement.ArithmeticError";

/// The `code` of a uniqueness-constraint violation.
pub const CONSTRAINT_VALIDATION_FAILED_CODE: &str =
    "Neo.ClientError.Schema.ConstraintValidationFailed";

/// The `code` of a query stopped by `--query-timeout-secs` (the engine's
/// `Cancelled`).
pub const TRANSACTION_TIMED_OUT_CODE: &str = "Neo.ClientError.Transaction.TransactionTimedOut";

/// The `code` of a write-write conflict: a `TransientError`, so drivers'
/// managed transactions retry it (the engine never does, ADR-0017).
pub const OUTDATED_CODE: &str = "Neo.TransientError.Transaction.Outdated";

/// The `code` of both memory conditions — a write over
/// `--logical-graph-size-limit` (`Capacity`) and a result over
/// `--max-result-bytes` — the one Neo4j memory code in the non-retryable
/// `ClientError` class (ADR-0307 item 4).
pub const TRANSACTION_OUT_OF_MEMORY_CODE: &str =
    "Neo.ClientError.General.TransactionOutOfMemoryError";

/// The `code` of a retryable processing cap
/// (`concurrent-logical-workspace-limit`). Transient, so a driver's managed
/// transaction retries the statement.
pub const MEMORY_POOL_OUT_OF_MEMORY_CODE: &str =
    "Neo.TransientError.General.MemoryPoolOutOfMemoryError";

/// The `code` sent when an internal-class engine error is genericized at a
/// trust boundary (ADR-0260, ADR-0307).
pub const UNKNOWN_ERROR_CODE: &str = "Neo.DatabaseError.General.UnknownError";

// The GQLSTATUS column (ADR-0502 §2's error shape). The values are the
// documented Neo4j GQLSTATUS codes: the engine-documented codes of
// ADR-0116 §9 for the fixed-namespace classes, the documented schema/DDL
// condition codes below (live-verified 2026-11-12 on Neo4j 2026.10.1), and
// the GQL general error code for every class without a class-specific code
// — exactly the split HTTP's error envelope (ADR-0232) has always made.

/// Which stage of statement handling an error belongs to (ADR-0319): a
/// compile-class error fails the statement before any work is done (Bolt's
/// RUN), a runtime-class error is discovered while producing rows (Bolt's
/// first PULL/DISCARD), and an internal-class error is not the statement's
/// fault and is genericized at every trust boundary (ADR-0260).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorStage {
    /// The statement itself is rejected: the RUN fails under the code.
    Compile,
    /// Discovered while executing: reported at the first row pull.
    Runtime,
    /// Engine-internal: genericized for the client (ADR-0260).
    Internal,
}

impl ErrorStage {
    /// The one string spelling of the stage (ADR-0502 §2: the error shape's
    /// `stage` field) — `"compile"`, `"runtime"` or `"internal"`. The C ABI
    /// and the Python binding both render it from here, so the spelling is
    /// single-sourced.
    ///
    /// ```
    /// use relate_error::ErrorStage;
    ///
    /// assert_eq!(ErrorStage::Compile.as_str(), "compile");
    /// assert_eq!(ErrorStage::Runtime.as_str(), "runtime");
    /// assert_eq!(ErrorStage::Internal.as_str(), "internal");
    /// ```
    pub fn as_str(self) -> &'static str {
        match self {
            ErrorStage::Compile => "compile",
            ErrorStage::Runtime => "runtime",
            ErrorStage::Internal => "internal",
        }
    }
}

/// The classification of one query-engine error (ADR-0502 §2): everything
/// the ABI v2 error shape carries beside the message, and everything the
/// surfaces need to render a failure. Built only by [`error_info`] — the
/// one exhaustive classification, so a new engine variant does not compile
/// until it is classified here.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ErrorInfo {
    /// The Neo4j status code the caller-facing classes carry; the
    /// internal class carries the genericized `UnknownError` code
    /// (ADR-0260).
    pub neo4j_code: &'static str,
    /// The GQLSTATUS (the codes the repo's surfaces emit today, see the
    /// module docs).
    pub gql_status: &'static str,
    /// The compile/runtime/internal stage (ADR-0319).
    pub stage: ErrorStage,
    /// The drivers' transient test (ADR-0502): whether a driver's managed
    /// transaction retries the statement. True for a write-write conflict
    /// and a retryable processing cap, false for everything else.
    pub retryable: bool,
}

/// The message a trust boundary may show the client for `e` — the
/// message-exposure half of ADR-0260 (OPLANE_REQ-00340359), derived from
/// the one classification beside it: the caller-facing classes carry the
/// engine's Display text; the internal class carries the fixed
/// [`INTERNAL_MESSAGE`], because engine-internal, IO, storage and locked
/// messages can hold file paths and engine internals. A boundary that
/// wants the original for its own log reads it itself (it has `e`) —
/// this helper never leaks it.
pub fn client_message(e: &Error) -> std::borrow::Cow<'_, str> {
    match error_info(e).stage {
        ErrorStage::Compile | ErrorStage::Runtime => std::borrow::Cow::Owned(e.to_string()),
        ErrorStage::Internal => std::borrow::Cow::Borrowed(INTERNAL_MESSAGE),
    }
}

/// Log the internal class's original message to stderr — the
/// boundary-log half of the same ADR-0260 policy
/// (OPLANE_REQ-00340359): the class whose message [`client_message`]
/// genericizes is the one whose original an operator needs server-side,
/// so the stage decision and the log format live here once, beside the
/// redaction they complement. `boundary` names the calling surface in
/// the line (`"bolt"`, `"http"`, `"ffi"`); a boundary that gates its
/// channel (the C ABI's host opt-in) applies its gate at its own call
/// site.
pub fn log_internal_original(e: &Error, boundary: &str) {
    if let ErrorStage::Internal = error_info(e).stage {
        eprintln!("{boundary} internal error: {e}");
    }
}

/// The openCypher error class nested in a still-stringly `Syntax`/
/// `Semantic`/`Execution` payload: the legacy constraint-class tokens
/// first, then a leading `<Class>:` name token. [`nested_error_class`]
/// returns `None` when the payload carries no recognized class — the
/// caller's variant-level class is then the answer.
///
/// The fixed client message every trust boundary substitutes for an
/// internal-class failure (ADR-0260, OPLANE_REQ-00340359): engine-internal,
/// IO, storage and locked errors — and caught panic payloads — can carry
/// file paths and engine internals, so their Display text stays
/// server-side (logged by the boundary) and the client sees this. The
/// caller-facing classes pass their Display text through verbatim.
pub const INTERNAL_MESSAGE: &str = "internal error";

/// The internal class's own row of the ADR-0307 table: the genericized
/// `UnknownError` code, the internal GQLSTATUS, the internal stage, never
/// retryable (ADR-0260 — an internal failure is not the statement's
/// fault). [`error_info`] returns exactly this row for an engine-internal
/// failure, and publishes it for the boundaries that fail before the
/// engine sees anything — a null or poisoned handle, an argument decode
/// refusal, a caught panic — so they render the internal classification
/// without fabricating an engine error to classify.
pub const INTERNAL_ERROR_INFO: ErrorInfo = ErrorInfo {
    neo4j_code: UNKNOWN_ERROR_CODE,
    gql_status: GQLSTATUS_INTERNAL,
    stage: ErrorStage::Internal,
    retryable: false,
};

/// Classify a query-engine error (ADR-0307, single-sourced by ADR-0502 §2).
/// Exhaustive on purpose: a new engine variant does not compile until it
/// has a code, a GQLSTATUS, a stage and a retryable verdict — the match
/// that Bolt's `failures::error_class` used to own alone.
///
/// ```
/// use relate_error::{error_info, ErrorStage, PARAMETER_MISSING_CODE};
///
/// let e = relate_core::Error::parameters_missing(["p"]);
/// let info = error_info(&e);
/// assert_eq!(info.neo4j_code, PARAMETER_MISSING_CODE);
/// assert_eq!(info.gql_status, "42N02");
/// assert_eq!(info.stage, ErrorStage::Compile);
/// assert!(!info.retryable);
/// ```
pub fn error_info(e: &Error) -> ErrorInfo {
    use ErrorStage::{Compile, Runtime};
    match e {
        // --- Compile class: the statement is rejected before any work. ---
        Error::Syntax(payload) => ErrorInfo {
            neo4j_code: SYNTAX_ERROR_CODE,
            gql_status: stringly_gql_status(nested_error_class(payload), GQLSTATUS_SYNTAX),
            stage: Compile,
            retryable: false,
        },
        Error::ProcedureNotFound { .. } => ErrorInfo {
            neo4j_code: PROCEDURE_NOT_FOUND_CODE,
            // Live Neo4j sends 42001 for an unregistered procedure, so its
            // GQLSTATUS is the syntax code even though the binding class is
            // `ProcedureError` (ADR-0565).
            gql_status: GQLSTATUS_SYNTAX,
            stage: Compile,
            retryable: false,
        },
        Error::ParameterMissing(_) => ErrorInfo {
            neo4j_code: PARAMETER_MISSING_CODE,
            gql_status: GQLSTATUS_PARAMETER_MISSING,
            stage: Compile,
            retryable: false,
        },
        Error::DatabaseNotFound { .. } => ErrorInfo {
            neo4j_code: DATABASE_NOT_FOUND_CODE,
            gql_status: GQLSTATUS_DATABASE_NOT_FOUND,
            stage: Compile,
            retryable: false,
        },
        // ADR-0489: a DDL option/index-config argument rejection is
        // discovered while the statement is validated, before any write, so
        // it fails the RUN (Neo4j sends it under the same code at RUN).
        Error::ArgumentError(_) => ErrorInfo {
            neo4j_code: ARGUMENT_ERROR_CODE,
            gql_status: GQLSTATUS_GENERAL,
            stage: Compile,
            retryable: false,
        },
        // --- Runtime class: discovered while producing rows. ---
        // The function-argument validator's rejections share the DDL
        // argument class but are discovered while rows are produced, so live
        // fails the PULL — its own code and stage, not the DDL one's.
        Error::ArgumentValue { fault, .. } => ErrorInfo {
            neo4j_code: ARGUMENT_VALUE_ERROR_CODE,
            gql_status: argument_fault_gql_status(*fault),
            stage: Runtime,
            retryable: false,
        },
        // A registered call failing its own signature: live fails the PULL
        // with ProcedureCallFailed and its 42001 (probed 2026-11-20 on
        // 2026.10.1 for both the temporal constructors' value rejections
        // and `duration.between`'s non-temporal operands) — the one
        // procedure-family site where the recorded GQLSTATUS is live's,
        // not ADR-0565's compile-time syntax mapping.
        Error::ProcedureCall(_) => ErrorInfo {
            neo4j_code: PROCEDURE_CALL_FAILED_CODE,
            gql_status: GQLSTATUS_PROCEDURE_CALL,
            stage: Runtime,
            retryable: false,
        },
        Error::Type(_) | Error::TypeError(_) | Error::InvalidArgumentType(_) => ErrorInfo {
            neo4j_code: TYPE_ERROR_CODE,
            gql_status: GQLSTATUS_TYPE,
            stage: Runtime,
            retryable: false,
        },
        // Division and modulo by zero were historically `Type` (the
        // bindings' TypeError class); rounding necessary was a nameless
        // `Execution` token — the GQLSTATUS column keeps that split.
        Error::Arithmetic(ArithmeticFailure::DivisionByZero | ArithmeticFailure::ModuloByZero) => {
            ErrorInfo {
                neo4j_code: ARITHMETIC_ERROR_CODE,
                gql_status: GQLSTATUS_TYPE,
                stage: Runtime,
                retryable: false,
            }
        }
        Error::Arithmetic(ArithmeticFailure::RoundingNecessary) => ErrorInfo {
            neo4j_code: ARITHMETIC_ERROR_CODE,
            gql_status: GQLSTATUS_GENERAL,
            stage: Runtime,
            retryable: false,
        },
        Error::UniquenessViolation { .. } => ErrorInfo {
            neo4j_code: CONSTRAINT_VALIDATION_FAILED_CODE,
            gql_status: GQLSTATUS_GENERAL,
            stage: Runtime,
            retryable: false,
        },
        Error::Cancelled => ErrorInfo {
            neo4j_code: TRANSACTION_TIMED_OUT_CODE,
            gql_status: GQLSTATUS_GENERAL,
            stage: Runtime,
            retryable: false,
        },
        // A `TransientError` code: drivers' managed transactions retry it.
        Error::Conflict => ErrorInfo {
            neo4j_code: OUTDATED_CODE,
            gql_status: GQLSTATUS_GENERAL,
            stage: Runtime,
            retryable: true,
        },
        // The capacity family — the graph cap, the expression cap and the
        // per-record WAL payload cap (ADR-0494) — is the one memory code.
        Error::Capacity { .. } => ErrorInfo {
            neo4j_code: TRANSACTION_OUT_OF_MEMORY_CODE,
            gql_status: GQLSTATUS_GENERAL,
            stage: Runtime,
            retryable: false,
        },
        // A retryable cap (`concurrent-logical-workspace-limit`) is a
        // transient memory refusal: drivers retry it, and the message stays
        // the engine's. A non-retryable cap is the same client memory code
        // as `Capacity`.
        Error::ResourceLimit { retryable, .. } => ErrorInfo {
            neo4j_code: if *retryable {
                MEMORY_POOL_OUT_OF_MEMORY_CODE
            } else {
                TRANSACTION_OUT_OF_MEMORY_CODE
            },
            gql_status: GQLSTATUS_GENERAL,
            stage: Runtime,
            retryable: *retryable,
        },
        Error::Semantic(payload) | Error::Execution(payload) => {
            let nested = nested_error_class(payload);
            ErrorInfo {
                neo4j_code: match nested {
                    Some(NestedErrorClass::EntityNotFound) => ENTITY_NOT_FOUND_CODE,
                    _ => SEMANTIC_ERROR_CODE,
                },
                gql_status: stringly_gql_status(nested, GQLSTATUS_GENERAL),
                stage: Runtime,
                retryable: false,
            }
        }
        // The creation condition is typed, so it carries its own row rather
        // than a token the classifier recovers from the rendered message.
        // Its client code is the constraint code every creation over
        // violating data has always reported (the legacy
        // `ConstraintVerificationFailed` class the bindings keep), and its
        // documented GQLSTATUS is `50N11`.
        Error::ConstraintCreationFailed { .. } => ErrorInfo {
            neo4j_code: CONSTRAINT_VALIDATION_FAILED_CODE,
            gql_status: GQLSTATUS_CONSTRAINT_CREATION_FAILED,
            stage: Runtime,
            retryable: false,
        },
        // --- Internal class (ADR-0260): genericized at every trust
        // boundary. The engine-internal failure carries the internal
        // GQLSTATUS; the storage/IO/locked family has always ridden the GQL
        // general code on the HTTP wire, so it does here. ---
        Error::Internal(_) => INTERNAL_ERROR_INFO,
        Error::Storage(_) | Error::Io(_) | Error::Locked(_) => ErrorInfo {
            gql_status: GQLSTATUS_GENERAL,
            ..INTERNAL_ERROR_INFO
        },
    }
}

#[cfg(test)]
mod tests;