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