fsci-conformance 0.3.0

Differential conformance testing harness for FrankenSciPy
#![forbid(unsafe_code)]
//! Live SciPy differential coverage for `scipy.sparse.csgraph.floyd_warshall`.
//!
//! Resolves [frankenscipy-uuoet]. fsci_sparse::floyd_warshall(graph)
//! returns the all-pairs shortest-path distance matrix. Deterministic
//! O(V³) — exact agreement expected (1e-12 abs). Unreachable pairs are
//! represented as +∞ on both sides.

use std::collections::{BTreeMap, HashMap};
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use std::process::Stdio;
use std::time::{Instant, SystemTime, UNIX_EPOCH};

use fsci_conformance::{ArmCounts, CompareLedger};
use fsci_sparse::{CooMatrix, FormatConvertible, Shape2D, floyd_warshall};
use serde::{Deserialize, Serialize};

const PACKET_ID: &str = "FSCI-P2C-004";
const ABS_TOL: f64 = 1.0e-12;
const REQUIRE_SCIPY_ENV: &str = "FSCI_REQUIRE_SCIPY_ORACLE";

#[derive(Debug, Clone, Serialize)]
struct PointCase {
    case_id: String,
    n: usize,
    /// COO triplets (row, col, weight).
    edges: Vec<(usize, usize, f64)>,
    directed: bool,
}

#[derive(Debug, Clone, Serialize)]
struct OracleQuery {
    points: Vec<PointCase>,
}

#[derive(Debug, Clone, Deserialize)]
struct PointArm {
    case_id: String,
    /// Flattened n×n distance matrix; +inf encoded as a large sentinel
    /// (1e308) so JSON survives a round trip.
    values: Option<Vec<f64>>,
}

#[derive(Debug, Clone, Deserialize)]
struct OracleResult {
    points: Vec<PointArm>,
}

#[derive(Debug, Clone, Serialize)]
struct CaseDiff {
    case_id: String,
    abs_diff: f64,
    pass: bool,
}

#[derive(Debug, Clone, Serialize)]
struct DiffLog {
    test_id: String,
    category: String,
    case_count: usize,
    compared: BTreeMap<String, ArmCounts>,
    max_abs_diff: f64,
    pass: bool,
    timestamp_ms: u128,
    duration_ns: u128,
    cases: Vec<CaseDiff>,
}

fn output_dir() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(format!("fixtures/artifacts/{PACKET_ID}/diff"))
}

fn ensure_output_dir() {
    fs::create_dir_all(output_dir()).expect("create floyd_warshall diff output dir");
}

fn timestamp_ms() -> u128 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_millis())
}

fn emit_log(log: &DiffLog) {
    ensure_output_dir();
    let path = output_dir().join(format!("{}.json", log.test_id));
    let json = serde_json::to_string_pretty(log).expect("serialize floyd_warshall diff log");
    fs::write(path, json).expect("write floyd_warshall diff log");
}

const SENTINEL: f64 = 1.0e300;

fn finite_or_sentinel(v: f64) -> f64 {
    if v.is_infinite() { SENTINEL } else { v }
}

fn generate_query() -> OracleQuery {
    let points = vec![
        // 4-node weighted directed graph with a clear shortest-path structure.
        PointCase {
            case_id: "4node_directed".into(),
            n: 4,
            edges: vec![
                (0, 1, 1.0),
                (0, 2, 5.0),
                (1, 2, 2.0),
                (1, 3, 4.0),
                (2, 3, 1.0),
            ],
            directed: true,
        },
        // 5-node undirected graph: symmetric edges.
        PointCase {
            case_id: "5node_undirected".into(),
            n: 5,
            edges: vec![
                (0, 1, 3.0),
                (0, 2, 8.0),
                (1, 2, 2.0),
                (1, 3, 5.0),
                (2, 3, 1.0),
                (3, 4, 4.0),
                (2, 4, 7.0),
            ],
            directed: false,
        },
        // 3-node fully connected with small weights.
        PointCase {
            case_id: "3node_dense_directed".into(),
            n: 3,
            edges: vec![
                (0, 1, 1.5),
                (0, 2, 4.0),
                (1, 0, 2.0),
                (1, 2, 1.0),
                (2, 0, 3.0),
                (2, 1, 0.5),
            ],
            directed: true,
        },
        // 4-node with a disconnected component.
        PointCase {
            case_id: "4node_disconnected".into(),
            n: 4,
            edges: vec![(0, 1, 1.0), (1, 0, 1.0), (2, 3, 2.0), (3, 2, 2.0)],
            directed: true,
        },
    ];

    OracleQuery { points }
}

