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