relate_core/error.rs
1use std::borrow::Cow;
2
3use crate::error_kinds::{
4 duplicate_variable_detail, undefined_variable_detail, unknown_function_detail, ErrorKind,
5};
6use thiserror::Error;
7
8pub type Result<T> = std::result::Result<T, Error>;
9
10/// The per-site fault of a run-time argument rejection
11/// ([`Error::ArgumentValue`]): either one of the sites whose live GQLSTATUS
12/// is its own, or [`Self::General`] for the kind-carrying sites that keep
13/// the general one. Live Neo4j (2026.09/2026.10) reports `point()`'s in-map
14/// rejections under one `ArgumentError` class but a code per rejection
15/// site; the classifier maps each variant to that code, so the code is
16/// data the site names, never recovered from the message text. The fault
17/// also fixes the detail token's [`ErrorKind`] ([`Self::kind`]), so the
18/// two cannot disagree, and the variant carries no second copy of it.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum ArgumentFault {
21 /// The srid does not match the coordinate dimension (22N20).
22 InvalidDimension,
23 /// An unknown srid code or crs name (22N21).
24 UnknownCrs,
25 /// A latitude outside `[-90, 90]` (22N23).
26 InvalidLatitude,
27 /// A NaN or infinite coordinate (22N24).
28 NonFiniteCoordinate,
29 /// A wrong-typed argument (22N27, classified under the type family's
30 /// 22G03).
31 WrongType,
32 /// A site with no GQLSTATUS of its own: the detail token names `kind`
33 /// and the classifier keeps the general status.
34 General(ErrorKind),
35}
36
37impl ArgumentFault {
38 /// The detail token's kind: a value domain, or a wrong type.
39 pub fn kind(self) -> ErrorKind {
40 match self {
41 Self::WrongType => ErrorKind::InvalidArgumentType,
42 Self::InvalidDimension
43 | Self::UnknownCrs
44 | Self::InvalidLatitude
45 | Self::NonFiniteCoordinate => ErrorKind::InvalidArgumentValue,
46 Self::General(kind) => kind,
47 }
48 }
49}
50
51/// Which capacity contract a [`Error::Capacity`] refusal belongs to
52/// (ADR-0042/ADR-0307 vs ADR-0463 vs ADR-0494). Public so a consumer can
53/// render the class without parsing the message; the Display already
54/// differs.
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
56pub enum CapacityKind {
57 /// The live graph + index cap (`--logical-graph-size-limit`, ADR-0042).
58 Graph,
59 /// One expression-built allocation over the per-value cap (ADR-0463).
60 Expression,
61 /// The per-record WAL payload cap (ADR-0650, ADR-0494): one commit
62 /// record whose serialized payload crosses the store's resolved cap
63 /// (`OpenOptions::wal_payload_limit`, defaulting to
64 /// [`Error::WAL_PAYLOAD_CAP_BYTES`]), refused mid-serialization before
65 /// any frame is written. `used` is the counted byte total at which
66 /// the bounded serializer stopped — a lower bound of the record the
67 /// statement tried to commit, never its final size.
68 WalPayload,
69 /// A shortest-path endpoint pattern matched more nodes than the route
70 /// will list to pick its search side (ADR-0556, ADR-0567). `used` is
71 /// the match count at which the bounded scan stopped — a lower bound,
72 /// never the full match count — and `limit` the cap it consulted.
73 SeekCandidates,
74 /// The sealed adjacency tier's per-node type cap (ADR-0599): one node
75 /// holds at most `u16::MAX` distinct relationship types in one
76 /// direction — the span-length field's structural bound, refused at
77 /// admission before the redo is logged. `used` is the distinct-type
78 /// count the node would reach, `limit` the bound.
79 AdjacencyTypes,
80 /// The sealed adjacency tier's stream cap (ADR-0599): one direction's
81 /// arena holds at most `u32::MAX` bytes of encoded hop streams — the
82 /// entry-offset field's structural bound, refused at admission.
83 /// `used` is the arena-plus-live-charge bound at which the batch was
84 /// refused, `limit` the bound.
85 SealedArena,
86 /// The plan-wire budget (ADR-0628, the rust round's refinement): an
87 /// EXPLAIN/PROFILE plan tree nested past
88 /// [`crate::MAX_PLAN_WIRE_DEPTH`](crate::convert::MAX_PLAN_WIRE_DEPTH)
89 /// container levels, refused at the plan-wire crossing before any
90 /// consumer walk recurses. `used` is the level the crossing stopped at
91 /// — a lower bound of the plan's true depth — and `limit` the budget.
92 PlanWire,
93}
94
95/// The one rendering of the three capacity contracts: the graph line is
96/// the historical byte contract (ADR-0042/ADR-0307, byte-identical); the
97/// expression and WAL payload lines are the plain-language user messages
98/// naming what hit the limit, the bound, and the one action.
99fn capacity_detail(kind: CapacityKind, used: u64, limit: u64) -> String {
100 match kind {
101 CapacityKind::Graph => format!("capacity exceeded: used={used} limit={limit}"),
102 CapacityKind::Expression => format!(
103 "This statement tried to build a single value of {}. This is a \
104 safety limit protecting against memory exhaustion (not a \
105 database limit) — build the value in smaller pieces, or raise \
106 it with --expression-memory-limit.",
107 human_bytes(used)
108 ),
109 // The cap is named in the binary unit ADR-0650 states it in, as
110 // rendered from the `limit` the check consulted (the resolved cap,
111 // not a re-spelled constant), so the message and the spec agree;
112 // the remedy names the batching forms that stay under it.
113 CapacityKind::WalPayload => format!(
114 "This statement tried to commit a single WAL record of at \
115 least {}. This is a safety limit protecting against memory \
116 exhaustion — the per-commit WAL payload cap is {} (ADR-0650); \
117 commit the data in smaller transactions (CALL {{ … }} IN \
118 TRANSACTIONS OF n ROWS, or client-side batches).",
119 human_bytes(used),
120 human_bytes(limit)
121 ),
122 CapacityKind::SeekCandidates => format!(
123 "A shortest-path endpoint pattern matches at least {used} nodes; \
124 the search lists at most {limit} to choose its side. This is a \
125 safety limit protecting against memory exhaustion — bind the \
126 endpoint or narrow it with an indexed property."
127 ),
128 CapacityKind::AdjacencyTypes => format!(
129 "One node would hold {used} distinct relationship types in a \
130 single direction; the in-memory adjacency arena addresses at \
131 most {limit}. This is a structural bound of the store, not a \
132 tunable limit — reduce the distinct relationship types on the \
133 node."
134 ),
135 CapacityKind::SealedArena => format!(
136 "One direction's in-memory adjacency arena holds at most {} of \
137 encoded relationship streams; this write would take it to {}. \
138 This embedded store is not built for that scale — keep the \
139 graph's adjacency under the bound.",
140 human_bytes(limit),
141 human_bytes(used)
142 ),
143 CapacityKind::PlanWire => format!(
144 "This statement's query plan nests at least {used} container \
145 levels; the plan-wire budget is {limit}. This is a safety limit \
146 protecting against stack exhaustion — the statement itself \
147 executed; only its plan document is refused. Split the \
148 statement into shorter clause chains to see the plan."
149 ),
150 }
151}
152
153/// A user-facing byte size: MB/GB at whole units, never the raw byte count.
154fn human_bytes(bytes: u64) -> String {
155 const KB: u64 = 1024;
156 const MB: u64 = 1024 * 1024;
157 const GB: u64 = 1024 * 1024 * 1024;
158 if bytes >= GB {
159 format!("{:.0} GB", bytes as f64 / GB as f64)
160 } else if bytes >= MB {
161 format!("{:.0} MB", bytes as f64 / MB as f64)
162 } else if bytes >= KB {
163 format!("{:.0} KB", bytes as f64 / KB as f64)
164 } else {
165 format!("{bytes} bytes")
166 }
167}
168
169#[derive(Debug, Error, Clone, PartialEq, Eq)]
170pub enum Error {
171 #[error("syntax error: {0}")]
172 Syntax(String),
173 #[error("semantic error: {0}")]
174 Semantic(String),
175 /// An argument-value rejection carrying Neo4j's `ArgumentError` class
176 /// (ADR-0489): a schema DDL command's `OPTIONS`/`indexConfig` value that
177 /// the argument validator refuses. The class travels as data so no
178 /// surface has to scan the rendered text for a prefix. Display keeps the
179 /// historical `semantic error: <detail>` rendering, so only the class
180 /// moves, never the detail text.
181 #[error("semantic error: {0}")]
182 ArgumentError(String),
183 /// An argument-value rejection discovered while producing rows — the
184 /// function-argument validator's, carrying Neo4j's `ArgumentError` class
185 /// under its `Neo.ClientError.Statement.ArgumentError` code (22N03). The
186 /// class matches [`Self::ArgumentError`]'s; the stage does not — live
187 /// fails the PULL, not the RUN, so the two cannot share one variant.
188 /// The kind and the detail travel as data, so a consumer reads the
189 /// token ([`Error::typed_detail`]) instead of parsing the rendered
190 /// message. Covers the kind-carrying PULL-time validator sites only:
191 /// `range()`'s zero step, the `substring()`/`left()`/`right()` range
192 /// rejections, list-slice bounds, `point()`'s in-map values, `bar()`'s
193 /// width and the percentile aggregates' argument. The plain-detail
194 /// PULL-time [`Self::ArgumentError`] sites (the temporal constructors,
195 /// `point_component()`, the regex compile failures and the fulltext
196 /// analyzer option) are not migrated here: they carry ADR-0489's
197 /// `InvalidArguments` class today, and moving them would change the
198 /// Neo4j code they report. They stay a separate decision (ADR-0559).
199 #[error("semantic error: {}", kind_prefixed(fault.kind(), detail.as_str()))]
200 ArgumentValue {
201 /// The site's fault: it fixes the detail token's kind
202 /// ([`ArgumentFault::kind`]) and the GQLSTATUS the classifier sends.
203 fault: ArgumentFault,
204 detail: String,
205 },
206 /// A uniqueness-constraint violation raised by constraint validation,
207 /// carrying the violated constraint's name typed, so consumers match the
208 /// class and read the name without parsing the rendered message. The
209 /// Display text is byte-identical to the historical
210 /// `Semantic("ConstraintValidationFailed: `<name>` uniqueness")`
211 /// rendering — stored text, bindings classification and pinned messages
212 /// do not move.
213 #[error("semantic error: {}", uniqueness_violation_detail(name))]
214 UniquenessViolation { name: String },
215 /// A constraint the statement created (or re-derived) failed its data
216 /// check, carrying the wrapped rule failure's bare detail. The creation
217 /// condition is a documented GQLSTATUS (`50N11`) of its own and outranks
218 /// the rule failure's class, so it travels typed — the classifier reads
219 /// the variant, never a token recovered from the rendered text. The
220 /// Display text is byte-identical to the historical
221 /// `Semantic("ConstraintCreationFailed: <detail>")` rendering — stored
222 /// text, bindings classification and pinned messages do not move.
223 #[error("semantic error: ConstraintCreationFailed: {detail}")]
224 ConstraintCreationFailed { detail: String },
225 /// A call to a procedure the engine does not register (ADR-0138),
226 /// carrying the missing procedure's name typed, so consumers match the
227 /// class without a prefix check on the rendered message. The Display
228 /// text is byte-identical to the historical
229 /// `Syntax("ProcedureNotFound: <name>")` rendering — pinned messages do
230 /// not move.
231 #[error("syntax error: ProcedureNotFound: {name}")]
232 ProcedureNotFound { name: String },
233 /// A registered function or procedure call whose argument values fail
234 /// the call's signature at runtime — Neo4j's `ProcedureCallFailed`
235 /// (42001): every runtime `Invalid call signature` rejection the
236 /// temporal family raises (the constructors' non-temporal and duration
237 /// operands, the `(value, pattern)` value side, `duration.between`/
238 /// `duration.in*`'s non-temporal operands, and the timezone STRING
239 /// reading — each live-probed on 2026.10.1). Live fails these at PULL
240 /// with the procedure class, unlike the `InvalidArgumentType`
241 /// rejections that stay the TypeError class.
242 #[error("ProcedureError: {0}")]
243 ProcedureCall(String),
244 /// An argument of the wrong static or runtime type, carrying the detail
245 /// text typed, so consumers match the class without scanning the
246 /// rendered message. The Display text is byte-identical to the
247 /// historical `Type("InvalidArgumentType: <detail>")` rendering.
248 #[error("{}", invalid_argument_type_display(.0))]
249 InvalidArgumentType(String),
250 /// A runtime type failure raised under the legacy `TypeError` detail
251 /// name, carrying the detail text typed. The Display text is
252 /// byte-identical to the historical `Type("TypeError: <detail>")`
253 /// rendering.
254 #[error("{}", type_error_variant_display(.0))]
255 TypeError(String),
256 /// A reference to a query parameter that was not supplied, carrying the
257 /// detail text typed. The Display text is byte-identical to the
258 /// historical `Semantic("ParameterMissing: <detail>")` rendering.
259 #[error("semantic error: ParameterMissing: {0}")]
260 ParameterMissing(String),
261 /// A selected database or `USE` target that is not one of the fixed
262 /// namespaces (ADR-0146, ADR-0307), carrying the name typed. The
263 /// Display text is byte-identical to the historical
264 /// `Semantic("DatabaseNotFound: Graph not found: <name>")` rendering.
265 #[error("semantic error: {}", database_not_found_detail(name))]
266 DatabaseNotFound { name: String },
267 #[error("{}", type_error_display(.0))]
268 Type(String),
269 /// An arithmetic failure raised while evaluating an expression
270 /// (ADR-0307). The Display text is the historical rendering of each
271 /// [`ArithmeticFailure`], composed here from the shared Type-class
272 /// prefix (ADR-0338).
273 #[error("{}", arithmetic_detail(.0))]
274 Arithmetic(ArithmeticFailure),
275 /// Failure raised while evaluating an already parsed and planned query.
276 /// The wrapped text preserves the executor's typed detail.
277 #[error("{0}")]
278 Execution(String),
279 /// A statement stopped through its [`crate::CancelToken`] (ADR-0111,
280 /// ADR-0307). The Display text is byte-identical to the historical
281 /// `Execution("query cancelled")` rendering.
282 #[error("query cancelled")]
283 Cancelled,
284 #[error("write-write conflict")]
285 Conflict,
286 /// A capacity refusal. `kind` selects the user-facing detail: the
287 /// graph-cap contract line (`capacity exceeded: used=… limit=…`,
288 /// ADR-0042/ADR-0307), the ADR-0463 expression-allocation line, or
289 /// the ADR-0494 per-record WAL payload cap line, the last two in
290 /// plain language. All three keep this variant so every surface's
291 /// status mapping is one memory/capacity class.
292 #[error("{}", capacity_detail(*kind, *used, *limit))]
293 Capacity {
294 used: u64,
295 limit: u64,
296 kind: CapacityKind,
297 },
298 /// A processing control refused work. `name` is
299 /// [`Error::CONCURRENT_LOGICAL_WORKSPACE_LIMIT`].
300 /// `retryable` is false when the same call will fail again. `receipt`
301 /// is the logical bytes counted when admission produced the error.
302 #[error("resource limit exceeded: {name} limit={limit}")]
303 ResourceLimit {
304 name: &'static str,
305 limit: u64,
306 retryable: bool,
307 receipt: Option<crate::tokens::ExecutionReceipt>,
308 },
309 #[error("storage error: {0}")]
310 Storage(String),
311 /// A persistent database is already owned by another independent opener.
312 #[error("storage locked: {0}")]
313 Locked(String),
314 #[error("io error: {0}")]
315 Io(String),
316 /// Engine-internal failure that is not the query's fault: worker-thread
317 /// spawn failure or a panic observed across the worker join (ADR-0259).
318 /// Always recoverable by the caller; never an abort.
319 #[error("internal error: {0}")]
320 Internal(String),
321}
322
323impl Error {
324 /// `ResourceLimit::name` for the concurrent logical-workspace admission
325 /// control. `limit` is the pool capacity in logical bytes.
326 pub const CONCURRENT_LOGICAL_WORKSPACE_LIMIT: &'static str =
327 "concurrent-logical-workspace-limit";
328
329 /// `ResourceLimit::name` for a writer mid-`demote` (ADR-0440): new
330 /// writes are refused while commits already past admission finish and
331 /// the handle checkpoints before releasing the writer lease. Always
332 /// `retryable: true` — the caller retries once the follower that is
333 /// about to be promoted takes over.
334 pub const WRITER_DRAINING: &'static str = "writer-draining";
335
336 /// `ResourceLimit::name` for a follower that yielded across a checkpoint
337 /// gap (ADR-0441). Always `retryable: true`. The host drops this engine
338 /// and opens a new one; this process does not load a second graph.
339 pub const FOLLOW_GAP: &'static str = "follow-gap";
340
341 /// The **default** per-record WAL payload cap (ADR-0650): one commit
342 /// record whose serialized JSON crosses this many bytes is refused with
343 /// [`Self::Capacity`] in the [`CapacityKind::WalPayload`] kind
344 /// (ADR-0494) before any frame is written. The *resolved* cap is an
345 /// open-time knob (`OpenOptions::wal_payload_limit`,
346 /// `RELATE_WAL_PAYLOAD_LIMIT`) — this constant is its unset default,
347 /// and the resolved value is the one source the refusal carries as
348 /// `limit` and the storage crate's WAL encoder consumes, so the
349 /// rendered message and the write refusal cannot drift apart
350 /// (ADR-0492; the replay scanner's frame bound is the segment
351 /// format's own, ADR-0650).
352 pub const WAL_PAYLOAD_CAP_BYTES: u64 = 256 * 1024 * 1024;
353
354 pub fn syntax(msg: impl Into<String>) -> Self {
355 Self::Syntax(msg.into())
356 }
357
358 pub fn semantic(msg: impl Into<String>) -> Self {
359 Self::Semantic(msg.into())
360 }
361
362 /// An argument-value rejection in Neo4j's `ArgumentError` class
363 /// (ADR-0489): the class a DDL command's `OPTIONS`/`indexConfig`
364 /// validation carries. The detail text is the historical one, so only
365 /// the class changes.
366 pub fn argument_error(detail: impl Into<String>) -> Self {
367 Self::ArgumentError(detail.into())
368 }
369
370 /// A run-time argument rejection in the `ArgumentError` class whose
371 /// detail carries `kind`'s token — live Neo4j reports `point()`'s in-map
372 /// rejections this way, with the token naming the *kind* of argument
373 /// fault (`InvalidArgumentValue` for a value domain, 22N20/22N21/22N23;
374 /// `InvalidArgumentType` for a wrong type, 22N27 → 22G03; verified
375 /// 2026-11-06). The token composes from [`ErrorKind`], so the class and
376 /// the kind spelling cannot drift apart. One entry point whose name
377 /// states the class and whose token is data — the class can no longer
378 /// be picked by word order, which is the hazard
379 /// [`Self::invalid_argument_type`] (TypeError class) shares a spelling
380 /// with. Distinct from [`Self::argument_error`] by *stage*: this one is
381 /// discovered while producing rows.
382 pub fn argument_value_kind(kind: ErrorKind, detail: impl Into<String>) -> Self {
383 Self::argument_value_fault(ArgumentFault::General(kind), detail)
384 }
385
386 /// A run-time argument rejection at a site with its own live GQLSTATUS
387 /// (`point()`'s in-map rejections): the `fault` names the site and
388 /// fixes the kind token ([`ArgumentFault::kind`]), so the classifier
389 /// sends the site's code while the class, code and stage stay those of
390 /// [`Self::argument_value_kind`].
391 pub fn argument_value_fault(fault: ArgumentFault, detail: impl Into<String>) -> Self {
392 Self::ArgumentValue {
393 fault,
394 detail: detail.into(),
395 }
396 }
397
398 /// A uniqueness violation naming the violated constraint — the typed
399 /// counterpart of the pinned `ConstraintValidationFailed` message text.
400 pub fn uniqueness_violation(name: impl Into<String>) -> Self {
401 Self::UniquenessViolation { name: name.into() }
402 }
403
404 /// A constraint a statement created failed its data check, carrying the
405 /// wrapped rule failure's bare detail — the typed counterpart of the
406 /// pinned `ConstraintCreationFailed: <detail>` message text.
407 pub fn constraint_creation_failed(detail: impl Into<String>) -> Self {
408 Self::ConstraintCreationFailed {
409 detail: detail.into(),
410 }
411 }
412
413 /// A call to an unregistered procedure, naming it — the typed
414 /// counterpart of the pinned `ProcedureNotFound: <name>` message text
415 /// (ADR-0138).
416 pub fn procedure_not_found(name: impl Into<String>) -> Self {
417 Self::ProcedureNotFound { name: name.into() }
418 }
419
420 /// A registered call failing its own signature at runtime — the typed
421 /// counterpart of the temporal family's `Invalid call signature`
422 /// rejections, carrying live's `ProcedureCallFailed` class.
423 pub fn procedure_call(detail: impl Into<String>) -> Self {
424 Self::ProcedureCall(detail.into())
425 }
426
427 /// A call to a function the engine does not register, naming it — the
428 /// one spelling of the pinned `UnknownFunction: unknown function
429 /// <name>()` text (42N48, a SyntaxError-class error). The planner's
430 /// binding-time check and the executor's scalar-eval backstop both call
431 /// this so the two layers cannot drift apart.
432 pub fn unknown_function(name: &str) -> Self {
433 Self::syntax(kind_prefixed(
434 ErrorKind::UnknownFunction,
435 unknown_function_detail(name),
436 ))
437 }
438
439 /// An argument of the wrong type, with the detail text after the pinned
440 /// `InvalidArgumentType:` token — the typed counterpart of the legacy
441 /// `Type("InvalidArgumentType: <detail>")` string.
442 pub fn invalid_argument_type(detail: impl Into<String>) -> Self {
443 Self::InvalidArgumentType(detail.into())
444 }
445
446 /// A wrong-typed argument whose detail is the shared 22N01 sentence
447 /// ([`expected_type_detail`]) — the one constructor of that family, so
448 /// callers stop hand-spelling it.
449 pub fn invalid_argument_type_expected(expected: &str, actual: &str) -> Self {
450 Self::invalid_argument_type(expected_type_detail(expected, actual))
451 }
452
453 /// A value outside an argument's domain, with the detail text after the
454 /// pinned `InvalidArgumentValue:` token — the typed counterpart of the
455 /// legacy `Type("InvalidArgumentValue: <detail>")` string, composing
456 /// the token once.
457 pub fn invalid_argument_value(detail: impl Into<String>) -> Self {
458 Self::ty(kind_prefixed(ErrorKind::InvalidArgumentValue, detail))
459 }
460
461 /// A call outside its arity requirement, with the detail text after the
462 /// pinned `InvalidNumberOfArguments:` token — the one composer of that
463 /// class, so a [`crate::ArityContract`] detail is never token-prefixed twice.
464 pub fn invalid_number_of_arguments(detail: impl Into<String>) -> Self {
465 Self::syntax(kind_prefixed(ErrorKind::InvalidNumberOfArguments, detail))
466 }
467
468 /// A boolean-requiring context that received a non-boolean, with the
469 /// detail text `<ctx> requires a boolean` — the one constructor of the
470 /// ADR-0511 boolean family, so the wording cannot drift between the
471 /// planner's and the executor's requiring sites. `ctx` is the site's
472 /// own naming of the position (`"predicate"`, an operator's spelling,
473 /// or a dynamic context like `"quantifier WHERE"`).
474 pub fn requires_boolean(ctx: &str) -> Self {
475 Self::invalid_argument_type(requires_boolean_detail(ctx))
476 }
477
478 /// The compile-time sibling of [`Self::requires_boolean`]: the same
479 /// `<ctx> requires a boolean` detail over the `Syntax` class, because a
480 /// *statically* non-boolean operand or predicate is Neo4j's compile-time
481 /// `SyntaxError`, while a value whose type is only known per row keeps
482 /// the runtime `TypeError` from [`Self::requires_boolean`]. Both read one
483 /// detail spelling.
484 pub fn static_requires_boolean(ctx: &str) -> Self {
485 Self::syntax(kind_prefixed(
486 ErrorKind::InvalidArgumentType,
487 requires_boolean_detail(ctx),
488 ))
489 }
490
491 /// Re-class an error into the compile-time `Syntax` class carrying only
492 /// its typed *detail* — never its rendered `Display`, whose
493 /// `<class> error:` prefix would be re-embedded and double the class.
494 /// The token-carrying variants keep their pinned token
495 /// ([`Error::typed_detail_text`]); the bare `Type`/`Semantic` payloads
496 /// keep only their detail. A variant with neither (a capacity refusal, a
497 /// cancellation) keeps its own class: its payload is not a string this
498 /// helper can re-home.
499 pub fn into_syntax(self) -> Self {
500 match self {
501 Error::Type(detail) | Error::Semantic(detail) => Self::syntax(detail),
502 other => match other.typed_detail_text() {
503 Some(text) => Self::syntax(text),
504 None => other,
505 },
506 }
507 }
508
509 /// A runtime type failure under the legacy `TypeError` detail name, with
510 /// the detail text after the pinned `TypeError:` token.
511 pub fn type_error(detail: impl Into<String>) -> Self {
512 Self::TypeError(detail.into())
513 }
514
515 /// A query parameter that was not supplied, with the detail text after
516 /// the pinned `ParameterMissing:` token — the typed counterpart of the
517 /// legacy `Semantic("ParameterMissing: <detail>")` string.
518 pub fn parameter_missing(detail: impl Into<String>) -> Self {
519 Self::ParameterMissing(detail.into())
520 }
521
522 /// A statement that references parameters the caller did not supply
523 /// (ADR-0308): the `Expected parameter(s): <names>` detail, the names
524 /// joined by `, ` in the order given. The one spelling of the message.
525 pub fn parameters_missing<'a>(names: impl IntoIterator<Item = &'a str>) -> Self {
526 let names: Vec<&str> = names.into_iter().collect();
527 Self::ParameterMissing(format!("Expected parameter(s): {}", names.join(", ")))
528 }
529
530 /// A database or `USE` target that is not a fixed namespace, naming it
531 /// (ADR-0307) — the typed counterpart of the pinned
532 /// `DatabaseNotFound: Graph not found: <name>` text.
533 pub fn database_not_found(name: impl Into<String>) -> Self {
534 Self::DatabaseNotFound { name: name.into() }
535 }
536
537 /// A reference to a variable the evaluated row does not bind (ADR-0335)
538 /// — the executor-side counterpart of the front-end's
539 /// `UndefinedVariable` semantic error, for expressions the plan-time
540 /// binding walk cannot see (catalog predicates lowered at run time).
541 /// Renders byte-identically to the front-end's error:
542 /// `syntax error: UndefinedVariable: variable '<name>' not defined`.
543 pub fn undefined_variable(name: &str) -> Self {
544 Self::syntax(kind_prefixed(
545 ErrorKind::UndefinedVariable,
546 undefined_variable_detail(name),
547 ))
548 }
549
550 /// A 42I24 `InvalidAggregation`: an aggregate call outside an
551 /// aggregation context. Neo4j reports it as a compile-time
552 /// `SyntaxError` carrying the `InvalidAggregation` kind token, the class
553 /// the front end's typed channel uses; the executor's scalar-eval
554 /// backstop renders the same token through this one constructor.
555 pub fn invalid_aggregation(detail: impl Into<String>) -> Self {
556 Self::syntax(kind_prefixed(ErrorKind::InvalidAggregation, detail))
557 }
558
559 /// A binding that redeclares a name its scope already binds — the
560 /// planner-side counterpart of the front end's `VariableAlreadyBound`.
561 /// Renders `syntax error: VariableAlreadyBound: variable '<name>'
562 /// already declared` from the same detail helper the typed channel
563 /// uses, so the two channels cannot drift.
564 pub fn duplicate_variable(name: &str) -> Self {
565 Self::syntax(kind_prefixed(
566 ErrorKind::VariableAlreadyBound,
567 duplicate_variable_detail(name),
568 ))
569 }
570
571 pub fn ty(msg: impl Into<String>) -> Self {
572 Self::Type(msg.into())
573 }
574
575 pub fn arithmetic(failure: ArithmeticFailure) -> Self {
576 Self::Arithmetic(failure)
577 }
578
579 pub fn execution(error: impl Into<String>) -> Self {
580 Self::Execution(error.into())
581 }
582
583 /// The one spelling of statement cancellation (see `crate::cancel`):
584 /// [`Error::Cancelled`], whose Display is the documented
585 /// `"query cancelled"` contract string.
586 pub fn cancelled() -> Self {
587 Self::Cancelled
588 }
589
590 pub fn conflict() -> Self {
591 Self::Conflict
592 }
593
594 pub fn capacity(used: u64, limit: u64) -> Self {
595 Self::Capacity {
596 used,
597 limit,
598 kind: CapacityKind::Graph,
599 }
600 }
601
602 /// The ADR-0463 expression refusal: one allocation of `bytes` exceeds
603 /// `limit`. The Display is the plain-language line the user sees — what
604 /// was built, in MB/GB, and the one action — never the internal
605 /// bytes/slots vocabulary.
606 pub fn capacity_expression(bytes: u64, limit: u64) -> Self {
607 Self::Capacity {
608 used: bytes,
609 limit,
610 kind: CapacityKind::Expression,
611 }
612 }
613
614 /// The ADR-0494 per-record WAL payload cap refusal: the bounded
615 /// serializer stopped at `counted` bytes — a lower bound of the record
616 /// the statement tried to commit — against the `limit` the check
617 /// consulted (the store's resolved `wal_payload_limit`, defaulting to
618 /// [`Self::WAL_PAYLOAD_CAP_BYTES`], ADR-0650).
619 pub fn capacity_wal_payload(counted: u64, limit: u64) -> Self {
620 Self::Capacity {
621 used: counted,
622 limit,
623 kind: CapacityKind::WalPayload,
624 }
625 }
626
627 /// The shortest-path endpoint refusal: the bounded candidate scan
628 /// stopped at `counted` matches (a lower bound) against the `limit` it
629 /// consulted.
630 pub fn capacity_seek_candidates(counted: u64, limit: u64) -> Self {
631 Self::Capacity {
632 used: counted,
633 limit,
634 kind: CapacityKind::SeekCandidates,
635 }
636 }
637
638 /// The ADR-0599 per-node type refusal: one node would reach `counted`
639 /// distinct relationship types in a single direction, over the span
640 /// length's structural `limit`.
641 pub fn capacity_adjacency_types(counted: u64, limit: u64) -> Self {
642 Self::Capacity {
643 used: counted,
644 limit,
645 kind: CapacityKind::AdjacencyTypes,
646 }
647 }
648
649 /// The ADR-0599 sealed-arena refusal: one direction's arena streams
650 /// plus the batch's growth stand at `counted`, over the entry offset's
651 /// structural `limit`.
652 pub fn capacity_sealed_arena(counted: u64, limit: u64) -> Self {
653 Self::Capacity {
654 used: counted,
655 limit,
656 kind: CapacityKind::SealedArena,
657 }
658 }
659
660 /// The ADR-0628 plan-wire budget refusal: a plan tree nesting past
661 /// [`MAX_PLAN_WIRE_DEPTH`](crate::convert::MAX_PLAN_WIRE_DEPTH)
662 /// container levels, refused at the plan-wire crossing. `used` is the
663 /// level the crossing stopped at (a lower bound of the plan's true
664 /// depth), `limit` the budget.
665 pub fn capacity_plan_wire(used: u64, limit: u64) -> Self {
666 Self::Capacity {
667 used,
668 limit,
669 kind: CapacityKind::PlanWire,
670 }
671 }
672
673 /// A processing control refused work. The display text names the
674 /// control and the configured limit.
675 pub fn resource_limit(name: &'static str, limit: u64, retryable: bool) -> Self {
676 Self::ResourceLimit {
677 name,
678 limit,
679 retryable,
680 receipt: None,
681 }
682 }
683
684 /// [`Self::resource_limit`] plus the token receipt counted so far.
685 pub fn resource_limit_with_receipt(
686 name: &'static str,
687 limit: u64,
688 retryable: bool,
689 receipt: crate::tokens::ExecutionReceipt,
690 ) -> Self {
691 Self::ResourceLimit {
692 name,
693 limit,
694 retryable,
695 receipt: Some(receipt),
696 }
697 }
698
699 /// The token receipt attached to a resource-limit error, when the
700 /// refusal came from token admission.
701 pub fn receipt(&self) -> Option<&crate::tokens::ExecutionReceipt> {
702 match self {
703 Self::ResourceLimit { receipt, .. } => receipt.as_ref(),
704 _ => None,
705 }
706 }
707
708 pub fn storage(msg: impl Into<String>) -> Self {
709 Self::Storage(msg.into())
710 }
711
712 pub fn io(msg: impl Into<String>) -> Self {
713 Self::Io(msg.into())
714 }
715
716 pub fn internal(msg: impl Into<String>) -> Self {
717 Self::Internal(msg.into())
718 }
719
720 /// The pinned class token and detail payload of the seven typed detail
721 /// variants ([`Error::UniquenessViolation`],
722 /// [`Error::ProcedureNotFound`], [`Error::InvalidArgumentType`],
723 /// [`Error::TypeError`], [`Error::ParameterMissing`],
724 /// [`Error::DatabaseNotFound`], [`Error::ArgumentValue`]), single-sourced
725 /// beside the Display attributes that own the same tokens so consumers
726 /// classify and re-render the legacy bare text without re-spelling
727 /// them. The detail borrows where the variant stores it verbatim and is
728 /// owned where Display composes it (the uniqueness violation's
729 /// `` `<name>` uniqueness ``, the CE `Graph not found: <name>`).
730 /// [`Error::ArgumentValue`] is the one exception to the first element
731 /// being a class: its token is the argument-fault *kind* the variant
732 /// carries, so a consumer that wants that variant's class reads the
733 /// engine's error classification instead.
734 /// `None` for every other class.
735 pub fn typed_detail(&self) -> Option<(&'static str, Cow<'_, str>)> {
736 match self {
737 Error::UniquenessViolation { name } => Some((
738 CONSTRAINT_VALIDATION_FAILED,
739 Cow::Owned(uniqueness_detail(name)),
740 )),
741 Error::ArgumentValue { fault, detail } => {
742 Some((fault.kind().as_str(), Cow::Borrowed(detail.as_str())))
743 }
744 Error::DatabaseNotFound { name } => Some((
745 ErrorKind::DatabaseNotFound.as_str(),
746 Cow::Owned(graph_not_found_text(name)),
747 )),
748 Error::ProcedureNotFound { name } => {
749 Some(("ProcedureNotFound", Cow::Borrowed(name.as_str())))
750 }
751 Error::InvalidArgumentType(detail) => {
752 Some(("InvalidArgumentType", Cow::Borrowed(detail.as_str())))
753 }
754 Error::TypeError(detail) => Some(("TypeError", Cow::Borrowed(detail.as_str()))),
755 Error::ParameterMissing(detail) => {
756 Some(("ParameterMissing", Cow::Borrowed(detail.as_str())))
757 }
758 _ => None,
759 }
760 }
761
762 /// The legacy bare detail text — `<Token>: <detail>` — of the typed
763 /// detail variants, exactly as the stringly `Type`/`Semantic` payloads
764 /// spelled it. Built on [`Error::typed_detail`]; `None` for every
765 /// other class.
766 pub fn typed_detail_text(&self) -> Option<String> {
767 let (token, detail) = self.typed_detail()?;
768 Some(format!("{token}: {detail}"))
769 }
770}
771
772impl From<std::io::Error> for Error {
773 fn from(e: std::io::Error) -> Self {
774 Self::Io(e.to_string())
775 }
776}
777
778/// The one spelling of the poisoned-lock policy (AGENTS.md: one canonical
779/// helper per policy): a panicked lock holder fences the operation with an
780/// internal error instead of silently proceeding on possibly torn state.
781/// Every `.lock()?` / `.read()?` on a store mutex or lock resolves through
782/// this impl.
783impl<T> From<std::sync::PoisonError<T>> for Error {
784 fn from(err: std::sync::PoisonError<T>) -> Self {
785 Self::internal(err.to_string())
786 }
787}
788
789/// The pinned class token of a uniqueness-constraint violation, shared by
790/// [`Error::UniquenessViolation`]'s Display composition and
791/// [`Error::typed_detail`] so both spell it from one place.
792const CONSTRAINT_VALIDATION_FAILED: &str = "ConstraintValidationFailed";
793
794/// The Type-class Display prefix, shared by [`Error::Type`]'s attribute and
795/// the other Type-class details composed beside it (ADR-0338), so none of
796/// them can spell the class differently.
797const TYPE_ERROR_PREFIX: &str = "type error";
798
799/// The one negative-`SKIP`/`LIMIT` detail, shared by the front end's
800/// compile-time rule, the planner's rule and the executor's runtime guard:
801/// the layer that fires decides the class, never the wording.
802pub const NEGATIVE_PAGE_BOUND_DETAIL: &str = "SKIP/LIMIT must be non-negative";
803
804/// [`NEGATIVE_PAGE_BOUND_DETAIL`] under its pinned `NegativeIntegerArgument`
805/// token — the one composition both stringly layers use: the planner wraps
806/// it in the compile-time `Syntax` class, the executor's runtime guard in its
807/// `Execution` class.
808pub fn negative_page_bound_text() -> String {
809 kind_prefixed(
810 ErrorKind::NegativeIntegerArgument,
811 NEGATIVE_PAGE_BOUND_DETAIL,
812 )
813}
814
815/// The one spelling of the wrong-type sentence the 22N01 argument errors
816/// and the SEARCH validators share. The expected set is the caller's own
817/// signature; the actual type name is the caller's vocabulary
818/// ([`crate::value_type_name`], or a SEARCH source-kind display name).
819pub fn expected_type_detail(expected: &str, actual: &str) -> String {
820 format!("Expected the value to be of type {expected}, but was of type {actual}")
821}
822
823/// [`Error::Type`]'s Display: the shared Type-class prefix and the detail.
824fn type_error_display(detail: &str) -> String {
825 format!("{TYPE_ERROR_PREFIX}: {detail}")
826}
827
828/// [`Error::InvalidArgumentType`]'s Display: [`type_error_display`] with the
829/// variant's pinned detail token, so the class prefix comes from the one
830/// [`TYPE_ERROR_PREFIX`].
831fn invalid_argument_type_display(detail: &str) -> String {
832 format!(
833 "{}: {detail}",
834 type_error_display(ErrorKind::InvalidArgumentType.as_str())
835 )
836}
837
838/// [`Error::TypeError`]'s Display: [`type_error_display`] with the
839/// variant's pinned detail token, on the same one [`TYPE_ERROR_PREFIX`].
840fn type_error_variant_display(detail: &str) -> String {
841 format!(
842 "{}: {detail}",
843 type_error_display(ErrorKind::TypeError.as_str())
844 )
845}
846
847/// [`Error::Arithmetic`]'s Display: the historical rendering of each
848/// [`ArithmeticFailure`] — [`type_error_display`] for the two division
849/// failures, the bare `ArithmeticError: …` payload for rounding (ADR-0307,
850/// ADR-0338).
851fn arithmetic_detail(failure: &ArithmeticFailure) -> String {
852 match failure {
853 ArithmeticFailure::DivisionByZero | ArithmeticFailure::ModuloByZero => {
854 type_error_display(failure.detail())
855 }
856 ArithmeticFailure::RoundingNecessary => failure.detail().to_string(),
857 }
858}
859
860/// The pinned `` `<name>` uniqueness `` detail of a uniqueness violation,
861/// shared by the Display composition and [`Error::typed_detail`].
862fn uniqueness_detail(name: &str) -> String {
863 format!("`{name}` uniqueness")
864}
865
866/// The bare `ConstraintValidationFailed` detail of a uniqueness violation —
867/// [`Error::UniquenessViolation`]'s Display without the `semantic error: `
868/// prefix, for error composition that embeds the violation's message.
869pub fn uniqueness_violation_detail(name: &str) -> String {
870 format!(
871 "{CONSTRAINT_VALIDATION_FAILED}: {}",
872 uniqueness_detail(name)
873 )
874}
875
876/// The CE text of an unknown graph, `Graph not found: <name>` — the one
877/// place it lives; [`Error::DatabaseNotFound`]'s Display and typed detail
878/// compose it (moved here from `ce_messages` so the dependency stays
879/// one-way `ce_messages -> error.rs`).
880fn graph_not_found_text(name: &str) -> String {
881 format!("Graph not found: {name}")
882}
883
884/// [`Error::DatabaseNotFound`]'s Display without the `semantic error: `
885/// prefix — its [`Error::typed_detail_text`], composed from the typed
886/// kind token and the CE text (ADR-0149).
887fn database_not_found_detail(name: &str) -> String {
888 kind_prefixed(ErrorKind::DatabaseNotFound, graph_not_found_text(name))
889}
890
891/// The one composition of a kind token and its detail —
892/// `"<Kind>: <detail>"` — used by every kind-carrying constructor in this
893/// module.
894fn kind_prefixed(kind: ErrorKind, detail: impl Into<String>) -> String {
895 format!("{}: {}", kind.as_str(), detail.into())
896}
897
898/// The one `<ctx> requires a boolean` detail, shared by the runtime
899/// ([`Error::requires_boolean`]) and compile-time
900/// ([`Error::static_requires_boolean`]) constructors so the wording cannot
901/// drift between the planner's and the executor's requiring sites.
902fn requires_boolean_detail(ctx: &str) -> String {
903 format!("{ctx} requires a boolean")
904}
905
906/// The arithmetic failures the executor raises (ADR-0307), typed so a
907/// surface maps them without reading the message. Each renders exactly as
908/// the stringly error it replaced did.
909#[derive(Debug, Clone, Copy, PartialEq, Eq)]
910pub enum ArithmeticFailure {
911 /// Integer or duration division by zero: `type error: / by zero`.
912 DivisionByZero,
913 /// Integer modulo by zero: `type error: % by zero`.
914 ModuloByZero,
915 /// `round(x, precision, 'UNNECESSARY')` on a value that needs rounding:
916 /// `ArithmeticError: rounding necessary`.
917 RoundingNecessary,
918}
919
920impl ArithmeticFailure {
921 /// The payload the replaced stringly error carried — `/ by zero` and
922 /// `% by zero` (historically `Type`), `ArithmeticError: rounding
923 /// necessary` (historically `Execution`) — for consumers that embed or
924 /// classify that legacy text.
925 pub fn detail(self) -> &'static str {
926 match self {
927 ArithmeticFailure::DivisionByZero => "/ by zero",
928 ArithmeticFailure::ModuloByZero => "% by zero",
929 ArithmeticFailure::RoundingNecessary => "ArithmeticError: rounding necessary",
930 }
931 }
932}
933
934impl std::fmt::Display for ArithmeticFailure {
935 /// The bare legacy payload ([`Self::detail`]); the enclosing
936 /// [`Error::Arithmetic`] composes the Type-class prefix (ADR-0338).
937 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
938 f.write_str(self.detail())
939 }
940}
941
942#[cfg(test)]
943mod tests;