fn scipy_oracle_or_skip(query: &OracleQuery) -> Option<OracleResult> {
    let script = r#"
import json
import math
import sys
import numpy as np
import scipy.sparse as sp
from scipy.sparse.csgraph import floyd_warshall

SENTINEL = 1.0e300

def vec_or_none(arr):
    out = []
    for v in np.asarray(arr).flatten().tolist():
        try:
            v = float(v)
        except Exception:
            return None
        if math.isnan(v):
            return None
        out.append(SENTINEL if math.isinf(v) else v)
    return out

q = json.load(sys.stdin)
points = []
for case in q["points"]:
    cid = case["case_id"]
    n = case["n"]
    directed = case["directed"]
    edges = case["edges"]
    if edges:
        r = np.array([e[0] for e in edges], dtype=int)
        c = np.array([e[1] for e in edges], dtype=int)
        w = np.array([e[2] for e in edges], dtype=float)
    else:
        r = np.zeros(0, dtype=int); c = np.zeros(0, dtype=int); w = np.zeros(0, dtype=float)
    try:
        A = sp.csr_matrix((w, (r, c)), shape=(n, n))
        d = floyd_warshall(csgraph=A, directed=directed)
        points.append({"case_id": cid, "values": vec_or_none(d)})
    except Exception:
        points.append({"case_id": cid, "values": None})
print(json.dumps({"points": points}))
"#;
    let query_json = serde_json::to_string(query).expect("serialize floyd_warshall query");
    let mut child = match fsci_conformance::scipy_oracle_command()
        .arg("-c")
        .arg(script)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
    {
        Ok(c) => c,
        Err(e) => {
            assert!(
                std::env::var(REQUIRE_SCIPY_ENV).is_err(),
                "failed to spawn python3 for floyd_warshall oracle: {e}"
            );
            eprintln!("skipping floyd_warshall oracle: python3 not available ({e})");
            return None;
        }
    };
    {
        let stdin = child
            .stdin
            .as_mut()
            .expect("open floyd_warshall oracle stdin");
        if let Err(err) = stdin.write_all(query_json.as_bytes()) {
            let output = child.wait_with_output().expect("wait for failed oracle");
            let stderr = String::from_utf8_lossy(&output.stderr);
            assert!(
                std::env::var(REQUIRE_SCIPY_ENV).is_err(),
                "floyd_warshall oracle stdin write failed: {err}; stderr: {stderr}"
            );
            eprintln!("skipping floyd_warshall oracle: stdin write failed ({err})\n{stderr}");
            return None;
        }
    }
    let output = child
        .wait_with_output()
        .expect("wait for floyd_warshall oracle");
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            std::env::var(REQUIRE_SCIPY_ENV).is_err(),
            "floyd_warshall oracle failed: {stderr}"
        );
        eprintln!("skipping floyd_warshall oracle: scipy not available\n{stderr}");
        return None;
    }
    let stdout = String::from_utf8_lossy(&output.stdout);
    Some(serde_json::from_str(&stdout).expect("parse floyd_warshall oracle JSON"))
}

fn fsci_eval(case: &PointCase) -> Option<Vec<f64>> {
    let mut r: Vec<usize> = case.edges.iter().map(|e| e.0).collect();
    let mut c: Vec<usize> = case.edges.iter().map(|e| e.1).collect();
    let mut w: Vec<f64> = case.edges.iter().map(|e| e.2).collect();

    // For undirected graphs, scipy with directed=False uses the graph as-is
    // but interprets each edge as bidirectional. fsci's floyd_warshall always
    // treats the matrix as the adjacency matrix of a directed graph, so we
    // symmetrize the input here to match scipy's semantics.
    if !case.directed {
        let edges = case.edges.clone();
        for (u, v, weight) in edges {
            if u != v {
                r.push(v);
                c.push(u);
                w.push(weight);
            }
        }
    }

    let coo = CooMatrix::from_triplets(Shape2D::new(case.n, case.n), w, r, c, false).ok()?;
    let csr = coo.to_csr().ok()?;
    let dist_matrix = floyd_warshall(&csr, case.directed).ok()?;
    let mut flat = Vec::with_capacity(case.n * case.n);
    for row in &dist_matrix {
        for &v in row {
            flat.push(finite_or_sentinel(v));
        }
    }
    Some(flat)
}

#[test]
fn diff_sparse_floyd_warshall() {
    let query = generate_query();
    let Some(oracle) = scipy_oracle_or_skip(&query) else {
        return;
    };
    assert_eq!(oracle.points.len(), query.points.len());

    let pmap: HashMap<String, PointArm> = oracle
        .points
        .into_iter()
        .map(|r| (r.case_id.clone(), r))
        .collect();

    let start = Instant::now();
    let mut diffs = Vec::new();
    let mut max_overall = 0.0_f64;
    let mut ledger = CompareLedger::new("diff_sparse_floyd_warshall", &["floyd_warshall"]);

    for case in &query.points {
        let scipy_arm = pmap.get(&case.case_id).expect("validated oracle");
        let fsci_v = fsci_eval(case);
        let Some((scipy_v, fsci_v)) = ledger.slices(
            "floyd_warshall",
            &case.case_id,
            scipy_arm.values.as_deref(),
            fsci_v.as_deref(),
        ) else {
            continue;
        };
        let abs_d = fsci_v
            .iter()
            .zip(scipy_v.iter())
            .map(|(a, b)| (a - b).abs())
            .fold(0.0_f64, f64::max);
        max_overall = max_overall.max(abs_d);
        ledger.compared("floyd_warshall", &case.case_id, abs_d <= ABS_TOL);
        diffs.push(CaseDiff {
            case_id: case.case_id.clone(),
            abs_diff: abs_d,
            pass: abs_d <= ABS_TOL,
        });
    }

    let all_pass = diffs.iter().all(|d| d.pass);

    let log = DiffLog {
        test_id: "diff_sparse_floyd_warshall".into(),
        category: "scipy.sparse.csgraph.floyd_warshall".into(),
        case_count: diffs.len(),
        compared: ledger.counts().clone(),
        max_abs_diff: max_overall,
        pass: all_pass,
        timestamp_ms: timestamp_ms(),
        duration_ns: start.elapsed().as_nanos(),
        cases: diffs.clone(),
    };
    emit_log(&log);

    for d in &diffs {
        if !d.pass {
            eprintln!(
                "floyd_warshall mismatch: {} abs_diff={}",
                d.case_id, d.abs_diff
            );
        }
    }

    assert!(
        all_pass,
        "scipy.sparse.csgraph.floyd_warshall conformance failed: {} cases, max_diff={}",
        diffs.len(),
        max_overall
    );
    ledger.finish(query.points.len());
}