Skip to main content

feral_ordering_core/
lib.rs

1//! Shared contract types for FERAL's fill-reducing ordering crates.
2//!
3//! This crate exists so that `feral-amd`, `feral-metis`, `feral-scotch`,
4//! and `feral-kahip` all accept the same input type and emit the same
5//! stats / error types without a type-conversion layer at their
6//! boundary. The contract itself is documented in
7//! `dev/plans/ordering-crate-contract.md`.
8//!
9//! The public surface is deliberately minimal:
10//!
11//! - [`CscPattern`] — borrowed, full-symmetric, 0-based, `i32`-indexed.
12//! - [`OrderingStats`] — producer-agnostic diagnostic counters.
13//! - [`OrderingError`] — shared error shape.
14//! - [`CONTRACT_VERSION`] — bumped on any breaking change.
15//!
16//! Each ordering crate exposes exactly one contract-conforming
17//! function with the signature:
18//!
19//! ```ignore
20//! pub fn xxx_order(
21//!     pattern: &feral_ordering_core::CscPattern<'_>,
22//!     opts: &XxxOptions,
23//! ) -> Result<
24//!     (Vec<i32>, feral_ordering_core::OrderingStats, XxxStats),
25//!     feral_ordering_core::OrderingError,
26//! >;
27//! ```
28//!
29//! `perm[k] = j` means new index `k` corresponds to old index `j`
30//! (new-to-old). Callers that need the inverse compute it with a
31//! trivial helper.
32
33#![forbid(unsafe_code)]
34#![deny(missing_docs)]
35
36pub mod interrupt;
37pub mod quotient_graph;
38
39use core::fmt;
40
41/// Version of the shared ordering-crate contract.
42///
43/// Bumped on any breaking change to [`CscPattern`], [`OrderingStats`],
44/// [`OrderingError`], or the per-crate producer-function signature.
45/// Consumers can assert at build time that all linked ordering crates
46/// target the same contract version.
47pub const CONTRACT_VERSION: u32 = 1;
48
49/// Borrowed symmetric sparsity pattern in CSC form.
50///
51/// The pattern must be **full-symmetric** — both the upper and lower
52/// halves are present. Row indices within each column must be sorted
53/// in ascending order. Indices are 0-based.
54///
55/// Invariants (checked by [`CscPattern::new`]):
56///
57/// - `col_ptr.len() == n + 1`
58/// - `col_ptr[0] == 0`, `col_ptr` is non-decreasing
59/// - `row_idx.len() == col_ptr[n]`
60/// - every row index is in `0..n` (non-negative and `< n`)
61/// - row indices within each column are sorted ascending
62///
63/// Structural symmetry is the caller's responsibility and is not
64/// checked here; individual ordering crates may debug-assert it.
65#[derive(Debug, Clone, Copy)]
66pub struct CscPattern<'a> {
67    /// Matrix dimension.
68    pub n: usize,
69    /// Column pointers. Length `n + 1`.
70    pub col_ptr: &'a [i32],
71    /// Row indices. Length `col_ptr[n]`.
72    pub row_idx: &'a [i32],
73}
74
75impl<'a> CscPattern<'a> {
76    /// Construct a validated pattern.
77    ///
78    /// Returns `None` if the structural invariants above are
79    /// violated. Does not check symmetry.
80    pub fn new(n: usize, col_ptr: &'a [i32], row_idx: &'a [i32]) -> Option<Self> {
81        if col_ptr.len() != n + 1 {
82            return None;
83        }
84        if col_ptr[0] != 0 {
85            return None;
86        }
87        let nnz_i32 = *col_ptr.last()?;
88        if nnz_i32 < 0 {
89            return None;
90        }
91        let nnz = nnz_i32 as usize;
92        if row_idx.len() != nnz {
93            return None;
94        }
95        for w in col_ptr.windows(2) {
96            if w[1] < w[0] {
97                return None;
98            }
99        }
100        let n_i32: i32 = match i32::try_from(n) {
101            Ok(v) => v,
102            Err(_) => return None,
103        };
104        for &r in row_idx {
105            if r < 0 || r >= n_i32 {
106                return None;
107            }
108        }
109        // Row indices within each column must be sorted ascending. This is a
110        // documented precondition that downstream consumers silently rely on:
111        // feral-metis's adjacency builder dedups only *adjacent* duplicates
112        // (graph.rs), and feral-scotch's compress step inserts neighbours with
113        // `partition_point` assuming sorted runs. Unsorted rows would let a
114        // non-adjacent duplicate survive as a spurious edge, corrupting the
115        // graph. Enforce it here (O(nnz)) so every consumer can trust it.
116        for w in col_ptr.windows(2) {
117            let lo = w[0] as usize;
118            let hi = w[1] as usize;
119            if row_idx[lo..hi].windows(2).any(|p| p[1] < p[0]) {
120                return None;
121            }
122        }
123        Some(Self {
124            n,
125            col_ptr,
126            row_idx,
127        })
128    }
129
130    /// Number of stored nonzeros.
131    pub fn nnz(&self) -> usize {
132        self.row_idx.len()
133    }
134}
135
136/// Diagnostic counters shared by every ordering producer.
137///
138/// Crate-specific counters live in the crate's own stats struct
139/// (e.g. `AmdStats`, `MetisStats`) returned alongside this one, not
140/// inside it.
141#[derive(Debug, Default, Clone, PartialEq, Eq)]
142pub struct OrderingStats {
143    /// Wall-clock ordering time, microseconds.
144    pub time_us: u64,
145    /// Predicted non-zeros in L (upper bound if known).
146    ///
147    /// `None` when the algorithm does not produce an estimate.
148    /// AMD can populate this; METIS / Scotch / KaHIP typically
149    /// cannot without a follow-up symbolic pass.
150    pub fill_estimate: Option<u64>,
151    /// Predicted factorization flops. `None` when not produced.
152    pub flop_estimate: Option<u64>,
153}
154
155/// Shared error shape for the ordering-crate contract.
156///
157/// Crate-specific failure modes are carried via [`OrderingError::Internal`]
158/// rather than a wrapped crate-specific enum, to avoid an error-type
159/// dependency tree between the sibling crates.
160#[derive(Debug, Clone, PartialEq, Eq)]
161pub enum OrderingError {
162    /// Input failed [`CscPattern::new`] validation (wrong lengths,
163    /// out-of-range row indices, etc.).
164    MalformedInput,
165    /// Input pattern was not structurally symmetric. Debug-only
166    /// detection; release builds trust the caller.
167    NonSymmetric,
168    /// Index overflow in the crate's internal workspace (for
169    /// example, `i32` overflow on a very large matrix).
170    IndexOverflow,
171    /// Graph is disconnected and the crate does not handle
172    /// disconnected components in its current form.
173    DisconnectedGraph,
174    /// Crate-specific failure with a short static message. Keep
175    /// short — this is a status channel, not a rich diagnostic.
176    Internal(&'static str),
177    /// The active [`interrupt::Interrupt`] triggered (its deadline passed or
178    /// its cancel flag was set) before the ordering finished. No partial
179    /// result is returned.
180    Interrupted,
181}
182
183impl fmt::Display for OrderingError {
184    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185        match self {
186            Self::MalformedInput => f.write_str("ordering input failed structural validation"),
187            Self::NonSymmetric => {
188                f.write_str("ordering input pattern was not structurally symmetric")
189            }
190            Self::IndexOverflow => f.write_str("ordering workspace exceeded i32::MAX"),
191            Self::DisconnectedGraph => f.write_str("ordering input graph is disconnected"),
192            Self::Internal(msg) => write!(f, "ordering internal error: {msg}"),
193            Self::Interrupted => f.write_str("ordering interrupted (deadline or cancel flag)"),
194        }
195    }
196}
197
198impl std::error::Error for OrderingError {}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203
204    #[test]
205    fn contract_version_is_one() {
206        assert_eq!(CONTRACT_VERSION, 1);
207    }
208
209    #[test]
210    fn empty_pattern_ok() {
211        let cp = [0i32];
212        let ri: [i32; 0] = [];
213        let p = CscPattern::new(0, &cp, &ri).expect("n=0 pattern");
214        assert_eq!(p.n, 0);
215        assert_eq!(p.nnz(), 0);
216    }
217
218    #[test]
219    fn diagonal_2x2_ok() {
220        let cp = [0i32, 1, 2];
221        let ri = [0i32, 1];
222        let p = CscPattern::new(2, &cp, &ri).unwrap();
223        assert_eq!(p.nnz(), 2);
224    }
225
226    #[test]
227    fn rejects_bad_col_ptr_length() {
228        let cp = [0i32, 1];
229        let ri = [0i32];
230        assert!(CscPattern::new(2, &cp, &ri).is_none());
231    }
232
233    #[test]
234    fn rejects_oob_row_index() {
235        let cp = [0i32, 1];
236        let ri = [5i32];
237        assert!(CscPattern::new(1, &cp, &ri).is_none());
238    }
239
240    #[test]
241    fn rejects_negative_row_index() {
242        let cp = [0i32, 1];
243        let ri = [-1i32];
244        assert!(CscPattern::new(1, &cp, &ri).is_none());
245    }
246
247    #[test]
248    fn rejects_nonzero_first_col_ptr() {
249        let cp = [1i32, 2];
250        let ri = [0i32];
251        assert!(CscPattern::new(1, &cp, &ri).is_none());
252    }
253
254    #[test]
255    fn rejects_nonmonotone_col_ptr() {
256        let cp = [0i32, 2, 1];
257        let ri = [0i32, 0];
258        assert!(CscPattern::new(2, &cp, &ri).is_none());
259    }
260
261    #[test]
262    fn rejects_row_idx_length_mismatch() {
263        let cp = [0i32, 1, 2];
264        let ri = [0i32];
265        assert!(CscPattern::new(2, &cp, &ri).is_none());
266    }
267
268    #[test]
269    fn rejects_unsorted_rows_within_column() {
270        // Column 0 has rows [1, 0] — descending, violating the documented
271        // ascending-order invariant. `new` must reject it: feral-metis's
272        // adjacency builder dedups only *adjacent* duplicates, so unsorted
273        // rows would let a non-adjacent duplicate survive as a spurious edge.
274        let cp = [0i32, 2, 2];
275        let ri = [1i32, 0];
276        assert!(CscPattern::new(2, &cp, &ri).is_none());
277    }
278
279    #[test]
280    fn accepts_sorted_rows_with_adjacent_duplicate() {
281        // Ascending order permits adjacent duplicates; feral-metis drops them
282        // in its adjacency builder. `new` enforces sortedness, not
283        // strict-increase, so this must still be accepted.
284        let cp = [0i32, 3, 3];
285        let ri = [0i32, 0, 1];
286        assert!(CscPattern::new(2, &cp, &ri).is_some());
287    }
288
289    #[test]
290    fn rejects_negative_col_ptr_tail() {
291        // col_ptr.last() is negative → nnz would be invalid.
292        let cp = [0i32, -1];
293        let ri: [i32; 0] = [];
294        assert!(CscPattern::new(1, &cp, &ri).is_none());
295    }
296
297    #[test]
298    fn ordering_error_display_is_non_empty() {
299        for e in [
300            OrderingError::MalformedInput,
301            OrderingError::NonSymmetric,
302            OrderingError::IndexOverflow,
303            OrderingError::DisconnectedGraph,
304            OrderingError::Internal("boom"),
305        ] {
306            assert!(!format!("{e}").is_empty());
307        }
308    }
309
310    #[test]
311    fn ordering_stats_default_is_none_fields() {
312        let s = OrderingStats::default();
313        assert_eq!(s.time_us, 0);
314        assert!(s.fill_estimate.is_none());
315        assert!(s.flop_estimate.is_none());
316    }
317}