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 /// A statement stopped because its deadline passed (the statement
285 /// timeout, ADR-0692). `requested` is true when the limit came from
286 /// the request (a driver's `tx_timeout`, an HTTP `maxExecutionTime`)
287 /// rather than the server default; surfaces map it to
288 /// `TransactionTimedOutClientConfiguration` against
289 /// `TransactionTimedOut`.
290 #[error("query timed out after {}", crate::deadline::format_limit(*.limit_ms))]
291 TimedOut { limit_ms: u64, requested: bool },
292 #[error("write-write conflict")]
293 Conflict,
294 /// A capacity refusal. `kind` selects the user-facing detail: the
295 /// graph-cap contract line (`capacity exceeded: used=… limit=…`,
296 /// ADR-0042/ADR-0307), the ADR-0463 expression-allocation line, or
297 /// the ADR-0494 per-record WAL payload cap line, the last two in
298 /// plain language. All three keep this variant so every surface's
299 /// status mapping is one memory/capacity class.
300 #[error("{}", capacity_detail(*kind, *used, *limit))]
301 Capacity {
302 used: u64,
303 limit: u64,
304 kind: CapacityKind,
305 },
306 /// A processing control refused work. `name` is
307 /// [`Error::CONCURRENT_LOGICAL_WORKSPACE_LIMIT`].
308 /// `retryable` is false when the same call will fail again. `receipt`
309 /// is the logical bytes counted when admission produced the error.
310 #[error("resource limit exceeded: {name} limit={limit}")]
311 ResourceLimit {
312 name: &'static str,
313 limit: u64,
314 retryable: bool,
315 receipt: Option<crate::tokens::ExecutionReceipt>,
316 },
317 #[error("storage error: {0}")]
318 Storage(String),
319 /// A persistent database is already owned by another independent opener.
320 #[error("storage locked: {0}")]
321 Locked(String),
322 #[error("io error: {0}")]
323 Io(String),
324 /// Engine-internal failure that is not the query's fault: worker-thread
325 /// spawn failure or a panic observed across the worker join (ADR-0259).
326 /// Always recoverable by the caller; never an abort.
327 #[error("internal error: {0}")]
328 Internal(String),
329}
330
331impl Error {
332 /// `ResourceLimit::name` for the concurrent logical-workspace admission
333 /// control. `limit` is the pool capacity in logical bytes.
334 pub const CONCURRENT_LOGICAL_WORKSPACE_LIMIT: &'static str =
335 "concurrent-logical-workspace-limit";
336
337 /// `ResourceLimit::name` for a writer mid-`demote` (ADR-0440): new
338 /// writes are refused while commits already past admission finish and
339 /// the handle checkpoints before releasing the writer lease. Always
340 /// `retryable: true` — the caller retries once the follower that is
341 /// about to be promoted takes over.
342 pub const WRITER_DRAINING: &'static str = "writer-draining";
343
344 /// `ResourceLimit::name` for a follower that yielded across a checkpoint
345 /// gap (ADR-0441). Always `retryable: true`. The host drops this engine
346 /// and opens a new one; this process does not load a second graph.
347 pub const FOLLOW_GAP: &'static str = "follow-gap";
348
349 /// The **default** per-record WAL payload cap (ADR-0650): one commit
350 /// record whose serialized JSON crosses this many bytes is refused with
351 /// [`Self::Capacity`] in the [`CapacityKind::WalPayload`] kind
352 /// (ADR-0494) before any frame is written. The *resolved* cap is an
353 /// open-time knob (`OpenOptions::wal_payload_limit`,
354 /// `RELATE_WAL_PAYLOAD_LIMIT`) — this constant is its unset default,
355 /// and the resolved value is the one source the refusal carries as
356 /// `limit` and the storage crate's WAL encoder consumes, so the
357 /// rendered message and the write refusal cannot drift apart
358 /// (ADR-0492; the replay scanner's frame bound is the segment
359 /// format's own, ADR-0650).
360 pub const WAL_PAYLOAD_CAP_BYTES: u64 = 256 * 1024 * 1024;
361
362 pub fn syntax(msg: impl Into<String>) -> Self {
363 Self::Syntax(msg.into())
364 }
365
366 pub fn semantic(msg: impl Into<String>) -> Self {
367 Self::Semantic(msg.into())
368 }
369
370 /// An argument-value rejection in Neo4j's `ArgumentError` class
371 /// (ADR-0489): the class a DDL command's `OPTIONS`/`indexConfig`
372 /// validation carries. The detail text is the historical one, so only
373 /// the class changes.
374 pub fn argument_error(detail: impl Into<String>) -> Self {
375 Self::ArgumentError(detail.into())
376 }
377
378 /// A run-time argument rejection in the `ArgumentError` class whose
379 /// detail carries `kind`'s token — live Neo4j reports `point()`'s in-map
380 /// rejections this way, with the token naming the *kind* of argument
381 /// fault (`InvalidArgumentValue` for a value domain, 22N20/22N21/22N23;
382 /// `InvalidArgumentType` for a wrong type, 22N27 → 22G03; verified
383 /// 2026-11-06). The token composes from [`ErrorKind`], so the class and
384 /// the kind spelling cannot drift apart. One entry point whose name
385 /// states the class and whose token is data — the class can no longer
386 /// be picked by word order, which is the hazard
387 /// [`Self::invalid_argument_type`] (TypeError class) shares a spelling
388 /// with. Distinct from [`Self::argument_error`] by *stage*: this one is
389 /// discovered while producing rows.
390 pub fn argument_value_kind(kind: ErrorKind, detail: impl Into<String>) -> Self {
391 Self::argument_value_fault(ArgumentFault::General(kind), detail)
392 }
393
394 /// A run-time argument rejection at a site with its own live GQLSTATUS
395 /// (`point()`'s in-map rejections): the `fault` names the site and
396 /// fixes the kind token ([`ArgumentFault::kind`]), so the classifier
397 /// sends the site's code while the class, code and stage stay those of
398 /// [`Self::argument_value_kind`].
399 pub fn argument_value_fault(fault: ArgumentFault, detail: impl Into<String>) -> Self {
400 Self::ArgumentValue {
401 fault,
402 detail: detail.into(),
403 }
404 }
405
406 /// A uniqueness violation naming the violated constraint — the typed
407 /// counterpart of the pinned `ConstraintValidationFailed` message text.
408 pub fn uniqueness_violation(name: impl Into<String>) -> Self {
409 Self::UniquenessViolation { name: name.into() }
410 }
411
412 /// A constraint a statement created failed its data check, carrying the
413 /// wrapped rule failure's bare detail — the typed counterpart of the
414 /// pinned `ConstraintCreationFailed: <detail>` message text.
415 pub fn constraint_creation_failed(detail: impl Into<String>) -> Self {
416 Self::ConstraintCreationFailed {
417 detail: detail.into(),
418 }
419 }
420
421 /// A call to an unregistered procedure, naming it — the typed
422 /// counterpart of the pinned `ProcedureNotFound: <name>` message text
423 /// (ADR-0138).
424 pub fn procedure_not_found(name: impl Into<String>) -> Self {
425 Self::ProcedureNotFound { name: name.into() }
426 }
427
428 /// A registered call failing its own signature at runtime — the typed
429 /// counterpart of the temporal family's `Invalid call signature`
430 /// rejections, carrying live's `ProcedureCallFailed` class.
431 pub fn procedure_call(detail: impl Into<String>) -> Self {
432 Self::ProcedureCall(detail.into())
433 }
434
435 /// A call to a function the engine does not register, naming it — the
436 /// one spelling of the pinned `UnknownFunction: unknown function
437 /// <name>()` text (42N48, a SyntaxError-class error). The planner's
438 /// binding-time check and the executor's scalar-eval backstop both call
439 /// this so the two layers cannot drift apart.
440 pub fn unknown_function(name: &str) -> Self {
441 Self::syntax(kind_prefixed(
442 ErrorKind::UnknownFunction,
443 unknown_function_detail(name),
444 ))
445 }
446
447 /// An argument of the wrong type, with the detail text after the pinned
448 /// `InvalidArgumentType:` token — the typed counterpart of the legacy
449 /// `Type("InvalidArgumentType: <detail>")` string.
450 pub fn invalid_argument_type(detail: impl Into<String>) -> Self {
451 Self::InvalidArgumentType(detail.into())
452 }
453
454 /// A wrong-typed argument whose detail is the shared 22N01 sentence
455 /// ([`expected_type_detail`]) — the one constructor of that family, so
456 /// callers stop hand-spelling it.
457 pub fn invalid_argument_type_expected(expected: &str, actual: &str) -> Self {
458 Self::invalid_argument_type(expected_type_detail(expected, actual))
459 }
460
461 /// A value outside an argument's domain, with the detail text after the
462 /// pinned `InvalidArgumentValue:` token — the typed counterpart of the
463 /// legacy `Type("InvalidArgumentValue: <detail>")` string, composing
464 /// the token once.
465 pub fn invalid_argument_value(detail: impl Into<String>) -> Self {
466 Self::ty(kind_prefixed(ErrorKind::InvalidArgumentValue, detail))
467 }
468
469 /// A call outside its arity requirement, with the detail text after the
470 /// pinned `InvalidNumberOfArguments:` token — the one composer of that
471 /// class, so a [`crate::ArityContract`] detail is never token-prefixed twice.
472 pub fn invalid_number_of_arguments(detail: impl Into<String>) -> Self {
473 Self::syntax(kind_prefixed(ErrorKind::InvalidNumberOfArguments, detail))
474 }
475
476 /// A boolean-requiring context that received a non-boolean, with the
477 /// detail text `<ctx> requires a boolean` — the one constructor of the
478 /// ADR-0511 boolean family, so the wording cannot drift between the
479 /// planner's and the executor's requiring sites. `ctx` is the site's
480 /// own naming of the position (`"predicate"`, an operator's spelling,
481 /// or a dynamic context like `"quantifier WHERE"`).
482 pub fn requires_boolean(ctx: &str) -> Self {
483 Self::invalid_argument_type(requires_boolean_detail(ctx))
484 }
485
486 /// The compile-time sibling of [`Self::requires_boolean`]: the same
487 /// `<ctx> requires a boolean` detail over the `Syntax` class, because a
488 /// *statically* non-boolean operand or predicate is Neo4j's compile-time
489 /// `SyntaxError`, while a value whose type is only known per row keeps
490 /// the runtime `TypeError` from [`Self::requires_boolean`]. Both read one
491 /// detail spelling.
492 pub fn static_requires_boolean(ctx: &str) -> Self {
493 Self::syntax(kind_prefixed(
494 ErrorKind::InvalidArgumentType,
495 requires_boolean_detail(ctx),
496 ))
497 }
498
499 /// Re-class an error into the compile-time `Syntax` class carrying only
500 /// its typed *detail* — never its rendered `Display`, whose
501 /// `<class> error:` prefix would be re-embedded and double the class.
502 /// The token-carrying variants keep their pinned token
503 /// ([`Error::typed_detail_text`]); the bare `Type`/`Semantic` payloads
504 /// keep only their detail. A variant with neither (a capacity refusal, a
505 /// cancellation) keeps its own class: its payload is not a string this
506 /// helper can re-home.
507 pub fn into_syntax(self) -> Self {
508 match self {
509 Error::Type(detail) | Error::Semantic(detail) => Self::syntax(detail),
510 other => match other.typed_detail_text() {
511 Some(text) => Self::syntax(text),
512 None => other,
513 },
514 }
515 }
516
517 /// A runtime type failure under the legacy `TypeError` detail name, with
518 /// the detail text after the pinned `TypeError:` token.
519 pub fn type_error(detail: impl Into<String>) -> Self {
520 Self::TypeError(detail.into())
521 }
522
523 /// A query parameter that was not supplied, with the detail text after
524 /// the pinned `ParameterMissing:` token — the typed counterpart of the
525 /// legacy `Semantic("ParameterMissing: <detail>")` string.
526 pub fn parameter_missing(detail: impl Into<String>) -> Self {
527 Self::ParameterMissing(detail.into())
528 }
529
530 /// A statement that references parameters the caller did not supply
531 /// (ADR-0308): the `Expected parameter(s): <names>` detail, the names
532 /// joined by `, ` in the order given. The one spelling of the message.
533 pub fn parameters_missing<'a>(names: impl IntoIterator<Item = &'a str>) -> Self {
534 let names: Vec<&str> = names.into_iter().collect();
535 Self::ParameterMissing(format!("Expected parameter(s): {}", names.join(", ")))
536 }
537
538 /// A database or `USE` target that is not a fixed namespace, naming it
539 /// (ADR-0307) — the typed counterpart of the pinned
540 /// `DatabaseNotFound: Graph not found: <name>` text.
541 pub fn database_not_found(name: impl Into<String>) -> Self {
542 Self::DatabaseNotFound { name: name.into() }
543 }
544
545 /// A reference to a variable the evaluated row does not bind (ADR-0335)
546 /// — the executor-side counterpart of the front-end's
547 /// `UndefinedVariable` semantic error, for expressions the plan-time
548 /// binding walk cannot see (catalog predicates lowered at run time).
549 /// Renders byte-identically to the front-end's error:
550 /// `syntax error: UndefinedVariable: variable '<name>' not defined`.
551 pub fn undefined_variable(name: &str) -> Self {
552 Self::syntax(kind_prefixed(
553 ErrorKind::UndefinedVariable,
554 undefined_variable_detail(name),
555 ))
556 }
557
558 /// A 42I24 `InvalidAggregation`: an aggregate call outside an
559 /// aggregation context. Neo4j reports it as a compile-time
560 /// `SyntaxError` carrying the `InvalidAggregation` kind token, the class
561 /// the front end's typed channel uses; the executor's scalar-eval
562 /// backstop renders the same token through this one constructor.
563 pub fn invalid_aggregation(detail: impl Into<String>) -> Self {
564 Self::syntax(kind_prefixed(ErrorKind::InvalidAggregation, detail))
565 }
566
567 /// A binding that redeclares a name its scope already binds — the
568 /// planner-side counterpart of the front end's `VariableAlreadyBound`.
569 /// Renders `syntax error: VariableAlreadyBound: variable '<name>'
570 /// already declared` from the same detail helper the typed channel
571 /// uses, so the two channels cannot drift.
572 pub fn duplicate_variable(name: &str) -> Self {
573 Self::syntax(kind_prefixed(
574 ErrorKind::VariableAlreadyBound,
575 duplicate_variable_detail(name),
576 ))
577 }
578
579 pub fn ty(msg: impl Into<String>) -> Self {
580 Self::Type(msg.into())
581 }
582
583 pub fn arithmetic(failure: ArithmeticFailure) -> Self {
584 Self::Arithmetic(failure)
585 }
586
587 pub fn execution(error: impl Into<String>) -> Self {
588 Self::Execution(error.into())
589 }
590
591 /// The one spelling of statement cancellation (see `crate::cancel`):
592 /// [`Error::Cancelled`], whose Display is the documented
593 /// `"query cancelled"` contract string.
594 pub fn cancelled() -> Self {
595 Self::Cancelled
596 }
597
598 /// The statement-deadline error (see [`crate::deadline`]).
599 pub fn timed_out(limit: std::time::Duration, requested: bool) -> Self {
600 Self::TimedOut {
601 // Rounded up, so a sub-millisecond budget reads `1ms`, never `0s`.
602 limit_ms: u64::try_from(limit.as_nanos().div_ceil(1_000_000)).unwrap_or(u64::MAX),
603 requested,
604 }
605 }
606
607 pub fn conflict() -> Self {
608 Self::Conflict
609 }
610
611 pub fn capacity(used: u64, limit: u64) -> Self {
612 Self::Capacity {
613 used,
614 limit,
615 kind: CapacityKind::Graph,
616 }
617 }
618
619 /// The ADR-0463 expression refusal: one allocation of `bytes` exceeds
620 /// `limit`. The Display is the plain-language line the user sees — what
621 /// was built, in MB/GB, and the one action — never the internal
622 /// bytes/slots vocabulary.
623 pub fn capacity_expression(bytes: u64, limit: u64) -> Self {
624 Self::Capacity {
625 used: bytes,
626 limit,
627 kind: CapacityKind::Expression,
628 }
629 }
630
631 /// The ADR-0494 per-record WAL payload cap refusal: the bounded
632 /// serializer stopped at `counted` bytes — a lower bound of the record
633 /// the statement tried to commit — against the `limit` the check
634 /// consulted (the store's resolved `wal_payload_limit`, defaulting to
635 /// [`Self::WAL_PAYLOAD_CAP_BYTES`], ADR-0650).
636 pub fn capacity_wal_payload(counted: u64, limit: u64) -> Self {
637 Self::Capacity {
638 used: counted,
639 limit,
640 kind: CapacityKind::WalPayload,
641 }
642 }
643
644 /// The shortest-path endpoint refusal: the bounded candidate scan
645 /// stopped at `counted` matches (a lower bound) against the `limit` it
646 /// consulted.
647 pub fn capacity_seek_candidates(counted: u64, limit: u64) -> Self {
648 Self::Capacity {
649 used: counted,
650 limit,
651 kind: CapacityKind::SeekCandidates,
652 }
653 }
654
655 /// The ADR-0599 per-node type refusal: one node would reach `counted`
656 /// distinct relationship types in a single direction, over the span
657 /// length's structural `limit`.
658 pub fn capacity_adjacency_types(counted: u64, limit: u64) -> Self {
659 Self::Capacity {
660 used: counted,
661 limit,
662 kind: CapacityKind::AdjacencyTypes,
663 }
664 }
665
666 /// The ADR-0599 sealed-arena refusal: one direction's arena streams
667 /// plus the batch's growth stand at `counted`, over the entry offset's
668 /// structural `limit`.
669 pub fn capacity_sealed_arena(counted: u64, limit: u64) -> Self {
670 Self::Capacity {
671 used: counted,
672 limit,
673 kind: CapacityKind::SealedArena,
674 }
675 }
676
677 /// The ADR-0628 plan-wire budget refusal: a plan tree nesting past
678 /// [`MAX_PLAN_WIRE_DEPTH`](crate::convert::MAX_PLAN_WIRE_DEPTH)
679 /// container levels, refused at the plan-wire crossing. `used` is the
680 /// level the crossing stopped at (a lower bound of the plan's true
681 /// depth), `limit` the budget.
682 pub fn capacity_plan_wire(used: u64, limit: u64) -> Self {
683 Self::Capacity {
684 used,
685 limit,
686 kind: CapacityKind::PlanWire,
687 }
688 }
689
690 /// A processing control refused work. The display text names the
691 /// control and the configured limit.
692 pub fn resource_limit(name: &'static str, limit: u64, retryable: bool) -> Self {
693 Self::ResourceLimit {
694 name,
695 limit,
696 retryable,
697 receipt: None,
698 }
699 }
700
701 /// [`Self::resource_limit`] plus the token receipt counted so far.
702 pub fn resource_limit_with_receipt(
703 name: &'static str,
704 limit: u64,
705 retryable: bool,
706 receipt: crate::tokens::ExecutionReceipt,
707 ) -> Self {
708 Self::ResourceLimit {
709 name,
710 limit,
711 retryable,
712 receipt: Some(receipt),
713 }
714 }
715
716 /// The token receipt attached to a resource-limit error, when the
717 /// refusal came from token admission.
718 pub fn receipt(&self) -> Option<&crate::tokens::ExecutionReceipt> {
719 match self {
720 Self::ResourceLimit { receipt, .. } => receipt.as_ref(),
721 _ => None,
722 }
723 }
724
725 pub fn storage(msg: impl Into<String>) -> Self {
726 Self::Storage(msg.into())
727 }
728
729 pub fn io(msg: impl Into<String>) -> Self {
730 Self::Io(msg.into())
731 }
732
733 pub fn internal(msg: impl Into<String>) -> Self {
734 Self::Internal(msg.into())
735 }
736
737 /// The pinned class token and detail payload of the seven typed detail
738 /// variants ([`Error::UniquenessViolation`],
739 /// [`Error::ProcedureNotFound`], [`Error::InvalidArgumentType`],
740 /// [`Error::TypeError`], [`Error::ParameterMissing`],
741 /// [`Error::DatabaseNotFound`], [`Error::ArgumentValue`]), single-sourced
742 /// beside the Display attributes that own the same tokens so consumers
743 /// classify and re-render the legacy bare text without re-spelling
744 /// them. The detail borrows where the variant stores it verbatim and is
745 /// owned where Display composes it (the uniqueness violation's
746 /// `` `<name>` uniqueness ``, the CE `Graph not found: <name>`).
747 /// [`Error::ArgumentValue`] is the one exception to the first element
748 /// being a class: its token is the argument-fault *kind* the variant
749 /// carries, so a consumer that wants that variant's class reads the
750 /// engine's error classification instead.
751 /// `None` for every other class.
752 pub fn typed_detail(&self) -> Option<(&'static str, Cow<'_, str>)> {
753 match self {
754 Error::UniquenessViolation { name } => Some((
755 CONSTRAINT_VALIDATION_FAILED,
756 Cow::Owned(uniqueness_detail(name)),
757 )),
758 Error::ArgumentValue { fault, detail } => {
759 Some((fault.kind().as_str(), Cow::Borrowed(detail.as_str())))
760 }
761 Error::DatabaseNotFound { name } => Some((
762 ErrorKind::DatabaseNotFound.as_str(),
763 Cow::Owned(graph_not_found_text(name)),
764 )),
765 Error::ProcedureNotFound { name } => {
766 Some(("ProcedureNotFound", Cow::Borrowed(name.as_str())))
767 }
768 Error::InvalidArgumentType(detail) => {
769 Some(("InvalidArgumentType", Cow::Borrowed(detail.as_str())))
770 }
771 Error::TypeError(detail) => Some(("TypeError", Cow::Borrowed(detail.as_str()))),
772 Error::ParameterMissing(detail) => {
773 Some(("ParameterMissing", Cow::Borrowed(detail.as_str())))
774 }
775 _ => None,
776 }
777 }
778
779 /// The legacy bare detail text — `<Token>: <detail>` — of the typed
780 /// detail variants, exactly as the stringly `Type`/`Semantic` payloads
781 /// spelled it. Built on [`Error::typed_detail`]; `None` for every
782 /// other class.
783 pub fn typed_detail_text(&self) -> Option<String> {
784 let (token, detail) = self.typed_detail()?;
785 Some(format!("{token}: {detail}"))
786 }
787}
788
789impl From<std::io::Error> for Error {
790 fn from(e: std::io::Error) -> Self {
791 Self::Io(e.to_string())
792 }
793}
794
795/// The one spelling of the poisoned-lock policy (AGENTS.md: one canonical
796/// helper per policy): a panicked lock holder fences the operation with an
797/// internal error instead of silently proceeding on possibly torn state.
798/// Every `.lock()?` / `.read()?` on a store mutex or lock resolves through
799/// this impl.
800impl<T> From<std::sync::PoisonError<T>> for Error {
801 fn from(err: std::sync::PoisonError<T>) -> Self {
802 Self::internal(err.to_string())
803 }
804}
805
806/// The pinned class token of a uniqueness-constraint violation, shared by
807/// [`Error::UniquenessViolation`]'s Display composition and
808/// [`Error::typed_detail`] so both spell it from one place.
809const CONSTRAINT_VALIDATION_FAILED: &str = "ConstraintValidationFailed";
810
811/// The Type-class Display prefix, shared by [`Error::Type`]'s attribute and
812/// the other Type-class details composed beside it (ADR-0338), so none of
813/// them can spell the class differently.
814const TYPE_ERROR_PREFIX: &str = "type error";
815
816/// The one negative-`SKIP`/`LIMIT` detail, shared by the front end's
817/// compile-time rule, the planner's rule and the executor's runtime guard:
818/// the layer that fires decides the class, never the wording.
819pub const NEGATIVE_PAGE_BOUND_DETAIL: &str = "SKIP/LIMIT must be non-negative";
820
821/// [`NEGATIVE_PAGE_BOUND_DETAIL`] under its pinned `NegativeIntegerArgument`
822/// token — the one composition both stringly layers use: the planner wraps
823/// it in the compile-time `Syntax` class, the executor's runtime guard in its
824/// `Execution` class.
825pub fn negative_page_bound_text() -> String {
826 kind_prefixed(
827 ErrorKind::NegativeIntegerArgument,
828 NEGATIVE_PAGE_BOUND_DETAIL,
829 )
830}
831
832/// A `CALL { … } IN TRANSACTIONS` modifier's positive-integer sentence
833/// ([`crate::integer_args`]) under the pinned `InvalidArgument` token —
834/// the one composition the planner's non-positive literal arms call (the
835/// SKIP/LIMIT shape: the token's single home is here, the layer that
836/// fires decides only the class).
837pub fn invalid_argument_text(detail: impl Into<String>) -> String {
838 format!("InvalidArgument: {}", detail.into())
839}
840
841/// A modifier's range sentence under the pinned `NumberOutOfRange` token —
842/// the sibling of [`invalid_argument_text`] for the sites whose plan-time
843/// rejection carries that token (the retry duration); the layer that fires
844/// decides only the class.
845pub fn number_out_of_range_text(detail: impl Into<String>) -> String {
846 kind_prefixed(ErrorKind::NumberOutOfRange, detail)
847}
848
849/// The one spelling of the wrong-type sentence the 22N01 argument errors
850/// and the SEARCH validators share. The expected set is the caller's own
851/// signature; the actual type name is the caller's vocabulary
852/// ([`crate::value_type_name`], or a SEARCH source-kind display name).
853pub fn expected_type_detail(expected: &str, actual: &str) -> String {
854 format!("Expected the value to be of type {expected}, but was of type {actual}")
855}
856
857/// [`Error::Type`]'s Display: the shared Type-class prefix and the detail.
858fn type_error_display(detail: &str) -> String {
859 format!("{TYPE_ERROR_PREFIX}: {detail}")
860}
861
862/// [`Error::InvalidArgumentType`]'s Display: [`type_error_display`] with the
863/// variant's pinned detail token, so the class prefix comes from the one
864/// [`TYPE_ERROR_PREFIX`].
865fn invalid_argument_type_display(detail: &str) -> String {
866 format!(
867 "{}: {detail}",
868 type_error_display(ErrorKind::InvalidArgumentType.as_str())
869 )
870}
871
872/// [`Error::TypeError`]'s Display: [`type_error_display`] with the
873/// variant's pinned detail token, on the same one [`TYPE_ERROR_PREFIX`].
874fn type_error_variant_display(detail: &str) -> String {
875 format!(
876 "{}: {detail}",
877 type_error_display(ErrorKind::TypeError.as_str())
878 )
879}
880
881/// [`Error::Arithmetic`]'s Display: the historical rendering of each
882/// [`ArithmeticFailure`] — [`type_error_display`] for the two division
883/// failures, the bare `ArithmeticError: …` payload for rounding (ADR-0307,
884/// ADR-0338).
885fn arithmetic_detail(failure: &ArithmeticFailure) -> String {
886 match failure {
887 ArithmeticFailure::DivisionByZero | ArithmeticFailure::ModuloByZero => {
888 type_error_display(failure.detail())
889 }
890 ArithmeticFailure::RoundingNecessary => failure.detail().to_string(),
891 }
892}
893
894/// The pinned `` `<name>` uniqueness `` detail of a uniqueness violation,
895/// shared by the Display composition and [`Error::typed_detail`].
896fn uniqueness_detail(name: &str) -> String {
897 format!("`{name}` uniqueness")
898}
899
900/// The bare `ConstraintValidationFailed` detail of a uniqueness violation —
901/// [`Error::UniquenessViolation`]'s Display without the `semantic error: `
902/// prefix, for error composition that embeds the violation's message.
903pub fn uniqueness_violation_detail(name: &str) -> String {
904 format!(
905 "{CONSTRAINT_VALIDATION_FAILED}: {}",
906 uniqueness_detail(name)
907 )
908}
909
910/// The CE text of an unknown graph, `Graph not found: <name>` — the one
911/// place it lives; [`Error::DatabaseNotFound`]'s Display and typed detail
912/// compose it (moved here from `ce_messages` so the dependency stays
913/// one-way `ce_messages -> error.rs`).
914fn graph_not_found_text(name: &str) -> String {
915 format!("Graph not found: {name}")
916}
917
918/// [`Error::DatabaseNotFound`]'s Display without the `semantic error: `
919/// prefix — its [`Error::typed_detail_text`], composed from the typed
920/// kind token and the CE text (ADR-0149).
921fn database_not_found_detail(name: &str) -> String {
922 kind_prefixed(ErrorKind::DatabaseNotFound, graph_not_found_text(name))
923}
924
925/// The one composition of a kind token and its detail —
926/// `"<Kind>: <detail>"` — used by every kind-carrying constructor in this
927/// module.
928fn kind_prefixed(kind: ErrorKind, detail: impl Into<String>) -> String {
929 format!("{}: {}", kind.as_str(), detail.into())
930}
931
932/// The one `<ctx> requires a boolean` detail, shared by the runtime
933/// ([`Error::requires_boolean`]) and compile-time
934/// ([`Error::static_requires_boolean`]) constructors so the wording cannot
935/// drift between the planner's and the executor's requiring sites.
936fn requires_boolean_detail(ctx: &str) -> String {
937 format!("{ctx} requires a boolean")
938}
939
940/// The arithmetic failures the executor raises (ADR-0307), typed so a
941/// surface maps them without reading the message. Each renders exactly as
942/// the stringly error it replaced did.
943#[derive(Debug, Clone, Copy, PartialEq, Eq)]
944pub enum ArithmeticFailure {
945 /// Integer or duration division by zero: `type error: / by zero`.
946 DivisionByZero,
947 /// Integer modulo by zero: `type error: % by zero`.
948 ModuloByZero,
949 /// `round(x, precision, 'UNNECESSARY')` on a value that needs rounding:
950 /// `ArithmeticError: rounding necessary`.
951 RoundingNecessary,
952}
953
954impl ArithmeticFailure {
955 /// The payload the replaced stringly error carried — `/ by zero` and
956 /// `% by zero` (historically `Type`), `ArithmeticError: rounding
957 /// necessary` (historically `Execution`) — for consumers that embed or
958 /// classify that legacy text.
959 pub fn detail(self) -> &'static str {
960 match self {
961 ArithmeticFailure::DivisionByZero => "/ by zero",
962 ArithmeticFailure::ModuloByZero => "% by zero",
963 ArithmeticFailure::RoundingNecessary => "ArithmeticError: rounding necessary",
964 }
965 }
966}
967
968impl std::fmt::Display for ArithmeticFailure {
969 /// The bare legacy payload ([`Self::detail`]); the enclosing
970 /// [`Error::Arithmetic`] composes the Type-class prefix (ADR-0338).
971 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
972 f.write_str(self.detail())
973 }
974}
975
976#[cfg(test)]
977mod tests;