cortex-hybrid 0.2.0

Backend-neutral ANN stage layer and deterministic Vec reference backend for hybrid ANN/SNN systems.
Documentation
// 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."
        )
    })
}