Skip to main content

cortex_hybrid/
error.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3use thiserror::Error;
4
5#[derive(Error, Debug)]
6pub enum CortexError {
7    // ── Tensor / math errors ──────────────────────────────────────────────
8    #[error("tensor rank mismatch: expected {expected}, got {got}")]
9    RankMismatch { expected: usize, got: usize },
10
11    #[error("tensor shape mismatch: expected {expected:?}, got {got:?}")]
12    ShapeMismatch {
13        expected: Vec<usize>,
14        got: Vec<usize>,
15    },
16
17    #[error("dimension mismatch for {op} on axis {axis}: expected {expected}, got {got}")]
18    DimMismatch {
19        op: &'static str,
20        axis: usize,
21        expected: usize,
22        got: usize,
23    },
24
25    #[error("dimension mismatch for matmul: [{m}×{k1}] × [{k2}×{n}]")]
26    MatmulDim {
27        m: usize,
28        k1: usize,
29        k2: usize,
30        n: usize,
31    },
32
33    #[error("index {index} out of bounds for axis {axis} with size {size}")]
34    IndexOutOfBounds {
35        axis: usize,
36        index: usize,
37        size: usize,
38    },
39
40    #[error("token index {index} is out of vocabulary of size {vocab_size}")]
41    TokenIndex { index: usize, vocab_size: usize },
42
43    #[error("invalid epsilon {eps}: must be positive and finite")]
44    InvalidEpsilon { eps: f32 },
45
46    #[error("zero-width axis {axis} is invalid for {op}")]
47    ZeroWidth { op: &'static str, axis: usize },
48
49    #[error("size overflow computing elements or strides for shape {shape:?}")]
50    SizeOverflow { shape: Vec<usize> },
51
52    /// The allocator refused the buffer for `shape` (`bytes` requested).
53    ///
54    /// Distinct from [`SizeOverflow`](Self::SizeOverflow): the shape is
55    /// representable, the machine just cannot back it. Returned instead of
56    /// letting `vec![0.0; n]` abort the process through `handle_alloc_error`.
57    #[error("allocation of {bytes} bytes failed for tensor shape {shape:?}")]
58    AllocationFailed { shape: Vec<usize>, bytes: usize },
59
60    // ── Configuration errors ──────────────────────────────────────────────
61    #[error("invalid configuration: {0}")]
62    InvalidConfig(String),
63
64    // ── Model loading errors ──────────────────────────────────────────────
65    #[error("model load failed for '{path}': {reason}")]
66    ModelLoad { path: String, reason: String },
67
68    #[error("unsupported model format: {0}")]
69    UnsupportedFormat(String),
70
71    #[error("missing tensor '{name}' in model '{path}'")]
72    MissingTensor { name: String, path: String },
73
74    // ── Forward-pass errors ───────────────────────────────────────────────
75    #[error("input length mismatch: expected {expected}, got {got}")]
76    InputLengthMismatch { expected: usize, got: usize },
77
78    #[error("router forward pass failed: {0}")]
79    MoeForward(String),
80
81    /// An external SNN backend (e.g. `neuromod`) rejected a step.
82    #[error("SNN backend step failed: {0}")]
83    SnnBackend(String),
84
85    /// Each expert needs a dedicated backend channel for 1:1 encode/decode.
86    #[error("SNN backend has {channels} channels but the router needs {experts} (one per expert)")]
87    SnnChannelMismatch { experts: usize, channels: usize },
88
89    /// NaN produced at the ANN↔SNN boundary (±Inf stays rankable).
90    #[error("NaN in SNN {stage}")]
91    SnnNan { stage: &'static str },
92
93    /// A gate score or encoded stimulus sample was ±Inf. NaN is reported as
94    /// `SnnNan`. Raised before the backend ticks; `channel` is the expert id
95    /// for a gate score and the backend channel for an encoded sample. Also
96    /// the mapping of `neuromod::StepError::NonFiniteStimulus`.
97    #[error("SNN stimulus at channel {channel} is {value}; expected finite")]
98    SnnInvalidStimulus { channel: usize, value: f32 },
99
100    /// An encoder returned a stimulus whose length differs from the backend
101    /// channel count. Raised before the backend ticks.
102    #[error("SNN encoder returned {got} stimulus values for {expected} channels")]
103    SnnStimulusLength { expected: usize, got: usize },
104
105    /// A spike addressed a channel the backend width cannot represent.
106    #[error("SNN spike at channel {channel} is outside backend width {channels}")]
107    SnnSpikeOutOfRange { channel: usize, channels: usize },
108
109    /// A backend reported the same channel more than once in one tick,
110    /// violating the at-most-once contract of `SnnStepOutput::spikes`.
111    #[error("SNN backend reported channel {channel} more than once in one tick")]
112    SnnDuplicateSpike { channel: usize },
113
114    /// A decoder returned a readout whose length differs from the backend
115    /// channel count.
116    #[error("SNN decoder returned {got} readout values for {expected} channels")]
117    SnnReadoutLength { expected: usize, got: usize },
118
119    /// A decoder readout was negative or infinite; spike activity must be a
120    /// finite, non-negative quantity (NaN is reported as `SnnNan`).
121    #[error("SNN decoder readout at channel {channel} is {value}; expected finite and >= 0")]
122    SnnInvalidReadout { channel: usize, value: f32 },
123
124    /// NaN is rejected before ranking so it never participates in `partial_cmp`.
125    #[error("NaN routing score at expert {expert_id}")]
126    NanRoutingScore { expert_id: usize },
127
128    // ── Stage-execution errors ────────────────────────────────────────────
129    /// A stage identifier was not a valid dotted path (see [`crate::stage::StageId`]).
130    #[error("invalid stage id '{id}': {reason}")]
131    InvalidStageId { id: String, reason: String },
132
133    /// A topology failed structural validation (empty, duplicate ids, or a
134    /// forward/self stage reference).
135    #[error("invalid topology: {reason}")]
136    InvalidTopology { reason: String },
137
138    /// An executor was asked to run a stage kind its capabilities do not cover.
139    #[error("backend '{backend}' does not support stage '{stage_id}' of kind {kind}")]
140    UnsupportedStage {
141        backend: &'static str,
142        stage_id: String,
143        kind: String,
144    },
145
146    /// An external adapter refused an operation its capability report does not cover.
147    ///
148    /// `category` is a stable negotiation key (`stage_kind`, `dtype`, `device`,
149    /// `policy`, …), not a ranking of backends. `stage_id` is set when the
150    /// refusal is about one stage.
151    #[error(
152        "backend '{backend}' does not support {category}{stage}: {detail}",
153        stage = stage_id.as_ref().map(|id| format!(" on stage '{id}'")).unwrap_or_default()
154    )]
155    UnsupportedOperation {
156        backend: &'static str,
157        stage_id: Option<String>,
158        category: &'static str,
159        detail: String,
160    },
161
162    /// A stage descriptor was missing the parameters its kind requires.
163    #[error("stage '{stage_id}' is missing required parameters")]
164    MissingStageParams { stage_id: String },
165
166    /// Parameters are bound for the stage, but for a different stage kind
167    /// (`expected` / `got` are [`crate::stage::StageKindTag`] tokens).
168    #[error("stage '{stage_id}' has parameters for kind {got}, expected {expected}")]
169    StageParamsMismatch {
170        stage_id: String,
171        expected: String,
172        got: String,
173    },
174
175    /// Parameters are bound for the right stage kind but are internally
176    /// inconsistent with it (e.g. a LayerNorm without a bias, or an RMSNorm
177    /// with one).
178    #[error("stage '{stage_id}' has invalid parameters: {reason}")]
179    InvalidStageParams { stage_id: String, reason: String },
180
181    /// A stage received the wrong number of inputs.
182    #[error("stage '{stage_id}' expected {expected} input(s), got {got}")]
183    StageInputArity {
184        stage_id: String,
185        expected: usize,
186        got: usize,
187    },
188
189    /// A stage input had the wrong kind (e.g. tokens where a tensor was expected).
190    #[error("stage '{stage_id}' received an input of the wrong kind at index {index}")]
191    StageInputKind { stage_id: String, index: usize },
192
193    /// A stage input or output used a dtype the executor does not support.
194    #[error("stage '{stage_id}' dtype mismatch: expected {expected}, got {got}")]
195    StageDTypeMismatch {
196        stage_id: String,
197        expected: String,
198        got: String,
199    },
200
201    /// A composition run had no binding for a named external ingress.
202    ///
203    /// The field is deliberately not named `source`: `thiserror` would treat a
204    /// field named `source` as the error cause and require it to implement
205    /// [`std::error::Error`], but here it is just the external ingress name.
206    #[error("missing binding for external stage source '{name}'")]
207    MissingStageBinding { name: String },
208
209    /// A binding name was supplied twice (for example as both token ids and a
210    /// tensor), or a bound stage output names a stage the topology itself
211    /// produces. Rejected at bind / run time instead of shadowing silently.
212    #[error("conflicting binding for stage source '{name}': {reason}")]
213    ConflictingStageBinding { name: String, reason: String },
214
215    /// A stage's execution failed; the wrapped error carries the cause.
216    #[error("stage '{stage_id}' failed: {source}")]
217    StageFailed {
218        stage_id: String,
219        #[source]
220        source: Box<CortexError>,
221    },
222
223    // ── I/O / serde ───────────────────────────────────────────────────────
224    #[error("io error: {0}")]
225    Io(#[from] std::io::Error),
226
227    #[error("serde error: {0}")]
228    Serde(#[from] serde_json::Error),
229
230    #[error("reference JSON input is {actual_bytes} bytes, exceeding the {max_bytes}-byte limit")]
231    SerdeInputTooLarge {
232        max_bytes: usize,
233        actual_bytes: usize,
234    },
235
236    #[error("{0}")]
237    Msg(String),
238}
239
240/// Alias retained so code ported from `corinth-canal` compiles unchanged.
241pub type HybridError = CortexError;
242
243pub type Result<T> = std::result::Result<T, CortexError>;
244
245/// Panic with a pre-1.0 compatibility message. Prefer the corresponding `try_*` API.
246#[inline]
247#[track_caller]
248pub(crate) fn unwrap_compat<T>(result: Result<T>, api: &'static str) -> T {
249    result.unwrap_or_else(|err| {
250        panic!(
251            "{api}: {err}. This panic-style API is retained for pre-1.0 source compatibility; migrate to the corresponding try_* function."
252        )
253    })
254}