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