Skip to main content

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