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