Skip to main content

csp_solver/
error.rs

1//! Unified error family for the solver's public API surface.
2//!
3//! Reconciled from grand-audit Pass 2 prototype 14 (`api-error-taxonomy`)
4//! onto the Pass-3 composed tree (Pass 3 `py-module-reconciliation`, T9).
5//!
6//! Before this, the crate had two independent, incomplete error shapes:
7//! `Unsatisfiable` (a bare unit struct, `lib.rs`) and `AssignmentError`
8//! (`builder/assignment.rs`, five variants scoped to the assignment-problem
9//! builder only, and — per the Pass-1 `rust-cop-builder` finding —
10//! conflating budget-exhaustion with genuine infeasibility). Every
11//! downstream binding (`py/`, wasm's `isomorphic.rs`) re-derived its own ad
12//! hoc mapping of "something went wrong" onto a bare
13//! `PyRuntimeError`/`JsError` string, which is exactly the "silent/conflated
14//! handling" the audit's fail-explicit precept bans (Pass-1 ledger R15, B0).
15//!
16//! `CspError` is the one family every layer should map 1:1 rather than
17//! reinvent: PyO3 via `create_exception!` (`py/errors.rs`) and wasm via a
18//! typed `WasmCspError` that stamps a `.code` onto a genuine `Error` instance
19//! (`wasm/src/errors.rs`, not reconciled in this pass — see report). `code()`
20//! is the one string all downstream layers agree on.
21//!
22//! Tests: `tests/error.rs`.
23
24use std::fmt;
25
26/// Unified error family for `Csp`/Sudoku/Futoshiki operations exposed
27/// across the PyO3 and wasm boundaries.
28///
29/// Deliberately flat (no nested `Box<dyn Error>` source chaining) — every
30/// downstream binding needs to pattern-match this by value to pick an
31/// exception class / HTTP status, and a flat enum is the cheapest thing
32/// that supports that without reflection.
33#[derive(Debug, Clone, PartialEq)]
34pub enum CspError {
35    /// No solution exists under the current constraints/propagation.
36    /// Maps from the crate's existing [`crate::Unsatisfiable`] marker (kept
37    /// as the internal propagation-layer type; this is the binding-facing
38    /// supertype).
39    Unsatisfiable,
40    /// The search aborted after [`crate::SolveConfig::node_budget`] nodes;
41    /// any solutions returned are best-so-far, not verified optimal or
42    /// exhaustive. Distinct from `Unsatisfiable` — conflating the two was
43    /// Pass-1 finding R8/F12 (`AssignmentBuilder` and `SudokuCSP` both did
44    /// this).
45    BudgetExceeded,
46    /// A caller-supplied argument was structurally invalid: an
47    /// out-of-range position, a malformed numeric key, an unknown enum
48    /// value, mismatched dimensions, etc. Carries a human-readable detail
49    /// string (never leaked Rust-internal panic/debug detail — callers
50    /// construct this variant explicitly, it is never built from a caught
51    /// panic).
52    InvalidInput {
53        /// What was wrong, safe to surface to an API client verbatim.
54        detail: String,
55    },
56    /// A wall-clock deadline elapsed before the search produced a result.
57    /// Distinct from `BudgetExceeded` (a node-count budget, checked at the
58    /// same cadence but triggered by *count* not *time*). Forward-declared
59    /// for the wall-clock `time_budget` deferred item (synthesis-pass1 §3.1
60    /// N11) — the cooperative cancellation flag a caller's own deadline
61    /// should set through the `CancelToken`, so the abort reaches the search
62    /// itself rather than only whatever coroutine or thread is awaiting it.
63    Timeout,
64}
65
66impl fmt::Display for CspError {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        match self {
69            Self::Unsatisfiable => write!(f, "no solution exists under the given constraints"),
70            Self::BudgetExceeded => {
71                write!(
72                    f,
73                    "search exceeded its node budget before finding a solution"
74                )
75            }
76            Self::InvalidInput { detail } => write!(f, "invalid input: {detail}"),
77            Self::Timeout => write!(f, "search exceeded its wall-clock deadline"),
78        }
79    }
80}
81
82impl std::error::Error for CspError {}
83
84impl CspError {
85    /// Stable machine-readable discriminant. This exact string is what
86    /// `py/errors.rs`'s exception class *names* are derived from and what a
87    /// wasm `CspJsError.code` carries across that boundary — the single
88    /// vocabulary every layer of the taxonomy shares.
89    pub const fn code(&self) -> &'static str {
90        match self {
91            Self::Unsatisfiable => "UNSATISFIABLE",
92            Self::BudgetExceeded => "BUDGET_EXCEEDED",
93            Self::InvalidInput { .. } => "INVALID_INPUT",
94            Self::Timeout => "TIMEOUT",
95        }
96    }
97
98    /// Convenience constructor — the one place `format!` call sites
99    /// collapse into, instead of each binding hand-rolling its own
100    /// `PyValueError::new_err(format!(...))` / `JsError::new(&format!(...))`.
101    pub fn invalid_input(detail: impl Into<String>) -> Self {
102        Self::InvalidInput {
103            detail: detail.into(),
104        }
105    }
106}
107
108/// The propagation layer's existing marker type converts losslessly — every
109/// current `?`-using call site (`Csp::propagate`, `Csp::propagate_with`)
110/// keeps compiling unchanged; only the bindings need to switch their
111/// `map_err` target.
112impl From<crate::Unsatisfiable> for CspError {
113    fn from(_: crate::Unsatisfiable) -> Self {
114        CspError::Unsatisfiable
115    }
116}
117
118/// `AssignmentBuilder`'s error family converts too, so `py/`/wasm call
119/// sites that touch the assignment/COP path get the same typed exceptions
120/// as the Sudoku path for free. Note this conversion is itself evidence of
121/// Pass-1 finding R8: `Infeasible` collapses onto `Unsatisfiable` here
122/// because `AssignmentError` has no distinct budget-exhaustion variant yet
123/// — fixing that is a separate, already ledgered item, not silently patched
124/// over by this mapping.
125impl From<crate::AssignmentError> for CspError {
126    fn from(e: crate::AssignmentError) -> Self {
127        match e {
128            crate::AssignmentError::Infeasible => CspError::Unsatisfiable,
129            other => CspError::invalid_input(other.to_string()),
130        }
131    }
132}